text:
let request = require('request');
let cheerio = require('cheerio');
let iconv = require('iconv-lite');
let fs = require('fs');
let debug = require('debug')('logger:read');

exports.readJS = function (url, callback) {
    request(url, function (err, response, body) {
        if (!err && response.statusCode == 200) {
            let $ = cheerio.load(body);
            let noteLists = [];
            $('#list-container .note-list li').each(function (index, item) {
                let $item = $(item);
                let noteList = {
                    url: `${url}${$item.find('.wrap-img').attr('href')}`,
                    imgSrc: $item.find('.wrap-img img').attr('src'),
                    author: $item.find('.author .name .blue-link').text(),
                    authorUrl: `${url}${$item.find('.author .name .blue-link').attr('href')}`,
                    avatarSrc: $('.author .avatar img').attr('src'),
                    createAt: $('.author .name .time').attr('data-shared-at'),
                    title: $item.find('.content .title').text(),
                    abstract:$item.find('.content .abstract').text(),
                    category:$item.find('.content .collection-tag').text(),
                    categoryUrl:`${url}${$item.find('.content .collection-tag').attr('href')}`
                };
                debug(`正在读数据:${noteList.title}`);
                noteLists.push(noteList);
            });
            callback(null,noteLists);
        }else {
            callback(err);
        }
    });
};

redpajama_set_name: RedPajamaGithub


text:
// DecentCMS (c) 2014 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details.
'use strict';
// TODO: resolve culture dynamically
// TODO: format strings have positional placeholders
// TODO: handling plurals
// TODO: handling completely custom string selection logic
// TODO: persist default strings as they are used to the default translation files
var format = require('util').format;

/**
 * @description
 * Provides the translation of the provided string in the current culture.
 *
 * @param {String} defaultString  The string to translate in the default en-US culture.
 */
function t(defaultString) {
  var translation = t.resolve(defaultString, 'en-US');
  if (arguments.length == 1) return translation;
  var args = Array.prototype.slice.call(arguments, 0);
  args[0] = translation;
  return format.apply(null, args);
}

t.feature = 'localization';
t.service = 'localization';
t.isStatic = true;
t.scope = 'shell';

/**
 * @description
 * Broadcasts calls for resolving string translations.
 * Don't call directly. Used internally by t.
 *
 * @param {String} defaultString the string to translate.
 * @param {String} culture       the culture for which a translation is required.
 */
t.resolve = function(defaultString, culture) {
  var translationEventPayload = {
    defaultString: defaultString,
    culture: culture,
    translation: null
  };
  t.translationProviders.forEach(function(provider) {
    provider(translationEventPayload);
  });
  return translationEventPayload.translation || defaultString;
};

t.translationProviders = [];

module.exports = t;


text:
namespace gfx {

GLContextWGL::GLContextWGL(GLShareGroup* share_group)
    : GLContextReal(share_group),
      context_(NULL) {
}

GLContextWGL::~GLContextWGL() {
  Destroy();
}

std::string GLContextWGL::GetExtensions() {
  const char* extensions = NULL;
  if (g_driver_wgl.fn.wglGetExtensionsStringARBFn)
    extensions = wglGetExtensionsStringARB(GLSurfaceWGL::GetDisplayDC());
  else if (g_driver_wgl.fn.wglGetExtensionsStringEXTFn)
    extensions = wglGetExtensionsStringEXT();

  if (extensions)
    return GLContext::GetExtensions() + " " + extensions;

  return GLContext::GetExtensions();
}

bool GLContextWGL::Initialize(
    GLSurface* compatible_surface, GpuPreference gpu_preference) {
  // Get the handle of another initialized context in the share group _before_
  // setting context_. Otherwise this context will be considered initialized
  // and could potentially be returned by GetHandle.
  HGLRC share_handle = static_cast<HGLRC>(share_group()->GetHandle());

  context_ = wglCreateContext(
      static_cast<HDC>(compatible_surface->GetHandle()));
  if (!context_) {
    LOG(ERROR) << "Failed to create GL context.";
    Destroy();
    return false;
  }

  if (share_handle) {
    if (!wglShareLists(share_handle, context_)) {
      LOG(ERROR) << "Could not share GL contexts.";
      Destroy();
      return false;
    }
  }

  return true;
}

void GLContextWGL::Destroy() {
  if (context_) {
    wglDeleteContext(context_);
    context_ = NULL;
  }
}

bool GLContextWGL::MakeCurrent(GLSurface* surface) {
  DCHECK(context_);
  if (IsCurrent(surface))
    return true;

  ScopedReleaseCurrent release_current;
  TRACE_EVENT0("gpu", "GLContextWGL::MakeCurrent");

  if (!wglMakeCurrent(static_cast<HDC>(surface->GetHandle()), context_)) {
    LOG(ERROR) << "Unable to make gl context current.";
    return false;
  }

  // Set this as soon as the context is current, since we might call into GL.
  SetRealGLApi();

  SetCurrent(surface);
  if (!InitializeDynamicBindings()) {
    return false;
  }

  if (!surface->OnMakeCurrent(this)) {
    LOG(ERROR) << "Could not make current.";
    return false;
  }

  release_current.Cancel();
  return true;
}

void GLContextWGL::ReleaseCurrent(GLSurface* surface) {
  if (!IsCurrent(surface))
    return;

  SetCurrent(NULL);
  wglMakeCurrent(NULL, NULL);
}

bool GLContextWGL::IsCurrent(GLSurface* surface) {
  bool native_context_is_current =
      wglGetCurrentContext() == context_;

  // If our context is current then our notion of which GLContext is
  // current must be correct. On the other hand, third-party code
  // using OpenGL might change the current context.
  DCHECK(!native_context_is_current || (GetRealCurrent() == this));

  if (!native_context_is_current)
    return false;

  if (surface) {
    if (wglGetCurrentDC() != surface->GetHandle())
      return false;
  }

  return true;
}

void* GLContextWGL::GetHandle() {
  return context_;
}

void GLContextWGL::OnSetSwapInterval(int interval) {
  DCHECK(IsCurrent(NULL));
  if (gfx::g_driver_wgl.ext.b_WGL_EXT_swap_control) {
    wglSwapIntervalEXT(interval);
  } else {
      LOG(WARNING) <<
          "Could not disable vsync: driver does not "
          "support WGL_EXT_swap_control";
  }
}

}  // namespace gfx


text:
class GURL;

namespace dom_storage {

class DomStorageArea;
class DomStorageTaskRunner;
class SessionStorageDatabase;

// Container for the set of per-origin Areas.
// See class comments for DomStorageContext for a larger overview.
class WEBKIT_STORAGE_EXPORT DomStorageNamespace
    : public base::RefCountedThreadSafe<DomStorageNamespace> {
 public:
  // Option for PurgeMemory.
  enum PurgeOption {
    // Purge unopened areas only.
    PURGE_UNOPENED,

    // Purge aggressively, i.e. discard cache even for areas that have
    // non-zero open count.
    PURGE_AGGRESSIVE,
  };

  // Constructor for a LocalStorage namespace with id of 0
  // and an optional backing directory on disk.
  DomStorageNamespace(const base::FilePath& directory,  // may be empty
                      DomStorageTaskRunner* task_runner);

  // Constructor for a SessionStorage namespace with a non-zero id and an
  // optional backing on disk via |session_storage_database| (may be NULL).
  DomStorageNamespace(int64 namespace_id,
                      const std::string& persistent_namespace_id,
                      SessionStorageDatabase* session_storage_database,
                      DomStorageTaskRunner* task_runner);

  int64 namespace_id() const { return namespace_id_; }
  const std::string& persistent_namespace_id() const {
    return persistent_namespace_id_;
  }

  // Returns the storage area for the given origin,
  // creating instance if needed. Each call to open
  // must be balanced with a call to CloseStorageArea.
  DomStorageArea* OpenStorageArea(const GURL& origin);
  void CloseStorageArea(DomStorageArea* area);

  // Returns the area for |origin| if it's open, otherwise NULL.
  DomStorageArea* GetOpenStorageArea(const GURL& origin);

  // Creates a clone of |this| namespace including
  // shallow copies of all contained areas.
  // Should only be called for session storage namespaces.
  DomStorageNamespace* Clone(int64 clone_namespace_id,
                             const std::string& clone_persistent_namespace_id);

  void DeleteLocalStorageOrigin(const GURL& origin);
  void DeleteSessionStorageOrigin(const GURL& origin);
  void PurgeMemory(PurgeOption purge);
  void Shutdown();

  unsigned int CountInMemoryAreas() const;

 private:
  friend class base::RefCountedThreadSafe<DomStorageNamespace>;

  // Struct to hold references to our contained areas and
  // to keep track of how many tabs have a given area open.
  struct AreaHolder {
    scoped_refptr<DomStorageArea> area_;
    int open_count_;
    AreaHolder();
    AreaHolder(DomStorageArea* area, int count);
    ~AreaHolder();
  };
  typedef std::map<GURL, AreaHolder> AreaMap;

  ~DomStorageNamespace();

  // Returns a pointer to the area holder in our map or NULL.
  AreaHolder* GetAreaHolder(const GURL& origin);

  int64 namespace_id_;
  std::string persistent_namespace_id_;
  base::FilePath directory_;
  AreaMap areas_;
  scoped_refptr<DomStorageTaskRunner> task_runner_;
  scoped_refptr<SessionStorageDatabase> session_storage_database_;
};

}  // namespace dom_storage

#endif  // WEBKIT_DOM_STORAGE_DOM_STORAGE_NAMESPACE_H_


text:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class CommandService {

  private commandsSource = new Subject<string>();
  public commandsSource$ = this.commandsSource.asObservable();

  sendCommand(command: string) {
    this.commandsSource.next(command);
  }
}


text:
<?php

namespace Glow\Auth\Notifications;

use Illuminate\Auth\Notifications\ResetPassword as IlluminateResetPassword;
use Illuminate\Notifications\Messages\MailMessage;

class ResetPassword extends IlluminateResetPassword
{

    /**
     * Build the reset password url
     *
     * @return string
     */
    public function url() {

        return url(config('app.url') . route('password.reset', $this->token, false));
    }

    /**
     * Build the mail representation of the notification.
     *
     * @param  mixed $notifiable
     *
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable) {

        return (new MailMessage)
            ->line('You are receiving this email because we received a password reset request for your account.')
            ->action('Reset Password', $this->url())
            ->line('If you did not request a password reset, no further action is required.');
    }
}


text:
import collections
import datetime
import json
import operator
import time

import flask
import six

from stackalytics.dashboard import decorators
from stackalytics.dashboard import helpers
from stackalytics.dashboard import parameters
from stackalytics.dashboard import vault
from stackalytics.processor import utils

DEFAULT_DAYS_COUNT = 7
FIRST_MEMBER_DATE = "2012-Jul-18"

blueprint = flask.Blueprint('reports', __name__, url_prefix='/report')

@blueprint.route('/blueprint/<module>/<blueprint_name>')
@decorators.templated()
@decorators.exception_handler()
def blueprint_summary(module, blueprint_name):
    blueprint_id = utils.get_blueprint_id(module, blueprint_name)
    bpd = vault.get_memory_storage().get_record_by_primary_key(
        'bpd:' + blueprint_id)
    if not bpd:
        flask.abort(404)
        return

    bpd = helpers.extend_record(bpd)
    record_ids = vault.get_memory_storage().get_record_ids_by_blueprint_ids(
        [blueprint_id])
    activity = [helpers.extend_record(record) for record in
                vault.get_memory_storage().get_records(record_ids)]
    activity.sort(key=lambda x: x['date'], reverse=True)

    return {'blueprint': bpd, 'activity': activity}

def _get_day(timestamp, time_now):
    return int((time_now - timestamp) / 60 / 60 / 24)

def _process_stat(data, key, time_now):
    if not data:
        return None

    data = sorted(data, key=operator.itemgetter(key))

    days = _get_day(data[0][key], time_now)
    chart_data = [0] * (days + 1)
    sum_ages = 0
    for review in data:
        age = time_now - review[key]
        sum_ages += age
        review[key + '_age'] = utils.make_age_string(age)
        chart_data[_get_day(review[key], time_now)] += 1

    return {
        'reviews': data,
        'average': utils.make_age_string(sum_ages / len(data)),
        'max': data[0][key + '_age'],
        'chart_data': json.dumps(chart_data),
    }

@blueprint.route('/reviews/<module>/open')
@decorators.templated()
@decorators.exception_handler()
def open_reviews(module):
    memory_storage_inst = vault.get_memory_storage()
    time_now = int(time.time())

    module_id_index = vault.get_vault()['module_id_index']
    module = module.lower()
    if module not in module_id_index:
        flask.abort(404)

    modules = module_id_index[module]['modules']

    review_ids = (memory_storage_inst.get_record_ids_by_modules(modules) &
                  memory_storage_inst.get_record_ids_by_types(['review']))

    waiting_on_reviewer = []
    waiting_on_submitter = []
    total_open = 0

    for review in memory_storage_inst.get_records(review_ids):
        if review.status == 'NEW':
            total_open += 1

            # review.value is minimum from votes made for the latest patch
            if review.value in [1, 2]:
                # CI or engineer liked this change request, waiting for someone
                # to merge or to put dislike
                waiting_on_reviewer.append(helpers.extend_record(review))
            elif review.value in [-1, -2]:
                # CI or reviewer do not like this, waiting for submitter to fix
                waiting_on_submitter.append(helpers.extend_record(review))
            else:
                # new requests without votes, waiting for CI
                pass

    return {
        'module': module,
        'total_open': total_open,
        'waiting_on_reviewer': len(waiting_on_reviewer),
        'waiting_on_submitter': len(waiting_on_submitter),
        'waiting_on_ci': (total_open - len(waiting_on_reviewer) -
                          len(waiting_on_submitter)),
        'reviewer_latest_revision': _process_stat(
            waiting_on_reviewer, 'updated_on', time_now),
        'reviewer_first_revision': _process_stat(
            waiting_on_reviewer, 'date', time_now),
        'submitter_latest_revision': _process_stat(
            waiting_on_submitter, 'updated_on', time_now),
        'submitter_first_revision': _process_stat(
            waiting_on_submitter, 'date', time_now),
    }

@blueprint.route('/contribution/<module>/<days>')
@decorators.templated()
@decorators.exception_handler()
def contribution(module, days):
    return {
        'module': module,
        'days': days,
        'start_date': int(time.time()) - int(days) * 24 * 60 * 60
    }

@blueprint.route('/ci/<module>/<days>')
@decorators.templated()
@decorators.exception_handler()
def external_ci(module, days):
    if int(days) > 30:
        days = 30

    return {
        'module': module,
        'days': days,
        'start_date': int(time.time()) - int(days) * 24 * 60 * 60
    }

@blueprint.route('/members')
@decorators.exception_handler()
@decorators.templated()
def members():
    days = int(flask.request.args.get('days') or DEFAULT_DAYS_COUNT)
    all_days = int(time.time() - utils.date_to_timestamp_ext(
        FIRST_MEMBER_DATE)) / (24 * 60 * 60) + 1

    return {
        'days': days,
        'all_days': all_days
    }

@blueprint.route('/affiliation_changes')
@decorators.exception_handler()
@decorators.templated()
def affiliation_changes():
    start_days = str(flask.request.args.get('start_days') or
                     utils.timestamp_to_date(int(time.time()) -
                                             365 * 24 * 60 * 60))
    end_days = str(flask.request.args.get('end_days') or
                   utils.timestamp_to_date(int(time.time())))

    return {
        'start_days': start_days,
        'end_days': end_days,
    }

@blueprint.route('/cores')
@decorators.exception_handler()
@decorators.templated()
def cores():
    project_type = parameters.get_single_parameter({}, 'project_type')
    return {
        'project_type': project_type,
    }

def _get_punch_card_data(records):
    punch_card_raw = []  # matrix days x hours
    for wday in six.moves.range(0, 7):
        punch_card_raw.append([0] * 24)
    for record in records:
        tt = datetime.datetime.fromtimestamp(record.date).timetuple()
        punch_card_raw[tt.tm_wday][tt.tm_hour] += 1

    punch_card_data = []  # format for jqplot bubble renderer
    for wday in six.moves.range(0, 7):
        for hour in six.moves.range(0, 24):
            v = punch_card_raw[wday][hour]
            if v:
                punch_card_data.append([hour, wday, v, v])

    # add corner point, otherwise chart doesn't know the bounds
    if punch_card_raw[0][0] == 0:
        punch_card_data.append([0, 0, 0, 0])
    if punch_card_raw[6][23] == 0:
        punch_card_data.append([23, 6, 0, 0])

    return json.dumps(punch_card_data)

def _get_activity_summary(record_ids):
    memory_storage_inst = vault.get_memory_storage()

    record_ids_by_type = memory_storage_inst.get_record_ids_by_types(
        ['mark', 'patch', 'email', 'bpd', 'bpc', 'ci_vote'])

    record_ids &= record_ids_by_type
    punch_card_data = _get_punch_card_data(
        memory_storage_inst.get_records(record_ids))

    return {
        'punch_card_data': punch_card_data,
    }

@blueprint.route('/users/<user_id>')
@decorators.templated()
@decorators.exception_handler()
def user_activity(user_id):
    user = vault.get_user_from_runtime_storage(user_id)
    if not user:
        flask.abort(404)
    user = helpers.extend_user(user)

    memory_storage_inst = vault.get_memory_storage()
    result = _get_activity_summary(
        memory_storage_inst.get_record_ids_by_user_ids([user_id]))
    result['user'] = user

    return result

@blueprint.route('/companies/<company>')
@decorators.templated()
@decorators.exception_handler()
def company_activity(company):
    memory_storage_inst = vault.get_memory_storage()
    original_name = memory_storage_inst.get_original_company_name(company)

    result = _get_activity_summary(
        memory_storage_inst.get_record_ids_by_companies([original_name]))
    result['company_name'] = original_name

    return result

@blueprint.route('/activity')
@decorators.templated()
@decorators.exception_handler()
def activity():
    pass

@blueprint.route('/large_commits')
@decorators.response()
@decorators.jsonify('commits')
@decorators.exception_handler()
@decorators.record_filter()
def get_commit_report(records, **kwargs):
    loc_threshold = int(flask.request.args.get('loc_threshold') or 0)
    response = []
    for record in records:
        if ('loc' in record) and (record['loc'] > loc_threshold):
            nr = dict([(k, record[k])
                       for k in ['loc', 'subject', 'module', 'primary_key',
                                 'change_id']
                       if k in record])
            response.append(nr)
    return response

@blueprint.route('/single_plus_two_reviews')
@decorators.response()
@decorators.jsonify()
@decorators.exception_handler()
@decorators.record_filter(ignore='metric')
def get_single_plus_two_reviews_report(records, **kwargs):
    memory_storage_inst = vault.get_memory_storage()
    plus_twos = collections.defaultdict(list)
    for record in records:
        if record['record_type'] != 'mark':
            continue

        if (record['branch'] == 'master' and
                record['type'] == 'Code-Review' and record['value'] == +2):
            review_id = record['review_id']
            review = memory_storage_inst.get_record_by_primary_key(review_id)
            if review and review['status'] == 'MERGED':
                plus_twos[review_id].append(record)

    response = []
    for review_id in plus_twos.keys():
        if len(plus_twos[review_id]) < 2:
            mark = plus_twos[review_id][0]
            review = memory_storage_inst.get_record_by_primary_key(
                mark['review_id'])
            response.append({'review_by': review['user_id'],
                             'mark_by': mark['user_id'],
                             'subject': review['subject'],
                             'url': review['url'],
                             'project': review['project']})

    return response

@blueprint.route('/driverlog')
@decorators.templated()
@decorators.exception_handler()
def driverlog():
    pass


text:
package scriptella.driver.shell;

import scriptella.AbstractTestCase;
import scriptella.execution.EtlExecutor;
import scriptella.execution.EtlExecutorException;
import scriptella.spi.MockConnectionParameters;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.regex.Pattern;

/**
 * Integration test for shell script/queries
 *
 * @author Fyodor Kupolov
 * @version 1.0
 */
public class ShellDriverITest extends AbstractTestCase {
    private ByteArrayOutputStream o1;
    private ByteArrayOutputStream o2;

    protected void setUp() throws Exception {

        testURLHandler = new TestURLHandler() {
            public InputStream getInputStream(final URL u) {
                throw new UnsupportedOperationException();
            }

            public OutputStream getOutputStream(final URL u) {
                if (u.toString().endsWith("2")) {
                    return o2 = new ByteArrayOutputStream();
                } else {
                    return o1 = new ByteArrayOutputStream();
                }
            }

            public int getContentLength(final URL u) {
                return -1;
            }
        };
    }

    public void test() throws EtlExecutorException, UnsupportedEncodingException {
        EtlExecutor e = newEtlExecutor();
        e.execute();
        assertNotNull(o1);
        assertNotNull(o2);
        String outputStr = new String(o1.toByteArray());
        // Normally unit tests should not rely on the running environment
        // but this is an integration test, so we actually verify that behavior is OS specific
        assertTrue("Unexpected output: '" + outputStr + "'", outputStr.contains("Running"));

        // Check that only one Running word appears
        int running = outputStr.replace("Running", "").length();
        assertEquals("Unexpected format - " + outputStr, "Running".length(),outputStr.length() - running);

        ShellConnectionParameters p = new ShellConnectionParameters(new MockConnectionParameters());
        String expectedOsName = p.getOsBehavior().name().toLowerCase();
        assertTrue("Expected " + expectedOsName + ", but found " + outputStr, outputStr.toLowerCase().contains(expectedOsName));

        // Now verify the query
        outputStr = new String(o2.toByteArray());
        Pattern expected = Pattern.compile("\\s*Exported Line1\\s*Exported Line2\\s*Done\\s*");
        assertTrue("Unexpected result: " + outputStr, expected.matcher(outputStr).matches());
    }

}


text:
<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Spinner</title>

  <link href='//fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en' rel='stylesheet' type='text/css'>

  <link rel="stylesheet" href="../../css/material.css">
  <link rel="stylesheet" href="style.css">

      Default:

      Single color (uses primary palette):


text:
package forklift.integration.server;

import forklift.Forklift;
import forklift.connectors.KafkaConnector;
import forklift.exception.StartupException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.net.telnet.TelnetClient;
import org.apache.kafka.common.errors.InterruptException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Contains all of the necessary connection management code that tests
 * need in order to run against the kafka, zookeeper, and schema registry.
 *
 * @author mconroy
 * @author afrieze
 */
public class TestServiceManager {
    private static final Logger log = LoggerFactory.getLogger(TestServiceManager.class);
    private ExecutorService executor = Executors.newFixedThreadPool(3);
    private  ZookeeperService zookeeper;
    private  KafkaService kafka;
    private  SchemaRegistryService schemaRegistry;
    private  KafkaConnector connector;
    private  TelnetClient telnet;
    private  int zookeeperPort = 42181;
    private  int kafkaPort = 49092;
    private  int schemaPort = 58081;
    private  List<Forklift> forklifts = new ArrayList<>();

    public void start() {

        try {
            zookeeper = new ZookeeperService(zookeeperPort);
            kafka = new KafkaService(zookeeperPort, kafkaPort);
            schemaRegistry = new SchemaRegistryService(zookeeperPort, schemaPort);

            this.removeDataDirectories();
            executor.execute(zookeeper);
            waitService("127.0.0.1", zookeeperPort);
            executor.execute(kafka);
            waitService("127.0.0.1", kafkaPort);
            Thread.sleep(2000); //kafka doesn't seem to be quite ready after it starts listening on its port
            executor.execute(schemaRegistry);
            waitService("127.0.0.1", schemaPort);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    private void waitService(String host, int port) throws InterruptedException {
        telnet = new TelnetClient();
        int triesLeft = 100;
        while (triesLeft > 0)
            try {
                telnet.connect(host, port);
                triesLeft = 0;
                telnet.disconnect();
            } catch (Exception e) {
                Thread.sleep(50);
                triesLeft--;
            }
    }

    public void stop() {

        // Kill the broker and cleanup the testing data.
        try {
            forklifts.forEach(forklift -> forklift.shutdown());
            schemaRegistry.stop();
            kafka.stop();
            zookeeper.stop();
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            removeDataDirectories();
        }
    }
    public void removeDataDirectories(){
        try {
            removeDirectory(kafka.getDataDirectoryFile());
            removeDirectory(zookeeper.getDataDirectoryFile());
        } catch (Exception e) {

        }
    }

    private void removeDirectory(File file) throws InterruptedException{
        int retries = 5;
        while(retries > 0){
            try {
                FileUtils.deleteDirectory(file);
                retries = 0;
            } catch (IOException e) {
                retries--;
                Thread.sleep(1000);
            }
        }
    }

    public Forklift newManagedForkliftInstance() throws StartupException {
        return newManagedForkliftInstance("");
    }

    public Forklift newManagedForkliftInstance(String controllerName) throws StartupException {
        // Verify that we can get a kafka connection to the broker.
        String kafkaUri = "127.0.0.1:" + kafkaPort;
        String schemaUrl = "http://127.0.0.1:" + schemaPort;
        connector = new KafkaConnector(kafkaUri, schemaUrl, "testGroup");
        Forklift forklift = new Forklift();
        forklift.start(connector);
        forklifts.add(forklift);
        return forklift;
    }
}


text:
module Gisele
  module Language
    module Syntax
      module WhenClause
        include Node

        def _to_ast
          cond = captures[:bool_expr].first.to_ast
          dost = captures[:process_statement].first.to_ast
          [:when_clause, cond, dost]
        end

      end # module WhenClause
    end # module Syntax
  end # module Language
end # module Gisele


text:
'''
    :codeauthor: :email:`Jayesh Kariya <jayeshk@saltstack.com>`
'''

# Import Python Libs
from __future__ import absolute_import

# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.mock import (
    MagicMock,
    patch,
    NO_MOCK,
    NO_MOCK_REASON
)
from salttesting.helpers import ensure_in_syspath

ensure_in_syspath('../../')

# Import Salt Libs
from salt.modules import logrotate

# Globals
logrotate.__salt__ = {}

@skipIf(NO_MOCK, NO_MOCK_REASON)
class LogrotateTestCase(TestCase):
    '''
    Test cases for salt.modules.logrotate
    '''
    # 'show_conf' function tests: 1

    @patch('salt.modules.logrotate._parse_conf',
           MagicMock(return_value=True))
    def test_show_conf(self):
        '''
        Test if it show parsed configuration
        '''
        self.assertTrue(logrotate.show_conf())

    # 'set_' function tests: 2

    @patch('salt.modules.logrotate._parse_conf',
           MagicMock(return_value={'include files': {'include': 'A'},
                                   'rotate': {'salt': 'A'}}))
    def test_set(self):
        '''
        Test if it set a new value for a specific configuration line
        '''
        ret = (
               'Error: rotate includes a dict, and a specific '
               'setting inside the dict was not declared'
               )
        self.assertEqual(logrotate.set_('rotate', '2'), ret)

    @patch('salt.modules.logrotate._parse_conf',
           MagicMock(return_value={'include files': {'include': 'A'},
                                   'rotate': 'salt'}))
    def test_set_setting(self):
        '''
        Test if it set a new value for a specific configuration line
        '''
        ret = (
               'Error: A setting for a dict was declared, '
               'but the configuration line given is not a dict'
               )
        self.assertEqual(logrotate.set_('rotate', '2', True), ret)

if __name__ == '__main__':
    from integration import run_tests
    run_tests(LogrotateTestCase, needs_daemon=False)


text:
@interface CKComponent(Injected)

@property (nonatomic, readonly) CSComponent *wrapper;

- (void)setWrapperStrongly:(CSComponent *)wrapper;
- (void)setWrapperWeakly:(CSComponent *)wrapper;

- (id)nextResponderSkippedWrapper;

@end


text:
using ::testing::InSequence;
using ::testing::StrictMock;
using ::testing::Values;

namespace media {

typedef StreamParser::BufferQueue BufferQueue;
typedef StreamParser::TrackId TrackId;

// Used for setting expectations on callbacks. Using a StrictMock also lets us
// test for missing or extra callbacks.
class FrameProcessorTestCallbackHelper {
 public:
  FrameProcessorTestCallbackHelper() {}
  virtual ~FrameProcessorTestCallbackHelper() {}

  MOCK_METHOD1(PossibleDurationIncrease, void(base::TimeDelta new_duration));

  // Helper that calls the mock method as well as does basic sanity checks on
  // |new_duration|.
  void OnPossibleDurationIncrease(base::TimeDelta new_duration) {
    PossibleDurationIncrease(new_duration);
    ASSERT_NE(kNoTimestamp, new_duration);
    ASSERT_NE(kInfiniteDuration, new_duration);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(FrameProcessorTestCallbackHelper);
};

// Test parameter determines indicates if the TEST_P instance is targeted for
// sequence mode (if true), or segments mode (if false).
class FrameProcessorTest : public testing::TestWithParam<bool> {
 protected:
  FrameProcessorTest()
      : frame_processor_(new FrameProcessor(
            base::Bind(
                &FrameProcessorTestCallbackHelper::OnPossibleDurationIncrease,
                base::Unretained(&callbacks_)),
            new MediaLog())),
        append_window_end_(kInfiniteDuration),
        frame_duration_(base::TimeDelta::FromMilliseconds(10)),
        audio_id_(1),
        video_id_(2) {}

  enum StreamFlags {
    HAS_AUDIO = 1 << 0,
    HAS_VIDEO = 1 << 1
  };

  void AddTestTracks(int stream_flags) {
    const bool has_audio = (stream_flags & HAS_AUDIO) != 0;
    const bool has_video = (stream_flags & HAS_VIDEO) != 0;
    ASSERT_TRUE(has_audio || has_video);

    if (has_audio) {
      CreateAndConfigureStream(DemuxerStream::AUDIO);
      ASSERT_TRUE(audio_);
      EXPECT_TRUE(frame_processor_->AddTrack(audio_id_, audio_.get()));
      seek(audio_.get(), base::TimeDelta());
    }
    if (has_video) {
      CreateAndConfigureStream(DemuxerStream::VIDEO);
      ASSERT_TRUE(video_);
      EXPECT_TRUE(frame_processor_->AddTrack(video_id_, video_.get()));
      seek(video_.get(), base::TimeDelta());
    }
  }

  void SetTimestampOffset(base::TimeDelta new_offset) {
    timestamp_offset_ = new_offset;
    frame_processor_->SetGroupStartTimestampIfInSequenceMode(timestamp_offset_);
  }

  BufferQueue StringToBufferQueue(const std::string& buffers_to_append,
                                  const TrackId track_id,
                                  const DemuxerStream::Type type) {
    std::vector<std::string> timestamps = base::SplitString(
        buffers_to_append, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);

    BufferQueue buffers;
    for (size_t i = 0; i < timestamps.size(); i++) {
      bool is_keyframe = false;
      if (base::EndsWith(timestamps[i], "K", base::CompareCase::SENSITIVE)) {
        is_keyframe = true;
        // Remove the "K" off of the token.
        timestamps[i] = timestamps[i].substr(0, timestamps[i].length() - 1);
      }

      // Use custom decode timestamp if included.
      std::vector<std::string> buffer_timestamps = base::SplitString(
          timestamps[i], "|", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
      if (buffer_timestamps.size() == 1)
        buffer_timestamps.push_back(buffer_timestamps[0]);
      CHECK_EQ(2u, buffer_timestamps.size());

      double time_in_ms, decode_time_in_ms;
      CHECK(base::StringToDouble(buffer_timestamps[0], &time_in_ms));
      CHECK(base::StringToDouble(buffer_timestamps[1], &decode_time_in_ms));

      // Create buffer. Encode the original time_in_ms as the buffer's data to
      // enable later verification of possible buffer relocation in presentation
      // timeline due to coded frame processing.
      const uint8_t* timestamp_as_data =
          reinterpret_cast<uint8_t*>(&time_in_ms);
      scoped_refptr<StreamParserBuffer> buffer =
          StreamParserBuffer::CopyFrom(timestamp_as_data, sizeof(time_in_ms),
                                       is_keyframe, type, track_id);
      base::TimeDelta timestamp = base::TimeDelta::FromSecondsD(
          time_in_ms / base::Time::kMillisecondsPerSecond);
      buffer->set_timestamp(timestamp);
      if (time_in_ms != decode_time_in_ms) {
        DecodeTimestamp decode_timestamp = DecodeTimestamp::FromSecondsD(
            decode_time_in_ms / base::Time::kMillisecondsPerSecond);
        buffer->SetDecodeTimestamp(decode_timestamp);
      }

      buffer->set_duration(frame_duration_);
      buffers.push_back(buffer);
    }
    return buffers;
  }

  void ProcessFrames(const std::string& audio_timestamps,
                     const std::string& video_timestamps) {
    StreamParser::BufferQueueMap buffer_queue_map;
    const auto& audio_buffers =
        StringToBufferQueue(audio_timestamps, audio_id_, DemuxerStream::AUDIO);
    if (!audio_buffers.empty())
      buffer_queue_map.insert(std::make_pair(audio_id_, audio_buffers));
    const auto& video_buffers =
        StringToBufferQueue(video_timestamps, video_id_, DemuxerStream::VIDEO);
    if (!video_buffers.empty())
      buffer_queue_map.insert(std::make_pair(video_id_, video_buffers));
    ASSERT_TRUE(frame_processor_->ProcessFrames(
        buffer_queue_map, append_window_start_, append_window_end_,
        &timestamp_offset_));
  }

  void CheckExpectedRangesByTimestamp(ChunkDemuxerStream* stream,
                                      const std::string& expected) {
    // Note, DemuxerStream::TEXT streams return [0,duration (==infinity here))
    Ranges<base::TimeDelta> r = stream->GetBufferedRanges(kInfiniteDuration);

    std::stringstream ss;
    ss << "{ ";
    for (size_t i = 0; i < r.size(); ++i) {
      int64_t start = r.start(i).InMilliseconds();
      int64_t end = r.end(i).InMilliseconds();
      ss << "[" << start << "," << end << ") ";
    }
    ss << "}";
    EXPECT_EQ(expected, ss.str());
  }

  void CheckReadStalls(ChunkDemuxerStream* stream) {
    int loop_count = 0;

    do {
      read_callback_called_ = false;
      stream->Read(base::Bind(&FrameProcessorTest::StoreStatusAndBuffer,
                              base::Unretained(this)));
      base::RunLoop().RunUntilIdle();
    } while (++loop_count < 2 && read_callback_called_ &&
             last_read_status_ == DemuxerStream::kAborted);

    ASSERT_FALSE(read_callback_called_ &&
                 last_read_status_ == DemuxerStream::kAborted)
        << "2 kAborted reads in a row. Giving up.";
    EXPECT_FALSE(read_callback_called_);
  }

  // Format of |expected| is a space-delimited sequence of
  // timestamp_in_ms:original_timestamp_in_ms
  // original_timestamp_in_ms (and the colon) must be omitted if it is the same
  // as timestamp_in_ms.
  void CheckReadsThenReadStalls(ChunkDemuxerStream* stream,
                                const std::string& expected) {
    std::vector<std::string> timestamps = base::SplitString(
        expected, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
    std::stringstream ss;
    for (size_t i = 0; i < timestamps.size(); ++i) {
      int loop_count = 0;

      do {
        read_callback_called_ = false;
        stream->Read(base::Bind(&FrameProcessorTest::StoreStatusAndBuffer,
                                base::Unretained(this)));
        base::RunLoop().RunUntilIdle();
        EXPECT_TRUE(read_callback_called_);
      } while (++loop_count < 2 &&
               last_read_status_ == DemuxerStream::kAborted);

      ASSERT_FALSE(last_read_status_ == DemuxerStream::kAborted)
          << "2 kAborted reads in a row. Giving up.";
      EXPECT_EQ(DemuxerStream::kOk, last_read_status_);
      EXPECT_FALSE(last_read_buffer_->end_of_stream());

      if (i > 0)
        ss << " ";

      int time_in_ms = last_read_buffer_->timestamp().InMilliseconds();
      ss << time_in_ms;

      // Decode the original_time_in_ms from the buffer's data.
      double original_time_in_ms;
      ASSERT_EQ(sizeof(original_time_in_ms), last_read_buffer_->data_size());
      original_time_in_ms = *(reinterpret_cast<const double*>(
          last_read_buffer_->data()));
      if (original_time_in_ms != time_in_ms)
        ss << ":" << original_time_in_ms;

      // Detect full-discard preroll buffer.
      if (last_read_buffer_->discard_padding().first == kInfiniteDuration &&
          last_read_buffer_->discard_padding().second.is_zero()) {
        ss << "P";
      }
    }

    EXPECT_EQ(expected, ss.str());
    CheckReadStalls(stream);
  }

  // TODO(wolenetz): Refactor to instead verify the expected signalling or lack
  // thereof of new coded frame group by the FrameProcessor. See
  // https://crbug.com/580613.
  bool in_coded_frame_group() {
    return frame_processor_->coded_frame_group_last_dts_ !=
           kNoDecodeTimestamp();
  }

  void seek(ChunkDemuxerStream* stream, base::TimeDelta seek_time) {
    stream->AbortReads();
    stream->Seek(seek_time);
    stream->StartReturningData();
  }

  base::MessageLoop message_loop_;
  StrictMock<FrameProcessorTestCallbackHelper> callbacks_;

  std::unique_ptr<FrameProcessor> frame_processor_;
  base::TimeDelta append_window_start_;
  base::TimeDelta append_window_end_;
  base::TimeDelta timestamp_offset_;
  base::TimeDelta frame_duration_;
  std::unique_ptr<ChunkDemuxerStream> audio_;
  std::unique_ptr<ChunkDemuxerStream> video_;
  const TrackId audio_id_;
  const TrackId video_id_;
  const BufferQueue empty_queue_;

  // StoreStatusAndBuffer's most recent result.
  DemuxerStream::Status last_read_status_;
  scoped_refptr<DecoderBuffer> last_read_buffer_;
  bool read_callback_called_;

 private:
  void StoreStatusAndBuffer(DemuxerStream::Status status,
                            const scoped_refptr<DecoderBuffer>& buffer) {
    if (status == DemuxerStream::kOk && buffer.get()) {
      DVLOG(3) << __FUNCTION__ << "status: " << status << " ts: "
               << buffer->timestamp().InSecondsF();
    } else {
      DVLOG(3) << __FUNCTION__ << "status: " << status << " ts: n/a";
    }

    read_callback_called_ = true;
    last_read_status_ = status;
    last_read_buffer_ = buffer;
  }

  void CreateAndConfigureStream(DemuxerStream::Type type) {
    // TODO(wolenetz/dalecurtis): Also test with splicing disabled?
    switch (type) {
      case DemuxerStream::AUDIO: {
        ASSERT_FALSE(audio_);
        audio_.reset(new ChunkDemuxerStream(DemuxerStream::AUDIO, "1"));
        AudioDecoderConfig decoder_config(kCodecVorbis, kSampleFormatPlanarF32,
                                          CHANNEL_LAYOUT_STEREO, 1000,
                                          EmptyExtraData(), Unencrypted());
        frame_processor_->OnPossibleAudioConfigUpdate(decoder_config);
        ASSERT_TRUE(audio_->UpdateAudioConfig(decoder_config, new MediaLog()));
        break;
      }
      case DemuxerStream::VIDEO: {
        ASSERT_FALSE(video_);
        video_.reset(new ChunkDemuxerStream(DemuxerStream::VIDEO, "2"));
        ASSERT_TRUE(video_->UpdateVideoConfig(TestVideoConfig::Normal(),
                                              new MediaLog()));
        break;
      }
      // TODO(wolenetz): Test text coded frame processing.
      case DemuxerStream::TEXT:
      case DemuxerStream::UNKNOWN: {
        ASSERT_FALSE(true);
      }
    }
  }

  DISALLOW_COPY_AND_ASSIGN(FrameProcessorTest);
};

TEST_F(FrameProcessorTest, WrongTypeInAppendedBuffer) {
  AddTestTracks(HAS_AUDIO);
  EXPECT_FALSE(in_coded_frame_group());

  StreamParser::BufferQueueMap buffer_queue_map;
  const auto& audio_buffers =
      StringToBufferQueue("0K", audio_id_, DemuxerStream::VIDEO);
  buffer_queue_map.insert(std::make_pair(audio_id_, audio_buffers));
  ASSERT_FALSE(
      frame_processor_->ProcessFrames(buffer_queue_map, append_window_start_,
                                      append_window_end_, &timestamp_offset_));
  EXPECT_FALSE(in_coded_frame_group());
  EXPECT_EQ(base::TimeDelta(), timestamp_offset_);
  CheckExpectedRangesByTimestamp(audio_.get(), "{ }");
  CheckReadStalls(audio_.get());
}

TEST_F(FrameProcessorTest, NonMonotonicallyIncreasingTimestampInOneCall) {
  AddTestTracks(HAS_AUDIO);

  StreamParser::BufferQueueMap buffer_queue_map;
  const auto& audio_buffers =
      StringToBufferQueue("10K 0K", audio_id_, DemuxerStream::AUDIO);
  buffer_queue_map.insert(std::make_pair(audio_id_, audio_buffers));
  ASSERT_FALSE(
      frame_processor_->ProcessFrames(buffer_queue_map, append_window_start_,
                                      append_window_end_, &timestamp_offset_));
  EXPECT_FALSE(in_coded_frame_group());
  EXPECT_EQ(base::TimeDelta(), timestamp_offset_);
  CheckExpectedRangesByTimestamp(audio_.get(), "{ }");
  CheckReadStalls(audio_.get());
}

TEST_P(FrameProcessorTest, AudioOnly_SingleFrame) {
  // Tests A: P(A) -> (a)
  InSequence s;
  AddTestTracks(HAS_AUDIO);
  if (GetParam())
    frame_processor_->SetSequenceMode(true);

  EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_));
  ProcessFrames("0K", "");
  EXPECT_TRUE(in_coded_frame_group());
  EXPECT_EQ(base::TimeDelta(), timestamp_offset_);
  CheckExpectedRangesByTimestamp(audio_.get(), "{ [0,10) }");
  CheckReadsThenReadStalls(audio_.get(), "0");
}

TEST_P(FrameProcessorTest, VideoOnly_SingleFrame) {
  // Tests V: P(V) -> (v)
  InSequence s;
  AddTestTracks(HAS_VIDEO);
  if (GetParam())
    frame_processor_->SetSequenceMode(true);

  EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_));
  ProcessFrames("", "0K");
  EXPECT_TRUE(in_coded_frame_group());
  EXPECT_EQ(base::TimeDelta(), timestamp_offset_);
  CheckExpectedRangesByTimestamp(video_.get(), "{ [0,10) }");
  CheckReadsThenReadStalls(video_.get(), "0");
}

TEST_P(FrameProcessorTest, AudioOnly_TwoFrames) {
  // Tests A: P(A0, A10) -> (a0, a10)
  InSequence s;
  AddTestTracks(HAS_AUDIO);
  if (GetParam())
    frame_processor_->SetSequenceMode(true);

  EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 2));
  ProcessFrames("0K 10K", "");
  EXPECT_TRUE(in_coded_frame_group());
  EXPECT_EQ(base::TimeDelta(), timestamp_offset_);
  CheckExpectedRangesByTimestamp(audio_.get(), "{ [0,20) }");
  CheckReadsThenReadStalls(audio_.get(), "0 10");
}

TEST_P(FrameProcessorTest, AudioOnly_SetOffsetThenSingleFrame) {
  // Tests A: STSO(50)+P(A0) -> TSO==50,(a0@50)
  InSequence s;
  AddTestTracks(HAS_AUDIO);
  if (GetParam())
    frame_processor_->SetSequenceMode(true);

  const base::TimeDelta fifty_ms = base::TimeDelta::FromMilliseconds(50);
  SetTimestampOffset(fifty_ms);
  EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ + fifty_ms));
  ProcessFrames("0K", "");
  EXPECT_TRUE(in_coded_frame_group());
  EXPECT_EQ(fifty_ms, timestamp_offset_);
  CheckExpectedRangesByTimestamp(audio_.get(), "{ [50,60) }");

  // We do not stall on reading without seeking to 50ms due to
  // SourceBufferStream::kSeekToStartFudgeRoom().
  CheckReadsThenReadStalls(audio_.get(), "50:0");
}

TEST_P(FrameProcessorTest, AudioOnly_SetOffsetThenFrameTimestampBelowOffset) {
  // Tests A: STSO(50)+P(A20) ->
  //   if sequence mode: TSO==30,(a20@50)
  //   if segments mode: TSO==50,(a20@70)
  InSequence s;
  AddTestTracks(HAS_AUDIO);
  bool using_sequence_mode = GetParam();
  if (using_sequence_mode)
    frame_processor_->SetSequenceMode(true);

  const base::TimeDelta fifty_ms = base::TimeDelta::FromMilliseconds(50);
  const base::TimeDelta twenty_ms = base::TimeDelta::FromMilliseconds(20);
  SetTimestampOffset(fifty_ms);

  if (using_sequence_mode) {
    EXPECT_CALL(callbacks_, PossibleDurationIncrease(
        fifty_ms + frame_duration_));
  } else {
    EXPECT_CALL(callbacks_, PossibleDurationIncrease(
        fifty_ms + twenty_ms + frame_duration_));
  }

  ProcessFrames("20K", "");
  EXPECT_TRUE(in_coded_frame_group());

  // We do not stall on reading without seeking to 50ms / 70ms due to
  // SourceBufferStream::kSeekToStartFudgeRoom().
  if (using_sequence_mode) {
    EXPECT_EQ(fifty_ms - twenty_ms, timestamp_offset_);
    CheckExpectedRangesByTimestamp(audio_.get(), "{ [50,60) }");
    CheckReadsThenReadStalls(audio_.get(), "50:20");
  } else {
    EXPECT_EQ(fifty_ms, timestamp_offset_);
    CheckExpectedRangesByTimestamp(audio_.get(), "{ [70,80) }");
    CheckReadsThenReadStalls(audio_.get(), "70:20");
  }
}

TEST_P(FrameProcessorTest, AudioOnly_SequentialProcessFrames) {
  // Tests A: P(A0,A10)+P(A20,A30) -> (a0,a10,a20,a30)
  InSequence s;
  AddTestTracks(HAS_AUDIO);
  if (GetParam())
    frame_processor_->SetSequenceMode(true);

  EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 2));
  ProcessFrames("0K 10K", "");
  EXPECT_TRUE(in_coded_frame_group());
  EXPECT_EQ(base::TimeDelta(), timestamp_offset_);
  CheckExpectedRangesByTimestamp(audio_.get(), "{ [0,20) }");

  EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 4));
  ProcessFrames("20K 30K", "");
  EXPECT_TRUE(in_coded_frame_group());
  EXPECT_EQ(base::TimeDelta(), timestamp_offset_);
  CheckExpectedRangesByTimestamp(audio_.get(), "{ [0,40) }");

  CheckReadsThenReadStalls(audio_.get(), "0 10 20 30");
}

TEST_P(FrameProcessorTest, AudioOnly_NonSequentialProcessFrames) {
  // Tests A: P(A20,A30)+P(A0,A10) ->
  //   if sequence mode: TSO==-20 after first P(), 20 after second P(), and
  //                     a(20@0,a30@10,a0@20,a10@30)
  //   if segments mode: TSO==0,(a0,a10,a20,a30)
  InSequence s;
  AddTestTracks(HAS_AUDIO);
  bool using_sequence_mode = GetParam();
  if (using_sequence_mode) {
    frame_processor_->SetSequenceMode(true);
    EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 2));
  } else {
    EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 4));
  }

  ProcessFrames("20K 30K", "");
  EXPECT_TRUE(in_coded_frame_group());

  if (using_sequence_mode) {
    CheckExpectedRangesByTimestamp(audio_.get(), "{ [0,20) }");
    EXPECT_EQ(frame_duration_ * -2, timestamp_offset_);
    EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 4));
  } else {
    CheckExpectedRangesByTimestamp(audio_.get(), "{ [20,40) }");
    EXPECT_EQ(base::TimeDelta(), timestamp_offset_);
    EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 2));
  }

  ProcessFrames("0K 10K", "");
  EXPECT_TRUE(in_coded_frame_group());

  if (using_sequence_mode) {
    CheckExpectedRangesByTimestamp(audio_.get(), "{ [0,40) }");
    EXPECT_EQ(frame_duration_ * 2, timestamp_offset_);
    CheckReadsThenReadStalls(audio_.get(), "0:20 10:30 20:0 30:10");
  } else {
    CheckExpectedRangesByTimestamp(audio_.get(), "{ [0,40) }");
    EXPECT_EQ(base::TimeDelta(), timestamp_offset_);
    // Re-seek to 0ms now that we've appended data earlier than what has already
    // satisfied our initial seek to start, above.
    seek(audio_.get(), base::TimeDelta());
    CheckReadsThenReadStalls(audio_.get(), "0 10 20 30");
  }
}

TEST_P(FrameProcessorTest, AudioVideo_SequentialProcessFrames) {
  // Tests AV: P(A0,A10;V0k,V10,V20)+P(A20,A30,A40,V30) ->
  //   (a0,a10,a20,a30,a40);(v0,v10,v20,v30)
  InSequence s;
  AddTestTracks(HAS_AUDIO | HAS_VIDEO);
  if (GetParam())
    frame_processor_->SetSequenceMode(true);

  EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 3));
  ProcessFrames("0K 10K", "0K 10 20");
  EXPECT_TRUE(in_coded_frame_group());
  EXPECT_EQ(base::TimeDelta(), timestamp_offset_);
  CheckExpectedRangesByTimestamp(audio_.get(), "{ [0,20) }");
  CheckExpectedRangesByTimestamp(video_.get(), "{ [0,30) }");

  EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 5));
  ProcessFrames("20K 30K 40K", "30");
  EXPECT_TRUE(in_coded_frame_group());
  EXPECT_EQ(base::TimeDelta(), timestamp_offset_);
  CheckExpectedRangesByTimestamp(audio_.get(), "{ [0,50) }");
  CheckExpectedRangesByTimestamp(video_.get(), "{ [0,40) }");

  CheckReadsThenReadStalls(audio_.get(), "0 10 20 30 40");
  CheckReadsThenReadStalls(video_.get(), "0 10 20 30");
}

TEST_P(FrameProcessorTest, AudioVideo_Discontinuity) {
  // Tests AV: P(A0,A10,A30,A40,A50;V0k,V10,V40,V50key) ->
  //   if sequence mode: TSO==10,(a0,a10,a30,a40,a50@60);(v0,v10,v50@60)
  //   if segments mode: TSO==0,(a0,a10,a30,a40,a50);(v0,v10,v50)
  // This assumes A40K is processed before V40, which depends currently on
  // MergeBufferQueues() behavior.
  InSequence s;
  AddTestTracks(HAS_AUDIO | HAS_VIDEO);
  bool using_sequence_mode = GetParam();
  if (using_sequence_mode) {
    frame_processor_->SetSequenceMode(true);
    EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 7));
  } else {
    EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 6));
  }

  ProcessFrames("0K 10K 30K 40K 50K", "0K 10 40 50K");
  EXPECT_TRUE(in_coded_frame_group());

  if (using_sequence_mode) {
    EXPECT_EQ(frame_duration_, timestamp_offset_);
    CheckExpectedRangesByTimestamp(audio_.get(), "{ [0,70) }");
    CheckExpectedRangesByTimestamp(video_.get(), "{ [0,70) }");
    CheckReadsThenReadStalls(audio_.get(), "0 10 30 40 60:50");
    CheckReadsThenReadStalls(video_.get(), "0 10 60:50");
  } else {
    EXPECT_EQ(base::TimeDelta(), timestamp_offset_);
    CheckExpectedRangesByTimestamp(audio_.get(), "{ [0,60) }");
    CheckExpectedRangesByTimestamp(video_.get(), "{ [0,20) [50,60) }");
    CheckReadsThenReadStalls(audio_.get(), "0 10 30 40 50");
    CheckReadsThenReadStalls(video_.get(), "0 10");
    seek(video_.get(), frame_duration_ * 5);
    CheckReadsThenReadStalls(video_.get(), "50");
  }
}

TEST_P(FrameProcessorTest, AudioVideo_Discontinuity_TimestampOffset) {
  // If in 'sequence' mode, a new coded frame group is *only* started if the
  // processed frame sequence outputs something that goes backwards in DTS
  // order. This helps retain the intent of 'sequence' mode: it both collapses
  // gaps as well as allows app to override the timeline placement and so needs
  // to handle overlap-appends, too.
  InSequence s;
  AddTestTracks(HAS_AUDIO | HAS_VIDEO);
  bool using_sequence_mode = GetParam();
  frame_processor_->SetSequenceMode(using_sequence_mode);

  // Start a coded frame group at time 100ms. Note the jagged start still uses
  // the coded frame group's start time as the range start for both streams.
  EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 14));
  SetTimestampOffset(frame_duration_ * 10);
  ProcessFrames("0K 10K 20K", "10K 20K 30K");
  EXPECT_EQ(frame_duration_ * 10, timestamp_offset_);
  EXPECT_TRUE(in_coded_frame_group());
  CheckExpectedRangesByTimestamp(audio_.get(), "{ [100,130) }");
  CheckExpectedRangesByTimestamp(video_.get(), "{ [100,140) }");

  // Test the differentiation between 'sequence' and 'segments' mode results if
  // the coded frame sequence jumps forward beyond the normal discontinuity
  // threshold.
  EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 24));
  SetTimestampOffset(frame_duration_ * 20);
  ProcessFrames("0K 10K 20K", "10K 20K 30K");
  EXPECT_EQ(frame_duration_ * 20, timestamp_offset_);
  EXPECT_TRUE(in_coded_frame_group());
  if (using_sequence_mode) {
    CheckExpectedRangesByTimestamp(audio_.get(), "{ [100,230) }");
    CheckExpectedRangesByTimestamp(video_.get(), "{ [100,240) }");
  } else {
    CheckExpectedRangesByTimestamp(audio_.get(), "{ [100,130) [200,230) }");
    CheckExpectedRangesByTimestamp(video_.get(), "{ [100,140) [200,240) }");
  }

  // Test the behavior when timestampOffset adjustment causes next frames to be
  // in the past relative to the previously processed frame and triggers a new
  // coded frame group, even in 'sequence' mode.
  base::TimeDelta fifty_five_ms = base::TimeDelta::FromMilliseconds(55);
  EXPECT_CALL(callbacks_,
              PossibleDurationIncrease(fifty_five_ms + frame_duration_ * 4));
  SetTimestampOffset(fifty_five_ms);
  ProcessFrames("0K 10K 20K", "10K 20K 30K");
  EXPECT_EQ(fifty_five_ms, timestamp_offset_);
  EXPECT_TRUE(in_coded_frame_group());
  // The new audio range is not within SourceBufferStream's coalescing threshold
  // relative to the next range, but the new video range is within the
  // threshold.
  if (using_sequence_mode) {
    // TODO(wolenetz/chcunningham): The large explicit-timestampOffset-induced
    // jump forward (from timestamp 130 to 200) while in a sequence mode coded
    // frame group makes our adjacency threshold in SourceBuffer, based on
    // max-interbuffer-distance-within-coded-frame-group, very lenient.
    // This causes [55,85) to merge with [100,230) here for audio, and similar
    // for video. See also https://crbug.com/620523.
    CheckExpectedRangesByTimestamp(audio_.get(), "{ [55,230) }");
    CheckExpectedRangesByTimestamp(video_.get(), "{ [55,240) }");
  } else {
    CheckExpectedRangesByTimestamp(audio_.get(),
                                   "{ [55,85) [100,130) [200,230) }");
    // Note that the range adjacency logic used in this case is doesn't consider
    // DTS 85 to be close enough to [100,140), since the first DTS in video
    // range [100,140) is actually 110. The muxed data started a coded frame
    // group at time 100, but actual DTS is used for adjacency checks while
    // appending.
    CheckExpectedRangesByTimestamp(video_.get(),
                                   "{ [55,95) [100,140) [200,240) }");
  }

  // Verify the buffers.
  // Re-seek now that we've appended data earlier than what already satisfied
  // our initial seek to start.
  seek(audio_.get(), fifty_five_ms);
  seek(video_.get(), fifty_five_ms);
  if (using_sequence_mode) {
    CheckReadsThenReadStalls(
        audio_.get(),
        "55:0 65:10 75:20 100:0 110:10 120:20 200:0 210:10 220:20");
    CheckReadsThenReadStalls(
        video_.get(),
        "65:10 75:20 85:30 110:10 120:20 130:30 210:10 220:20 230:30");
  } else {
    CheckReadsThenReadStalls(audio_.get(), "55:0 65:10 75:20");
    CheckReadsThenReadStalls(video_.get(), "65:10 75:20 85:30");
    seek(audio_.get(), frame_duration_ * 10);
    seek(video_.get(), frame_duration_ * 10);
    CheckReadsThenReadStalls(audio_.get(), "100:0 110:10 120:20");
    CheckReadsThenReadStalls(video_.get(), "110:10 120:20 130:30");
    seek(audio_.get(), frame_duration_ * 20);
    seek(video_.get(), frame_duration_ * 20);
    CheckReadsThenReadStalls(audio_.get(), "200:0 210:10 220:20");
    CheckReadsThenReadStalls(video_.get(), "210:10 220:20 230:30");
  }
}

TEST_P(FrameProcessorTest,
       AppendWindowFilterOfNegativeBufferTimestampsWithPrerollDiscard) {
  InSequence s;
  AddTestTracks(HAS_AUDIO);
  if (GetParam())
    frame_processor_->SetSequenceMode(true);

  SetTimestampOffset(frame_duration_ * -2);
  EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_));
  ProcessFrames("0K 10K 20K", "");
  EXPECT_TRUE(in_coded_frame_group());
  EXPECT_EQ(frame_duration_ * -2, timestamp_offset_);
  CheckExpectedRangesByTimestamp(audio_.get(), "{ [0,10) }");
  CheckReadsThenReadStalls(audio_.get(), "0:10P 0:20");
}

TEST_P(FrameProcessorTest, AppendWindowFilterWithInexactPreroll) {
  InSequence s;
  AddTestTracks(HAS_AUDIO);
  if (GetParam())
    frame_processor_->SetSequenceMode(true);
  SetTimestampOffset(-frame_duration_);
  EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 2));
  ProcessFrames("0K 9.75K 20K", "");
  CheckExpectedRangesByTimestamp(audio_.get(), "{ [0,20) }");
  CheckReadsThenReadStalls(audio_.get(), "0P 0:9.75 10:20");
}

TEST_P(FrameProcessorTest, AppendWindowFilterWithInexactPreroll_2) {
  InSequence s;
  AddTestTracks(HAS_AUDIO);
  if (GetParam())
    frame_processor_->SetSequenceMode(true);
  SetTimestampOffset(-frame_duration_);
  EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 2));
  ProcessFrames("0K 10.25K 20K", "");
  CheckExpectedRangesByTimestamp(audio_.get(), "{ [0,20) }");
  CheckReadsThenReadStalls(audio_.get(), "0P 0:10.25 10:20");
}

TEST_P(FrameProcessorTest, AllowNegativeFramePTSAndDTSBeforeOffsetAdjustment) {
  InSequence s;
  AddTestTracks(HAS_AUDIO);
  bool using_sequence_mode = GetParam();
  if (using_sequence_mode) {
    frame_processor_->SetSequenceMode(true);
    EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 3));
  } else {
    EXPECT_CALL(callbacks_,
                PossibleDurationIncrease((frame_duration_ * 5) / 2));
  }

  ProcessFrames("-5K 5K 15K", "");

  if (using_sequence_mode) {
    EXPECT_EQ(frame_duration_ / 2, timestamp_offset_);
    CheckExpectedRangesByTimestamp(audio_.get(), "{ [0,30) }");
    CheckReadsThenReadStalls(audio_.get(), "0:-5 10:5 20:15");
  } else {
    EXPECT_EQ(base::TimeDelta(), timestamp_offset_);
    CheckExpectedRangesByTimestamp(audio_.get(), "{ [0,25) }");
    CheckReadsThenReadStalls(audio_.get(), "0:-5 5 15");
  }
}

TEST_P(FrameProcessorTest, PartialAppendWindowFilterNoDiscontinuity) {
  // Tests that spurious discontinuity is not introduced by a partially
  // trimmed frame.
  InSequence s;
  AddTestTracks(HAS_AUDIO);
  if (GetParam())
    frame_processor_->SetSequenceMode(true);
  EXPECT_CALL(callbacks_,
              PossibleDurationIncrease(base::TimeDelta::FromMilliseconds(29)));

  append_window_start_ = base::TimeDelta::FromMilliseconds(7);
  ProcessFrames("0K 19K", "");

  EXPECT_EQ(base::TimeDelta(), timestamp_offset_);
  CheckExpectedRangesByTimestamp(audio_.get(), "{ [7,29) }");
  CheckReadsThenReadStalls(audio_.get(), "7:0 19");
}

TEST_P(FrameProcessorTest,
       PartialAppendWindowFilterNoDiscontinuity_DtsAfterPts) {
  // Tests that spurious discontinuity is not introduced by a partially trimmed
  // frame that originally had DTS > PTS.
  InSequence s;
  AddTestTracks(HAS_AUDIO);
  bool using_sequence_mode = GetParam();
  if (using_sequence_mode) {
    frame_processor_->SetSequenceMode(true);
    EXPECT_CALL(callbacks_, PossibleDurationIncrease(
                                base::TimeDelta::FromMilliseconds(20)));
  } else {
    EXPECT_CALL(callbacks_, PossibleDurationIncrease(
                                base::TimeDelta::FromMilliseconds(13)));
  }

  ProcessFrames("-7|10K 3|20K", "");

  if (using_sequence_mode) {
    EXPECT_EQ(base::TimeDelta::FromMilliseconds(7), timestamp_offset_);

    // TODO(wolenetz): Adjust the following expectation to use PTS instead of
    // DTS once https://crbug.com/398130 is fixed.
    CheckExpectedRangesByTimestamp(audio_.get(), "{ [17,37) }");

    CheckReadsThenReadStalls(audio_.get(), "0:-7 10:3");
  } else {
    EXPECT_EQ(base::TimeDelta(), timestamp_offset_);

    // TODO(wolenetz): Adjust the following expectation to use PTS instead of
    // DTS once https://crbug.com/398130 is fixed.
    CheckExpectedRangesByTimestamp(audio_.get(), "{ [17,30) }");

    CheckReadsThenReadStalls(audio_.get(), "0:-7 3");
  }
}

TEST_P(FrameProcessorTest, PartialAppendWindowFilterNoNewMediaSegment) {
  // Tests that a new media segment is not forcibly signalled for audio frame
  // partial front trim, to prevent incorrect introduction of a discontinuity
  // and potentially a non-keyframe video frame to be processed next after the
  // discontinuity.
  InSequence s;
  AddTestTracks(HAS_AUDIO | HAS_VIDEO);
  frame_processor_->SetSequenceMode(GetParam());
  EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_));
  ProcessFrames("", "0K");
  EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_));
  ProcessFrames("-5K", "");
  EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_* 2));
  ProcessFrames("", "10");

  EXPECT_EQ(base::TimeDelta(), timestamp_offset_);
  EXPECT_TRUE(in_coded_frame_group());
  CheckExpectedRangesByTimestamp(audio_.get(), "{ [0,5) }");
  CheckExpectedRangesByTimestamp(video_.get(), "{ [0,20) }");
  CheckReadsThenReadStalls(audio_.get(), "0:-5");
  CheckReadsThenReadStalls(video_.get(), "0 10");
}

TEST_F(FrameProcessorTest, AudioOnly_SequenceModeContinuityAcrossReset) {
  InSequence s;
  AddTestTracks(HAS_AUDIO);
  frame_processor_->SetSequenceMode(true);
  EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_));
  ProcessFrames("0K", "");
  frame_processor_->Reset();
  EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 2));
  ProcessFrames("100K", "");

  EXPECT_EQ(frame_duration_ * -9, timestamp_offset_);
  EXPECT_TRUE(in_coded_frame_group());
  CheckExpectedRangesByTimestamp(audio_.get(), "{ [0,20) }");
  CheckReadsThenReadStalls(audio_.get(), "0 10:100");
}

TEST_P(FrameProcessorTest, PartialAppendWindowZeroDurationPreroll) {
  InSequence s;
  AddTestTracks(HAS_AUDIO);
  bool is_sequence_mode = GetParam();
  frame_processor_->SetSequenceMode(is_sequence_mode);

  append_window_start_ = base::TimeDelta::FromMilliseconds(5);

  // Append a 0 duration frame that falls just before the append window.
  frame_duration_ = base::TimeDelta::FromMilliseconds(0);
  EXPECT_FALSE(in_coded_frame_group());
  EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_));
  ProcessFrames("4K", "");
  // Verify buffer is not part of ranges. It should be silently saved for
  // preroll for future append.
  CheckExpectedRangesByTimestamp(audio_.get(), "{ }");
  CheckReadsThenReadStalls(audio_.get(), "");
  EXPECT_FALSE(in_coded_frame_group());

  // Abort the reads from last stall. We don't want those reads to "complete"
  // when we append below. We will initiate new reads to confirm the buffer
  // looks as we expect.
  seek(audio_.get(), base::TimeDelta());

  // Append a frame with 10ms duration, with 9ms falling after the window start.
  base::TimeDelta expected_duration =
      base::TimeDelta::FromMilliseconds(is_sequence_mode ? 10 : 14);
  EXPECT_CALL(callbacks_, PossibleDurationIncrease(expected_duration));
  frame_duration_ = base::TimeDelta::FromMilliseconds(10);
  ProcessFrames("4K", "");
  EXPECT_TRUE(in_coded_frame_group());

  // Verify range updated to reflect last append was processed and trimmed, and
  // also that zero duration buffer was saved and attached as preroll.
  if (is_sequence_mode) {
    // For sequence mode, append window trimming is applied after the append
    // is adjusted for timestampOffset. Basically, everything gets rebased to 0
    // and trimming then removes 5 seconds from the front.
    CheckExpectedRangesByTimestamp(audio_.get(), "{ [5,10) }");
    CheckReadsThenReadStalls(audio_.get(), "5:4P 5:4");
  } else {  // segments mode
    CheckExpectedRangesByTimestamp(audio_.get(), "{ [5,14) }");
    CheckReadsThenReadStalls(audio_.get(), "5:4P 5:4");
  }

  // Verify the preroll buffer still has zero duration.
  StreamParserBuffer* last_read_parser_buffer =
      static_cast<StreamParserBuffer*>(last_read_buffer_.get());
  ASSERT_EQ(base::TimeDelta::FromMilliseconds(0),
            last_read_parser_buffer->preroll_buffer()->duration());
}

INSTANTIATE_TEST_CASE_P(SequenceMode, FrameProcessorTest, Values(true));
INSTANTIATE_TEST_CASE_P(SegmentsMode, FrameProcessorTest, Values(false));

}  // namespace media


text:
layout: page
title: Christina Parrish's 32nd Birthday
date: 2016-05-24
author: Gregory Coffey
tags: weekly links, java
status: published
summary: Curabitur porttitor metus ac tortor luctus.
banner: images/banner/wedding.jpg
booking:
  startDate: 10/04/2016
  endDate: 10/09/2016
  ctyhocn: HOUCYHX
  groupCode: CP3B
published: true
---
Pellentesque lobortis est nec purus sodales, ac auctor metus ultricies. Sed dui turpis, fringilla vitae mollis non, tempus eu quam. Praesent auctor enim sed justo convallis, lacinia pretium est fringilla. Nulla lectus eros, maximus ac placerat eget, accumsan vel arcu. Nulla sollicitudin posuere ipsum, elementum tempus nisl dictum et. Quisque sollicitudin diam vel ante sagittis, a fringilla turpis porta. Maecenas consectetur purus diam. Pellentesque ac erat sed mi mollis aliquam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Praesent non velit ac justo consequat congue id in quam. Proin ornare, ipsum at pretium vulputate, nulla est pretium ex, ac porta eros velit ac neque.
Sed enim ante, commodo ut porta eget, ornare vitae tortor. Integer ac massa augue. Vestibulum venenatis rutrum neque, vel accumsan sem dictum vitae. Nam dolor sapien, malesuada ut accumsan vitae, gravida quis nunc. Morbi eget eros ac mi laoreet tincidunt id nec purus. Duis viverra nunc risus, quis placerat orci blandit vitae. Sed lacinia consequat quam, ut tristique sapien convallis ac. Vestibulum sed varius tortor. Vivamus a eros quam.

1 Morbi ac lorem quis est placerat congue.

Quisque finibus lacus vitae urna iaculis consectetur. Vestibulum fringilla hendrerit urna, vel consectetur massa mattis ullamcorper. Etiam semper sapien sed aliquet luctus. Pellentesque dapibus fringilla lectus, id posuere nibh rutrum nec. Nullam nibh sem, ornare in felis varius, dapibus pellentesque tellus. Mauris facilisis vitae ante quis pretium. Quisque porta vel risus quis aliquet. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam quis posuere arcu. Duis eu ornare tortor, vel tempor nibh. Maecenas id rhoncus elit.


text:
package play.core

import java.util.concurrent.ForkJoinPool
import play.api.Play
import scala.concurrent.{ ExecutionContext, ExecutionContextExecutor }

/**
 * Provides access to Play's internal ExecutionContext.
 */
private[play] object Execution {

  /**
   * @deprecated Use the application execution context.
   * @return the actorsystem's execution context
   */
  @deprecated("Use an injected execution context", "2.6.0")
  def internalContext: ExecutionContextExecutor = {
    Play.privateMaybeApplication match {
      case None => common
      case Some(app) => app.actorSystem.dispatcher
    }
  }

  def trampoline = play.api.libs.streams.Execution.trampoline

  object Implicits {
    implicit def trampoline = Execution.trampoline
  }

  /**
   * Use this as a fallback when the application is unavailable.
   * The ForkJoinPool implementation promises to create threads on-demand
   * and clean them up when not in use (standard is when idle for 2
   * seconds).
   */
  private val common = ExecutionContext.fromExecutor(new ForkJoinPool())

}


text:
#ifndef AdamUpdater_H
#define AdamUpdater_H
#include <shogun/optimization/DescendUpdaterWithCorrection.h>
namespace shogun
{
/** @brief The class implements the Adam method.
 *
 * Please see the paper (https://arxiv.org/abs/1412.6980) for technical detail.
 *
 */
class AdamUpdater: public DescendUpdaterWithCorrection
{
public:
	/* Constructor */
	AdamUpdater();

	/** Parameterized Constructor
	 *
	 * @param learning_rate learning_rate
	 * @param epsilon epsilon
	 * @param first_moment_decay_factor first_moment_decay_factor
	 * @param second_moment_decay_factor second_moment_decay_factor
	 */
	AdamUpdater(float64_t learning_rate,float64_t epsilon,
		float64_t first_moment_decay_factor,
		float64_t second_moment_decay_factor);

	/* Destructor */
	virtual ~AdamUpdater();

	/** Set learning rate
	 *
	 * @param learning_rate learning rate
	 */
	virtual void set_learning_rate(float64_t learning_rate);

	/** Set epsilon
	 *
	 * @param epsilon epsilon
	 */
	virtual void set_epsilon(float64_t epsilon);

	/** Set decay factor for first moment
	 *
	 * @param decay_factor decay factor
	 */
	virtual void set_first_moment_decay_factor(float64_t decay_factor);

	/** Set decay factor for second moment
	 *
	 * @param decay_factor decay factor
	 */
	virtual void set_second_moment_decay_factor(float64_t decay_factor);

	/** returns the name of the class
	 *
	 * @return name AdamUpdater
	 */
	virtual const char* get_name() const { return "AdamUpdater"; }

	/** Update the target variable based on the given negative descend direction
	 *
	 * Note that this method will update the target variable in place.
	 * This method will be called by FirstOrderMinimizer::minimize()
	 *
	 * @param variable_reference a reference of the target variable
	 * @param raw_negative_descend_direction the negative descend direction given the current value
	 * @param learning_rate learning rate
	 */
	virtual void update_variable(SGVector<float64_t> variable_reference,
		SGVector<float64_t> raw_negative_descend_direction, float64_t learning_rate);

protected:
	/** Get the negative descend direction given current variable and gradient
	 *
	 * It will be called at update_variable()
	 *
	 * @param variable current variable
	 * @param gradient current gradient
	 * @param idx the index of the variable
	 * @param learning_rate learning rate
	 *
	 * @return negative descend direction (that is, the given gradient in the class)
	 */
	virtual float64_t get_negative_descend_direction(float64_t variable,
		float64_t gradient, index_t idx, float64_t learning_rate);

	/* learning_rate at iteration */
	float64_t m_log_learning_rate;

	/* epsilon */
	float64_t m_epsilon;

	/* counter of iteration */
	int64_t m_iteration_counter;

	/* decay_factor in first moment */
	float64_t m_decay_factor_first_moment;

	/* decay_factor in second moment */
	float64_t m_decay_factor_second_moment;

	/* weighted factor in logarithmic domain */
	float64_t m_log_scale_pre_iteration;

	/* first moment of gradient */
	SGVector<float64_t> m_gradient_first_moment;

	/* second moment of gradient */
	SGVector<float64_t> m_gradient_second_moment;
private:
	/*  Init */
	void init();
};

}
#endif


text:
MBTA Alerts
===========

### The Bot That Tweets

The MBTA puts out an RSS feed that an enterprising developer (or frustrated MBTA commuter) started scraping and turning into tweets.

This app scrapes the [MBTA's readtime feed feed](http://realtime.mbta.com/portal), and will tweet out the short descriptions, with the hashtag #[mbta](https://twitter.com/search?q=%23mbta&src=typd).

### The Story

[FredHQ][fredhq], the creator of [@mbta_alerts][alerts], [almost suspended][almost] the account due to a number of obstacles, but Code for Boston offered to take it over. Fred provided [thorough documentation of his processes][prodoc], which led to the development of this app.

[fredhq]: https://twitter.com/fredhq
[alerts]: https://twitter.com/mbta_alerts
[almost]: https://gist.github.com/fredhq/34781ea7c60c1388e16e
[prodoc]: https://gist.github.com/fredhq/eaf7a6ebb1ac88c6cc69

Then for the 2014 national day of civic hacking [Calvin Metcalf][] creatted a whole slew of single line accounts on top of the origional one.

- [Green Line Alerts](https://twitter.com/greenlinealerts/)
- [Red Line Alerts](https://twitter.com/Red_Line_Alerts)
- [Fitchburg/South Acton Line Alerts](https://twitter.com/fitchburgalerts)
- [Orange Line Alerts](https://twitter.com/OrangeLineAlert)
- [Framingham/Worcester Line Alerts](https://twitter.com/framinghamline)
- [Newburyport/Rockport Line Alerts](https://twitter.com/NewburyportLine)
- [Providence/Stoughton Line Alerts](https://twitter.com/providenceline)
- [Blue Line Alerts](https://twitter.com/BlueLineAlerts)
- [Haverhill Line Alerts](https://twitter.com/haverhillline)
- [Franklin Line Alerts](https://twitter.com/franklinalerts)
- [8 Bus Alerts](https://twitter.com/8_bus)
- [Lowell Line Alerts](https://twitter.com/lowellline)
- [60 Bus Alerts](https://twitter.com/60_bus)
- [Commuter Boat Alerts](https://twitter.com/mbtaboatalerts)
- [Mattapan High Speed Line](https://twitter.com/highspeedalerts)
- [Buses 220, 221, 222 alerts](https://twitter.com/220_222)
- [MBTA Bus Alerts](https://twitter.com/mbta_bus_alerts)
- [Eastie MBTA Alerts](https://twitter.com/EastieMBTA)
- [Melrose MBTA Alerts](https://twitter.com/melrosembta)
- [Salem MBTA Alerts](https://twitter.com/SalemMBTA)
- [Saugus MBTA Alerts](https://twitter.com/SaugusMBTA)
- [Quincy MBTA Aalerts](https://twitter.com/quincy_mbta)
- [Southie MBTA Aalerts](https://twitter.com/SouthieMBTA)

[Calvin Metcalf]: https://github.com/calvinmetcalf

### Tech stack

MBTA Alerts uses:

+ nodejs
+ couchdb
+ [pouchdb](https://github.com/pouchdb/pouchdb)
+ last pass


text:
<?php

declare(strict_types=1);

namespace CommunityTranslation\Api\EntryPoint;

use CommunityTranslation\Api\EntryPoint;
use CommunityTranslation\Entity\Package as PackageEntity;
use CommunityTranslation\Entity\Package\Version as PackageVersionEntity;
use CommunityTranslation\Repository\Package as PackageRepository;
use CommunityTranslation\Repository\Package\Version as PackageVersionRepository;
use CommunityTranslation\Translatable\Importer as TranslatableImporter;
use CommunityTranslation\TranslationsConverter\Provider as TranslationsConverterProvider;
use Concrete\Core\Error\UserMessageException;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\Response;

defined('C5_EXECUTE') or die('Access Denied.');

/**
 * Set the translatable strings of a package version.
 *
 * @example POST request to http://www.example.com/api/package/concrete5/8.2.0/translatables/po in multipart/form-data format with these fields:
 * - file: the file containing the translatable strings (required)
 * - packageName: the name of the package (required when creating a new package, optional if the package already exists)
 */
class ImportPackageVersionTranslatables extends EntryPoint
{
    public const ACCESS_KEY = 'importPackageVersionTranslatables';

    public function __invoke(string $packageHandle, string $packageVersion, string $formatHandle): Response
    {
        return $this->handle(
            function () use ($packageHandle, $packageVersion, $formatHandle): Response {
                $this->userControl->checkGenericAccess(static::ACCESS_KEY);
                if ($packageHandle === '') {
                    throw new UserMessageException(t('Package handle not specified'), Response::HTTP_NOT_ACCEPTABLE);
                }
                if ($packageVersion === '') {
                    throw new UserMessageException(t('Package version not specified'), Response::HTTP_NOT_ACCEPTABLE);
                }
                if ($formatHandle === '') {
                    throw new UserMessageException(t('Translations format handle not specified'), Response::HTTP_NOT_ACCEPTABLE);
                }
                $file = $this->request->files->get('file');
                if ($file === null) {
                    throw new UserMessageException(t('The file with the translatable strings has not been specified'), Response::HTTP_NOT_ACCEPTABLE);
                }
                /** @var \Symfony\Component\HttpFoundation\File\UploadedFile $file */
                if (!$file->isValid()) {
                    throw new UserMessageException(t('The file with the translatable strings has not been received correctly: %s', $file->getErrorMessage()), Response::HTTP_NOT_ACCEPTABLE);
                }
                $format = $this->app->make(TranslationsConverterProvider::class)->getByHandle($formatHandle);
                if ($format === null) {
                    throw new UserMessageException(t('Unable to find the specified translations format'), 404);
                }
                $translations = $format->loadTranslationsFromFile($file->getPathname());
                if (count($translations) < 1) {
                    throw new UserMessageException(t('No translatable strings found in the received file'));
                }
                $packageName = $this->request->request->get('packageName', '');
                $packageName = is_string($packageName) ? trim($packageName) : '';
                $package = $this->app->make(PackageRepository::class)->findOneBy(['handle' => $packageHandle]);
                $em = $this->app->make(EntityManager::class);
                if ($package === null) {
                    if ($packageName === '') {
                        throw new UserMessageException(t('The package with handle "%1$s" does not exist yet, so you need to specify the "%2$s" field in the request body.', $packageHandle, 'packageName'), Response::HTTP_NOT_ACCEPTABLE);
                    }
                    $package = new PackageEntity($packageHandle, $packageName);
                    $em->persist($package);
                    $em->flush($package);
                    $version = null;
                } else {
                    if ($packageName !== '' && $package->getName() !== $packageName) {
                        $package->setName($packageName);
                        $em->persist($package);
                        $em->flush($package);
                    }
                    $version = $this->app->make(PackageVersionRepository::class)->findByOneBy(['package' => $package, 'version' => $packageVersion]);
                }
                if ($version === null) {
                    $version = new PackageVersionEntity($package, $packageVersion);
                    $em->persist($version);
                    $em->flush($version);
                }
                $importer = $this->app->make(TranslatableImporter::class);
                $changed = $importer->importTranslations($translations, $package->getHandle(), $packageVersion->getVersion());

                return $this->buildJsonResponse(['changed' => $changed]);
            }
        );
    }
}


text:
invocieManager
==============

Manage your invoices.


text:
import React from 'react';
import CallToAction from '../CallToAction';

const PaymentCallToAction = ({ handleClick }) => (
  <CallToAction
    icon="credit_card"
    text="Tap to pay"
    handleClick={handleClick}
  />
);

export default PaymentCallToAction;


text:
class C {
    get [Symbol.toPrimitive]() { return ""; }
    set [Symbol.toPrimitive](x) { }
}

//// [symbolDeclarationEmit4.js]
class C {
    get [Symbol.toPrimitive]() { return ""; }
    set [Symbol.toPrimitive](x) { }
}

//// [symbolDeclarationEmit4.d.ts]
declare class C {
    [Symbol.toPrimitive]: string;
}


text:
A Javascript modal component.

## Getting Started
You can either download a copy of the source files or install Modalplate via Bower.

```
bower install modalplate
```

Start by including the necessary files.

```
<head>
   <link href="css/modalplate.css" rel="stylesheet" type="text/css">
</head>
<body>
   <script src="js/min/modalplate.js"></script>
</body>
```

## Basic Example
See a basic example of how to use the component.

```
<a href id="example">Open Modal</a>
<script>
document.getElementById('example').onclick = function(event) {
   new modalplate({
      heading: 'Example Modal',
      body: 'Here is the body text.',
      parseEvent: event
   });
};
</script>
```

## Javascript Options
See the different options you have available on component call.

Name | Default | Options | Description
---- | ---- | ---- | ----
body | false | | You can make the body whatever you would like to display.
breakpoint | 700 | | Set the breakpoint of the modal (in pixels) to change from a fullscreen modal to a standard content modal.
classAdd | false | | Set a class to the containing modal.
close | close | | Set the text or inner HTML of the close link.
heading | false | | You can make the heading whatever you would like.
overlay | true | true, false | Set whether or not you want the overlay to display on modal open.
parseEvent | false | true, false | Parse the event of a click to prevent the default link behavior.
reveal | slide-from-top | appear, appear-scale, slide-from-bottom, slide-from-left, slide-from-right, slide-from-top | Set the reveal animation.
revealLarge | false | appear, appear-scale, slide-from-bottom, slide-from-left, slide-from-right, slide-from-top | Set the reveal animation after the breakpoint has been reached. **NOTE** that false means the already existing reveal animation will be used.
trigger | always | always, small, large | Set when you want the modal trigger to fire. Small is below the breakpoint, large above the breakpoint and always is always.

## Advanced Example
See an advanced example below with options as per the above.

```
<a href id="example">Open Modal</a>
<script>
document.getElementById('example').onclick = function(event) {
   new modalplate({
      heading: 'Advanced Modal',
      body: 'Here is the body text.',
      close: '<i class="icon-close"></i>',
      breakpoint: 320,
      reveal: 'slide-from-right',
      revealLarge: 'slide-from-top',
      parseEvent: event
   });
};
</script>
```

## Author
Created and maintained by Chris Humboldt

Website: chrishumboldt.com

Twitter: twitter.com/chrishumboldt

GitHub github.com/chrishumboldt

## Copyright and License
Copyright 2015 Webplate Project

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.


text:
import os
import platform

from . import shell

try:
    from build_swift.build_swift.wrappers import xcrun
except ImportError:
    from build_swift.wrappers import xcrun

class Platform(object):
    """
    Abstract representation of a platform Swift can run on.
    """

    def __init__(self, name, archs, sdk_name=None):
        """
        Create a platform with the given name and list of architectures.
        """
        self.name = name
        self.targets = [Target(self, arch) for arch in archs]
        # FIXME: Eliminate this argument; apparently the SDK names are
        # internally a private implementation detail of the build script, so we
        # should just make them the same as the platform name.
        self.sdk_name = name.upper() if sdk_name is None else sdk_name

        # Add a property for each arch.
        for target in self.targets:
            setattr(self, target.arch, target)

    @property
    def is_darwin(self):
        """Convenience function for checking if this is a Darwin platform."""
        return isinstance(self, DarwinPlatform)

    @property
    def supports_benchmark(self):
        # By default, we don't support benchmarks on most platforms.
        return False

    @property
    def uses_host_tests(self):
        """
        Check if this is a Darwin platform that needs a connected device
        for tests.
        """
        # By default, we don't use connected devices on most platforms.
        return False

    def contains(self, target_name):
        """
        Returns True if the given target name belongs to a one of this
        platform's targets.
        """
        for target in self.targets:
            if target.name == target_name:
                return True
        return False

    def swift_flags(self, args):
        """
        Swift compiler flags for a platform, useful for cross-compiling
        """
        return ''

    def cmake_options(self, args):
        """
        CMake flags to build for a platform, useful for cross-compiling
        """
        return ''

    def swiftpm_config(self, args, output_dir, swift_toolchain, resource_path):
        """
        Generate a JSON file that SPM can use to cross-compile
        """
        raise NotImplementedError('Generating a SwiftPM cross-compilation JSON file '
                                  'for %s is not supported yet' % self.name)

class DarwinPlatform(Platform):
    def __init__(self, name, archs, sdk_name=None, is_simulator=False):
        self.is_simulator = is_simulator
        super(DarwinPlatform, self).__init__(name, archs, sdk_name)

    @property
    def is_embedded(self):
        """Check if this is a Darwin platform for embedded devices."""
        return self.name != "macosx" and self.name != "maccatalyst"

    @property
    def supports_benchmark(self):
        # By default, on Darwin we support benchmarks on all non-simulator
        # platforms.
        return not self.is_simulator

    @property
    def uses_host_tests(self):
        """
        Check if this is a Darwin platform that needs a connected device
        for tests.
        """
        return self.is_embedded and not self.is_simulator

    def sdk_supports_architecture(self, arch, toolchain):
        """
        Convenience function for checking whether the SDK supports the
        target architecture.
        """

        # The names match up with the xcrun SDK names.
        xcrun_sdk_name = self.name

        sdk_path = xcrun.sdk_path(sdk=xcrun_sdk_name, toolchain=toolchain)
        if not sdk_path:
            raise RuntimeError('Cannot find SDK path for %s' % xcrun_sdk_name)

        # Find the SDKSettings.plist for this sdK
        plistCommand = [
            '/usr/libexec/PlistBuddy',
            '-c',
            'Print :SupportedTargets:%s:Archs' % (self.name),
            '%s/SDKSettings.plist' % (sdk_path)
        ]

        sdk_archs = shell.capture(plistCommand, dry_run=False, echo=True)
        return arch in sdk_archs

class AndroidPlatform(Platform):
    @property
    def uses_host_tests(self):
        """
        Check if this is a Darwin platform that needs a connected device
        for tests.
        """
        return True

    def swift_flags(self, args):
        flags = '-target %s-unknown-linux-android%s ' % (args.android_arch,
                                                         args.android_api_level)

        flags += '-resource-dir %s/swift-%s-%s/lib/swift ' % (
                 args.build_root, self.name, args.android_arch)

        android_toolchain_path = self.ndk_toolchain_path(args)

        flags += '-sdk %s/sysroot ' % (android_toolchain_path)
        flags += '-tools-directory %s/bin' % (android_toolchain_path)
        return flags

    def cmake_options(self, args):
        options = '-DCMAKE_SYSTEM_NAME=Android '
        options += '-DCMAKE_SYSTEM_VERSION=%s ' % (args.android_api_level)
        options += '-DCMAKE_SYSTEM_PROCESSOR=%s ' % (args.android_arch if not
                                                     args.android_arch == 'armv7'
                                                     else 'armv7-a')
        options += '-DCMAKE_ANDROID_NDK:PATH=%s' % (args.android_ndk)
        return options

    def ndk_toolchain_path(self, args):
        return '%s/toolchains/llvm/prebuilt/%s' % (
            args.android_ndk, StdlibDeploymentTarget.host_target().name)

    def swiftpm_config(self, args, output_dir, swift_toolchain, resource_path):
        config_file = '%s/swiftpm-android-%s.json' % (output_dir, args.android_arch)

        if os.path.exists(config_file):
            print("Using existing config at %s" % config_file)
            return config_file

        spm_json = '{\n'
        spm_json += '  "version": 1,\n'
        spm_json += '  "target": "%s-unknown-linux-android%s",\n' % (
                    args.android_arch, args.android_api_level)
        spm_json += '  "toolchain-bin-dir": "%s/bin",\n' % swift_toolchain
        spm_json += '  "sdk": "%s/sysroot",\n' % self.ndk_toolchain_path(args)

        spm_json += '  "extra-cc-flags": [ "-fPIC", "-I%s/usr/include" ],\n' % (
                    args.cross_compile_deps_path)

        spm_json += '  "extra-swiftc-flags": [\n'
        spm_json += '    "-resource-dir", "%s",\n' % resource_path
        spm_json += '    "-tools-directory", "%s/bin",\n' % (
                    self.ndk_toolchain_path(args))
        spm_json += '    "-Xcc", "-I%s/usr/include",\n' % args.cross_compile_deps_path
        spm_json += '    "-L%s/usr/lib"\n' % args.cross_compile_deps_path
        spm_json += '  ],\n'

        spm_json += '  "extra-cpp-flags": [ "-lstdc++" ]\n'
        spm_json += '}'

        with open(config_file, 'w') as f:
            f.write(spm_json)
        return config_file

class OpenBSDPlatform(Platform):
    def cmake_options(self, args):
        toolchain_file = os.getenv('OPENBSD_USE_TOOLCHAIN_FILE')
        if not toolchain_file:
            return ''
        return f'-DCMAKE_TOOLCHAIN_FILE="${toolchain_file}"'

class Target(object):
    """
    Abstract representation of a target Swift can run on.
    """

    def __init__(self, platform, arch):
        self.platform = platform
        self.arch = arch
        # Delegate to the platform, this is usually not arch specific.
        self.supports_benchmark = self.platform.supports_benchmark

    @property
    def name(self):
        return "{}-{}".format(self.platform.name, self.arch)

class StdlibDeploymentTarget(object):
    OSX = DarwinPlatform("macosx", archs=["x86_64", "arm64"],
                         sdk_name="OSX")

    iOS = DarwinPlatform("iphoneos", archs=["arm64", "arm64e"],
                         sdk_name="IOS")
    iOSSimulator = DarwinPlatform("iphonesimulator", archs=["x86_64", "arm64"],
                                  sdk_name="IOS_SIMULATOR",
                                  is_simulator=True)

    AppleTV = DarwinPlatform("appletvos", archs=["arm64"],
                             sdk_name="TVOS")
    AppleTVSimulator = DarwinPlatform("appletvsimulator", archs=["x86_64", "arm64"],
                                      sdk_name="TVOS_SIMULATOR",
                                      is_simulator=True)

    AppleWatch = DarwinPlatform("watchos", archs=["armv7k", "arm64_32"],
                                sdk_name="WATCHOS")

    AppleWatchSimulator = DarwinPlatform("watchsimulator",
                                         archs=["i386", "x86_64", "arm64"],
                                         sdk_name="WATCHOS_SIMULATOR",
                                         is_simulator=True)

    # A platform that's not tied to any particular OS, and it meant to be used
    # to build the stdlib as standalone and/or statically linked.
    Freestanding = Platform("freestanding",
                            archs=["i386", "x86_64", "armv7", "armv7s", "armv7k",
                                   "arm64", "arm64e"])

    Linux = Platform("linux", archs=[
        "x86_64",
        "i686",
        "armv5",
        "armv6",
        "armv7",
        "aarch64",
        "powerpc",
        "powerpc64",
        "powerpc64le",
        "s390x"])

    FreeBSD = Platform("freebsd", archs=["x86_64"])

    OpenBSD = OpenBSDPlatform("openbsd", archs=["amd64"])

    Cygwin = Platform("cygwin", archs=["x86_64"])

    Android = AndroidPlatform("android", archs=["armv7", "aarch64", "x86_64"])

    Windows = Platform("windows", archs=["x86_64"])

    Haiku = Platform("haiku", archs=["x86_64"])

    WASI = Platform("wasi", archs=["wasm32"])

    # The list of known platforms.
    known_platforms = [
        OSX,
        iOS, iOSSimulator,
        AppleTV, AppleTVSimulator,
        AppleWatch, AppleWatchSimulator,
        Freestanding,
        Linux,
        FreeBSD,
        OpenBSD,
        Cygwin,
        Android,
        Windows,
        Haiku,
        WASI]

    # Cache of targets by name.
    _targets_by_name = dict((target.name, target)
                            for platform in known_platforms
                            for target in platform.targets)

    _sdk_targets = {
        'OSX': OSX.targets,
        'IOS': iOS.targets,
        'IOS_SIMULATOR': iOSSimulator.targets,
        'TVOS': AppleTV.targets,
        'TVOS_SIMULATOR': AppleTVSimulator.targets,
        'WATCHOS': AppleWatch.targets,
        'WATCHOS_SIMULATOR': AppleWatchSimulator.targets,
    }

    @staticmethod
    def host_target():
        """
        Return the host target for the build machine, if it is one of
        the recognized targets. Otherwise, throw a NotImplementedError.
        """
        system = platform.system()
        machine = platform.machine()

        if system == 'Linux':
            if 'ANDROID_DATA' in os.environ:
                if machine.startswith('armv7'):
                    return StdlibDeploymentTarget.Android.armv7
                elif machine == 'aarch64':
                    return StdlibDeploymentTarget.Android.aarch64
                raise NotImplementedError('Android System with architecture '
                                          '"%s" is not supported' % machine)

            if machine == 'x86_64':
                return StdlibDeploymentTarget.Linux.x86_64
            elif machine == 'i686':
                return StdlibDeploymentTarget.Linux.i686
            elif machine.startswith('armv7'):
                # linux-armv7* is canonicalized to 'linux-armv7'
                return StdlibDeploymentTarget.Linux.armv7
            elif machine.startswith('armv6'):
                # linux-armv6* is canonicalized to 'linux-armv6'
                return StdlibDeploymentTarget.Linux.armv6
            elif machine.startswith('armv5'):
                # linux-armv5* is canonicalized to 'linux-armv5'
                return StdlibDeploymentTarget.Linux.armv5
            elif machine == 'aarch64':
                return StdlibDeploymentTarget.Linux.aarch64
            elif machine == 'ppc':
                return StdlibDeploymentTarget.Linux.powerpc
            elif machine == 'ppc64':
                return StdlibDeploymentTarget.Linux.powerpc64
            elif machine == 'ppc64le':
                return StdlibDeploymentTarget.Linux.powerpc64le
            elif machine == 's390x':
                return StdlibDeploymentTarget.Linux.s390x

        elif system == 'Darwin':
            if machine == 'x86_64':
                return StdlibDeploymentTarget.OSX.x86_64
            elif machine == 'arm64':
                return StdlibDeploymentTarget.OSX.arm64
            elif machine == 'arm64e':
                return StdlibDeploymentTarget.OSX.arm64e

        elif system == 'FreeBSD':
            if machine == 'amd64':
                return StdlibDeploymentTarget.FreeBSD.x86_64

        elif system == 'OpenBSD':
            if machine == 'amd64':
                return StdlibDeploymentTarget.OpenBSD.amd64

        elif system == 'CYGWIN_NT-10.0':
            if machine == 'x86_64':
                return StdlibDeploymentTarget.Cygwin.x86_64

        elif system == 'Windows':
            if machine == "AMD64":
                return StdlibDeploymentTarget.Windows.x86_64

        elif system == 'Haiku':
            if machine == 'x86_64':
                return StdlibDeploymentTarget.Haiku.x86_64

        elif system == 'WASI':
            if machine == 'wasm32':
                return StdlibDeploymentTarget.WASI.wasm32

        raise NotImplementedError('System "%s" with architecture "%s" is not '
                                  'supported' % (system, machine))

    @classmethod
    def get_target_for_name(cls, name):
        return cls._targets_by_name.get(name)

    @classmethod
    def get_targets_by_name(cls, names):
        return [cls.get_target_for_name(name) for name in names]

    @classmethod
    def get_target_names(cls):
        return sorted([name for (name, target) in
                       cls._targets_by_name.items()])

    @classmethod
    def get_migrated_targets_for_sdk(cls, sdk_name):
        return cls._sdk_targets.get(sdk_name, None)

    @classmethod
    def get_all_migrated_sdks(cls):
        return cls._sdk_targets.keys()

def install_prefix():
    """
    Returns the default path at which built Swift products (like bin, lib,
    and include) will be installed, based on the host machine's operating
    system.
    """
    if platform.system() == 'Darwin':
        return '/Applications/Xcode.app/Contents/Developer/Toolchains/' + \
            'XcodeDefault.xctoolchain/usr'
    else:
        return '/usr'

def darwin_toolchain_prefix(darwin_install_prefix):
    """
    Given the install prefix for a Darwin system, and assuming that path
    is to a .xctoolchain directory, return the path to the .xctoolchain
    directory.
    """
    return os.path.split(darwin_install_prefix)[0]

def toolchain_path(install_destdir, install_prefix):
    """
    Given the install prefix for a Darwin system, and assuming that path
    is to a .xctoolchain directory, return the path to the .xctoolchain
    directory in the given install directory.
    This toolchain is being populated during the build-script invocation.
    Downstream products can use products that were previously installed into
    this toolchain.
    """
    built_toolchain_path = install_destdir
    if platform.system() == 'Darwin':
        # The prefix is an absolute path, so concatenate without os.path.
        built_toolchain_path += darwin_toolchain_prefix(install_prefix) + "/usr"
    else:
        built_toolchain_path += install_prefix
    return built_toolchain_path