text:
import time
import random
from threading import Thread

import zmq

# We have two workers, here we copy the code, normally these would
# run on different boxes...
#
def worker_a(context=None):
    context = context or zmq.Context.instance()
    worker = context.socket(zmq.DEALER)
    worker.setsockopt(zmq.IDENTITY, b'A')
    worker.connect("ipc://routing.ipc")

    total = 0
    while True:
        # We receive one part, with the workload
        request = worker.recv()
        finished = request == b"END"
        if finished:
            print("A received: %s" % total)
            break
        total += 1

def worker_b(context=None):
    context = context or zmq.Context.instance()
    worker = context.socket(zmq.DEALER)
    worker.setsockopt(zmq.IDENTITY, b'B')
    worker.connect("ipc://routing.ipc")

    total = 0
    while True:
        # We receive one part, with the workload
        request = worker.recv()
        finished = request == b"END"
        if finished:
            print("B received: %s" % total)
            break
        total += 1

context = zmq.Context.instance()
client = context.socket(zmq.ROUTER)
client.bind("ipc://routing.ipc")

Thread(target=worker_a).start()
Thread(target=worker_b).start()

# Wait for threads to stabilize
time.sleep(1)

# Send 10 tasks scattered to A twice as often as B
for _ in range(10):
    # Send two message parts, first the address...
    ident = random.choice([b'A', b'A', b'B'])
    # And then the workload
    work = b"This is the workload"
    client.send_multipart([ident, work])

client.send_multipart([b'A', b'END'])
client.send_multipart([b'B', b'END'])


text:
@class WMFTableOfContentsViewController, WebViewController;

typedef NS_ENUM(NSInteger, WMFArticleFooterViewIndex) {
    WMFArticleFooterViewIndexAboutThisArticle = 0,
    WMFArticleFooterViewIndexReadMore = 1
};

NS_ASSUME_NONNULL_BEGIN

@interface WMFArticleViewController (WMFPrivate)

// Data
@property (nonatomic, strong, readwrite, nullable) MWKArticle *article;

// Children
@property (nonatomic, strong, nullable) WMFTableOfContentsViewController *tableOfContentsViewController;
@property (nonatomic, strong) WebViewController *webViewController;

@end

NS_ASSUME_NONNULL_END

redpajama_set_name: RedPajamaGithub


text:
package hu.pazsitz.pacuse.tests.cucumber.featuretables.fieldactions.delegates.populator;

import org.apache.log4j.Logger;

import hu.pazsitz.pacuse.tests.cucumber.featuretables.AnnotatedWebElement;
import hu.pazsitz.pacuse.tests.cucumber.featuretables.fieldactions.delegates.IDelegatedAction;

public class ButtonPopulatorAction implements IDelegatedAction {

	@Override
	public boolean doAction(AnnotatedWebElement element, String value) throws Exception {
		Logger.getLogger(this.getClass()).info(" tag: " + element.getTagName() + " value: " + value);

		element.click();

		return true;
	}

}


text:
result=`pvecm status | grep "Node addresses:" | cut -d ":" -f 2 | cut -d " " -f 2`
echo $result


text:
using UnityEngine;

namespace ContextActionsTests
{
    public class ContextActionsTests : MonoBehaviour
    {
        private void Start()
        {

        }

        private void Update()
        {
            FFFF();
            FFF2();
        }

        private void FFF{caret}F()
        {

        }

        private void FFF2()
        {
            GetComponent<int>();
        }

        private void FFF3()
        {
            GetComponent<int>();
        }
    }
}


text:
package com.wandrell.tabletop.punkapocalyptic.model.unit.event;

import com.wandrell.tabletop.stats.event.ValueChangeEvent;

/**
 * Adapter for the Gang listener.
 *
 * @author Bernardo Martínez Garrido
 */
public class GangListenerAdapter implements GangListener {

    @Override
    public void bulletsChanged(final ValueChangeEvent event) {}

    @Override
    public void unitAdded(final UnitEvent event) {}

    @Override
    public void unitRemoved(final UnitEvent event) {}

    @Override
    public void valorationChanged(final ValueChangeEvent event) {}

}


text:
/**
 */
package CIM15.IEC61970.Informative.InfERPSupport;

import CIM15.IEC61968.Common.Status;

import CIM15.IEC61970.Core.IdentifiedObject;

import org.eclipse.emf.common.notify.NotificationChain;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;

/**
 *
 * A representation of the model object 'Erp Time Entry'.
 *
 *
 *

 * The following features are supported:
 *

 *
{@link CIM15.IEC61970.Informative.InfERPSupport.ErpTimeEntry#getErpProjectAccounting Erp Project Accounting}

 *
{@link CIM15.IEC61970.Informative.InfERPSupport.ErpTimeEntry#getStatus Status}

 *
{@link CIM15.IEC61970.Informative.InfERPSupport.ErpTimeEntry#getErpTimeSheet Erp Time Sheet}

 *

 *

 *
 * @generated
 */
public class ErpTimeEntry extends IdentifiedObject {
	/**
	 * The cached value of the '{@link #getErpProjectAccounting() Erp Project Accounting}' reference.
	 *
	 *
	 * @see #getErpProjectAccounting()
	 * @generated
	 * @ordered
	 */
	protected ErpProjectAccounting erpProjectAccounting;

	/**
	 * The cached value of the '{@link #getStatus() Status}' containment reference.
	 *
	 *
	 * @see #getStatus()
	 * @generated
	 * @ordered
	 */
	protected Status status;

	/**
	 * The cached value of the '{@link #getErpTimeSheet() Erp Time Sheet}' reference.
	 *
	 *
	 * @see #getErpTimeSheet()
	 * @generated
	 * @ordered
	 */
	protected ErpTimeSheet erpTimeSheet;

	/**
	 *
	 *
	 * @generated
	 */
	protected ErpTimeEntry() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return InfERPSupportPackage.Literals.ERP_TIME_ENTRY;
	}

	/**
	 * Returns the value of the 'Erp Project Accounting' reference.
	 * It is bidirectional and its opposite is '{@link CIM15.IEC61970.Informative.InfERPSupport.ErpProjectAccounting#getErpTimeEntries Erp Time Entries}'.
	 *
	 *

	 * If the meaning of the 'Erp Project Accounting' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Erp Project Accounting' reference.
	 * @see #setErpProjectAccounting(ErpProjectAccounting)
	 * @see CIM15.IEC61970.Informative.InfERPSupport.ErpProjectAccounting#getErpTimeEntries
	 * @generated
	 */
	public ErpProjectAccounting getErpProjectAccounting() {
		if (erpProjectAccounting != null && erpProjectAccounting.eIsProxy()) {
			InternalEObject oldErpProjectAccounting = (InternalEObject)erpProjectAccounting;
			erpProjectAccounting = (ErpProjectAccounting)eResolveProxy(oldErpProjectAccounting);
			if (erpProjectAccounting != oldErpProjectAccounting) {
			}
		}
		return erpProjectAccounting;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public ErpProjectAccounting basicGetErpProjectAccounting() {
		return erpProjectAccounting;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public NotificationChain basicSetErpProjectAccounting(ErpProjectAccounting newErpProjectAccounting, NotificationChain msgs) {
		ErpProjectAccounting oldErpProjectAccounting = erpProjectAccounting;
		erpProjectAccounting = newErpProjectAccounting;
		return msgs;
	}

	/**
	 * Sets the value of the '{@link CIM15.IEC61970.Informative.InfERPSupport.ErpTimeEntry#getErpProjectAccounting Erp Project Accounting}' reference.
	 *
	 *
	 * @param value the new value of the 'Erp Project Accounting' reference.
	 * @see #getErpProjectAccounting()
	 * @generated
	 */
	public void setErpProjectAccounting(ErpProjectAccounting newErpProjectAccounting) {
		if (newErpProjectAccounting != erpProjectAccounting) {
			NotificationChain msgs = null;
			if (erpProjectAccounting != null)
				msgs = ((InternalEObject)erpProjectAccounting).eInverseRemove(this, InfERPSupportPackage.ERP_PROJECT_ACCOUNTING__ERP_TIME_ENTRIES, ErpProjectAccounting.class, msgs);
			if (newErpProjectAccounting != null)
				msgs = ((InternalEObject)newErpProjectAccounting).eInverseAdd(this, InfERPSupportPackage.ERP_PROJECT_ACCOUNTING__ERP_TIME_ENTRIES, ErpProjectAccounting.class, msgs);
			msgs = basicSetErpProjectAccounting(newErpProjectAccounting, msgs);
			if (msgs != null) msgs.dispatch();
		}
	}

	/**
	 * Returns the value of the 'Status' containment reference.
	 *
	 *

	 * If the meaning of the 'Status' containment reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Status' containment reference.
	 * @see #setStatus(Status)
	 * @generated
	 */
	public Status getStatus() {
		return status;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public NotificationChain basicSetStatus(Status newStatus, NotificationChain msgs) {
		Status oldStatus = status;
		status = newStatus;
		return msgs;
	}

	/**
	 * Sets the value of the '{@link CIM15.IEC61970.Informative.InfERPSupport.ErpTimeEntry#getStatus Status}' containment reference.
	 *
	 *
	 * @param value the new value of the 'Status' containment reference.
	 * @see #getStatus()
	 * @generated
	 */
	public void setStatus(Status newStatus) {
		if (newStatus != status) {
			NotificationChain msgs = null;
			if (status != null)
				msgs = ((InternalEObject)status).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - InfERPSupportPackage.ERP_TIME_ENTRY__STATUS, null, msgs);
			if (newStatus != null)
				msgs = ((InternalEObject)newStatus).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - InfERPSupportPackage.ERP_TIME_ENTRY__STATUS, null, msgs);
			msgs = basicSetStatus(newStatus, msgs);
			if (msgs != null) msgs.dispatch();
		}
	}

	/**
	 * Returns the value of the 'Erp Time Sheet' reference.
	 * It is bidirectional and its opposite is '{@link CIM15.IEC61970.Informative.InfERPSupport.ErpTimeSheet#getErpTimeEntries Erp Time Entries}'.
	 *
	 *

	 * If the meaning of the 'Erp Time Sheet' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Erp Time Sheet' reference.
	 * @see #setErpTimeSheet(ErpTimeSheet)
	 * @see CIM15.IEC61970.Informative.InfERPSupport.ErpTimeSheet#getErpTimeEntries
	 * @generated
	 */
	public ErpTimeSheet getErpTimeSheet() {
		if (erpTimeSheet != null && erpTimeSheet.eIsProxy()) {
			InternalEObject oldErpTimeSheet = (InternalEObject)erpTimeSheet;
			erpTimeSheet = (ErpTimeSheet)eResolveProxy(oldErpTimeSheet);
			if (erpTimeSheet != oldErpTimeSheet) {
			}
		}
		return erpTimeSheet;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public ErpTimeSheet basicGetErpTimeSheet() {
		return erpTimeSheet;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public NotificationChain basicSetErpTimeSheet(ErpTimeSheet newErpTimeSheet, NotificationChain msgs) {
		ErpTimeSheet oldErpTimeSheet = erpTimeSheet;
		erpTimeSheet = newErpTimeSheet;
		return msgs;
	}

	/**
	 * Sets the value of the '{@link CIM15.IEC61970.Informative.InfERPSupport.ErpTimeEntry#getErpTimeSheet Erp Time Sheet}' reference.
	 *
	 *
	 * @param value the new value of the 'Erp Time Sheet' reference.
	 * @see #getErpTimeSheet()
	 * @generated
	 */
	public void setErpTimeSheet(ErpTimeSheet newErpTimeSheet) {
		if (newErpTimeSheet != erpTimeSheet) {
			NotificationChain msgs = null;
			if (erpTimeSheet != null)
				msgs = ((InternalEObject)erpTimeSheet).eInverseRemove(this, InfERPSupportPackage.ERP_TIME_SHEET__ERP_TIME_ENTRIES, ErpTimeSheet.class, msgs);
			if (newErpTimeSheet != null)
				msgs = ((InternalEObject)newErpTimeSheet).eInverseAdd(this, InfERPSupportPackage.ERP_TIME_SHEET__ERP_TIME_ENTRIES, ErpTimeSheet.class, msgs);
			msgs = basicSetErpTimeSheet(newErpTimeSheet, msgs);
			if (msgs != null) msgs.dispatch();
		}
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
		switch (featureID) {
			case InfERPSupportPackage.ERP_TIME_ENTRY__ERP_PROJECT_ACCOUNTING:
				if (erpProjectAccounting != null)
					msgs = ((InternalEObject)erpProjectAccounting).eInverseRemove(this, InfERPSupportPackage.ERP_PROJECT_ACCOUNTING__ERP_TIME_ENTRIES, ErpProjectAccounting.class, msgs);
				return basicSetErpProjectAccounting((ErpProjectAccounting)otherEnd, msgs);
			case InfERPSupportPackage.ERP_TIME_ENTRY__ERP_TIME_SHEET:
				if (erpTimeSheet != null)
					msgs = ((InternalEObject)erpTimeSheet).eInverseRemove(this, InfERPSupportPackage.ERP_TIME_SHEET__ERP_TIME_ENTRIES, ErpTimeSheet.class, msgs);
				return basicSetErpTimeSheet((ErpTimeSheet)otherEnd, msgs);
		}
		return super.eInverseAdd(otherEnd, featureID, msgs);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
		switch (featureID) {
			case InfERPSupportPackage.ERP_TIME_ENTRY__ERP_PROJECT_ACCOUNTING:
				return basicSetErpProjectAccounting(null, msgs);
			case InfERPSupportPackage.ERP_TIME_ENTRY__STATUS:
				return basicSetStatus(null, msgs);
			case InfERPSupportPackage.ERP_TIME_ENTRY__ERP_TIME_SHEET:
				return basicSetErpTimeSheet(null, msgs);
		}
		return super.eInverseRemove(otherEnd, featureID, msgs);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case InfERPSupportPackage.ERP_TIME_ENTRY__ERP_PROJECT_ACCOUNTING:
				if (resolve) return getErpProjectAccounting();
				return basicGetErpProjectAccounting();
			case InfERPSupportPackage.ERP_TIME_ENTRY__STATUS:
				return getStatus();
			case InfERPSupportPackage.ERP_TIME_ENTRY__ERP_TIME_SHEET:
				if (resolve) return getErpTimeSheet();
				return basicGetErpTimeSheet();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case InfERPSupportPackage.ERP_TIME_ENTRY__ERP_PROJECT_ACCOUNTING:
				setErpProjectAccounting((ErpProjectAccounting)newValue);
				return;
			case InfERPSupportPackage.ERP_TIME_ENTRY__STATUS:
				setStatus((Status)newValue);
				return;
			case InfERPSupportPackage.ERP_TIME_ENTRY__ERP_TIME_SHEET:
				setErpTimeSheet((ErpTimeSheet)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case InfERPSupportPackage.ERP_TIME_ENTRY__ERP_PROJECT_ACCOUNTING:
				setErpProjectAccounting((ErpProjectAccounting)null);
				return;
			case InfERPSupportPackage.ERP_TIME_ENTRY__STATUS:
				setStatus((Status)null);
				return;
			case InfERPSupportPackage.ERP_TIME_ENTRY__ERP_TIME_SHEET:
				setErpTimeSheet((ErpTimeSheet)null);
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case InfERPSupportPackage.ERP_TIME_ENTRY__ERP_PROJECT_ACCOUNTING:
				return erpProjectAccounting != null;
			case InfERPSupportPackage.ERP_TIME_ENTRY__STATUS:
				return status != null;
			case InfERPSupportPackage.ERP_TIME_ENTRY__ERP_TIME_SHEET:
				return erpTimeSheet != null;
		}
		return super.eIsSet(featureID);
	}

} // ErpTimeEntry


text:
#include "cameraexample.h"

#include <QtGui>
#include <QApplication>
#include <QDebug>

// Lock Symbian orientation
#ifdef Q_OS_SYMBIAN
#include <eikenv.h>
#include <eikappui.h>
#include <aknenv.h>
#include <aknappui.h>
#endif

#ifdef Q_OS_SYMBIAN
#include <QSymbianEvent>
#include <w32std.h>

#endif

static const int KGoomMemoryLowEvent = 0x10282DBF;
static const int KGoomMemoryGoodEvent = 0x20026790;

class MyApplication : public QApplication
{
public:
  MyApplication( int argc, char** argv ) : QApplication( argc, argv ) {}

#ifdef Q_OS_SYMBIAN
protected:
//! [0]
  bool symbianEventFilter( const QSymbianEvent* symbianEvent )
  {
    const TWsEvent *event = symbianEvent->windowServerEvent();
    if ( !event ) {
      return false;
    }
    switch ( event->Type() ) {
      // GOOM handling enabled
      // http://wiki.forum.nokia.com/index.php/Graphics_memory_handling
      case EEventUser: {
        TApaSystemEvent* eventData = reinterpret_cast<TApaSystemEvent*>(event->EventData());
        if ((*eventData) == EApaSystemEventShutdown) {
            eventData++;
            if ((*eventData) == KGoomMemoryLowEvent) {
             return true;
            }
        }
        break;
      }
      default:
        break;
    };

    // Always return false so we don't stop
    // the event from being processed
    return false;
  }
//! [0]
#endif
};

int main(int argc, char *argv[])
{
    // NOTE: set this value before creating MyApplication instance
    // http://doc.trolltech.com/qapplication.html#setGraphicsSystem
    QApplication::setGraphicsSystem("raster"); // NOTE: Seems that raster have to be enabled with Nokia N8

    MyApplication a(argc, argv);

    // Lock Symbian orientation
#ifdef Q_OS_SYMBIAN
    CAknAppUi* appUi = dynamic_cast<CAknAppUi*> (CEikonEnv::Static()->AppUi());
    TRAP_IGNORE(
    if (appUi) {
        appUi->SetOrientationL(CAknAppUi::EAppUiOrientationLandscape);
    }
    );
#endif

    CameraExample w;
    w.showFullScreen();

    return a.exec();
}


text:
'use strict';

const fromEvent = require('nodeca.core/lib/app/from_event');

let $dialog;
let params;
let result;

N.wire.once(module.apiPath, function init_handlers() {

  // Select subscription type
  //
  N.wire.on(module.apiPath + ':select', function select_type_subscription_dlg(data) {
    params.subscription = result = +data.$this.data('type');
    $dialog.modal('hide');
  });

  // Close dialog on sudden page exit (if user click back button in browser)
  //
  N.wire.on('navigate.exit', function teardown_page() {
    $dialog?.modal('hide');
  });
});

// Init dialog
//
N.wire.on(module.apiPath, async function show_subscription_dlg(options) {
  result = null;
  params = options;
  $dialog = $(N.runtime.render(module.apiPath, Object.assign({ apiPath: module.apiPath }, params)));
  $('body').append($dialog);

  $dialog
    .on('shown.bs.modal', function () {
      $dialog.find('.btn-secondary').focus();
    })
    .modal('show');

  await fromEvent($dialog, 'hidden.bs.modal');

  // When dialog closes - remove it from body and free resources.
  $dialog.remove();
  $dialog = null;
  params = null;

  if (!result) throw 'CANCELED';
});


text:
package org.mx.components.rbac.repository;

import org.mx.components.rbac.entities.UserEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserPagingQueryRepository extends PagingAndSortingRepository<UserEntity, String> {
	public Page<UserEntity> findByIsDeleted(boolean deleted, Pageable page);
}


text:
"""
Read a MAF and print counts and frequencies of all n-mers
(words composed on n consecutive alignment columns)

TODO: reconcile this and maf_mapping_word_frequency.py

usage: %prog n < maf_file
"""

from __future__ import division

import psyco; psyco.profile()

from bx.cookbook import doc_optparse
import string
import sys

from align import maf

def __main__():

    motif_len = int( sys.argv[1] )

    big_map = {}
    total = 0

    maf_reader = maf.Reader( sys.stdin )

    for m in maf_reader:
        texts = [ c.text.upper() for c in m.components ]
        for i in range( m.text_size - motif_len ):
            motif = string.join( [ text[ i : i + motif_len ] for text in texts ] )
            if big_map.has_key( motif ): big_map[ motif ] += 1
            else: big_map[ motif ] = 1
            total += 1

    items = zip( big_map.values(), big_map.keys() )
    items.sort()
    items.reverse()

    for count, motif in items:
        print "%d\t%0.10f\t%s" % ( count, count / total, motif )

if __name__ == "__main__": __main__()


text:
import {ListWrapper} from 'angular2/src/facade/collection';
import {unimplemented} from 'angular2/src/facade/exceptions';
import {ResolvedProvider} from 'angular2/src/core/di';
import {isPresent, isBlank} from 'angular2/src/facade/lang';

import {AppElement} from './element';

import {ElementRef, ElementRef_} from './element_ref';
import {TemplateRef, TemplateRef_} from './template_ref';
import {
  EmbeddedViewRef,
  HostViewRef,
  HostViewFactoryRef,
  HostViewFactoryRef_,
  ViewRef,
  ViewRef_
} from './view_ref';

/**
 * Represents a container where one or more Views can be attached.
 *
 * The container can contain two kinds of Views. Host Views, created by instantiating a
 * {@link Component} via {@link #createHostView}, and Embedded Views, created by instantiating an
 * {@link TemplateRef Embedded Template} via {@link #createEmbeddedView}.
 *
 * The location of the View Container within the containing View is specified by the Anchor
 * `element`. Each View Container can have only one Anchor Element and each Anchor Element can only
 * have a single View Container.
 *
 * Root elements of Views attached to this container become siblings of the Anchor Element in
 * the Rendered View.
 *
 * To access a `ViewContainerRef` of an Element, you can either place a {@link Directive} injected
 * with `ViewContainerRef` on the Element, or you obtain it via
 * {@link AppViewManager#getViewContainer}.
 *
 * <!-- TODO(i): we are also considering ElementRef#viewContainer api -->
 */
export abstract class ViewContainerRef {
  /**
   * Anchor element that specifies the location of this container in the containing View.
   * <!-- TODO: rename to anchorElement -->
   */
  get element(): ElementRef { return unimplemented(); }

  /**
   * Destroys all Views in this container.
   */
  clear(): void {
    for (var i = this.length - 1; i >= 0; i--) {
      this.remove(i);
    }
  }

  /**
   * Returns the {@link ViewRef} for the View located in this container at the specified index.
   */
  abstract get(index: number): ViewRef;

  /**
   * Returns the number of Views currently attached to this container.
   */
  get length(): number { return unimplemented(); };

  /**
   * Instantiates an Embedded View based on the {@link TemplateRef `templateRef`} and inserts it
   * into this container at the specified `index`.
   *
   * If `index` is not specified, the new View will be inserted as the last View in the container.
   *
   * Returns the {@link ViewRef} for the newly created View.
   */
  abstract createEmbeddedView(templateRef: TemplateRef, index?: number): EmbeddedViewRef;

  /**
   * Instantiates a single {@link Component} and inserts its Host View into this container at the
   * specified `index`.
   *
   * The component is instantiated using its {@link ProtoViewRef `protoView`} which can be
   * obtained via {@link Compiler#compileInHost}.
   *
   * If `index` is not specified, the new View will be inserted as the last View in the container.
   *
   * You can optionally specify `dynamicallyCreatedProviders`, which configure the {@link Injector}
   * that will be created for the Host View.
   *
   * Returns the {@link HostViewRef} of the Host View created for the newly instantiated Component.
   */
  abstract createHostView(hostViewFactoryRef: HostViewFactoryRef, index?: number,
                          dynamicallyCreatedProviders?: ResolvedProvider[],
                          projectableNodes?: any[][]): HostViewRef;

  /**
   * Inserts a View identified by a {@link ViewRef} into the container at the specified `index`.
   *
   * If `index` is not specified, the new View will be inserted as the last View in the container.
   *
   * Returns the inserted {@link ViewRef}.
   */
  abstract insert(viewRef: EmbeddedViewRef, index?: number): EmbeddedViewRef;

  /**
   * Returns the index of the View, specified via {@link ViewRef}, within the current container or
   * `-1` if this container doesn't contain the View.
   */
  abstract indexOf(viewRef: ViewRef): number;

  /**
   * Destroys a View attached to this container at the specified `index`.
   *
   * If `index` is not specified, the last View in the container will be removed.
   */
  abstract remove(index?: number): void;

  /**
   * Use along with {@link #insert} to move a View within the current container.
   *
   * If the `index` param is omitted, the last {@link ViewRef} is detached.
   */
  abstract detach(index?: number): EmbeddedViewRef;
}

export class ViewContainerRef_ extends ViewContainerRef {
  constructor(private _element: AppElement) { super(); }

  get(index: number): EmbeddedViewRef { return this._element.nestedViews[index].ref; }
  get length(): number {
    var views = this._element.nestedViews;
    return isPresent(views) ? views.length : 0;
  }

  get element(): ElementRef_ { return this._element.ref; }

  // TODO(rado): profile and decide whether bounds checks should be added
  // to the methods below.
  createEmbeddedView(templateRef: TemplateRef, index: number = -1): EmbeddedViewRef {
    if (index == -1) index = this.length;
    var vm = this._element.parentView.viewManager;
    return vm.createEmbeddedViewInContainer(this._element.ref, index, templateRef);
  }

  createHostView(hostViewFactoryRef: HostViewFactoryRef, index: number = -1,
                 dynamicallyCreatedProviders: ResolvedProvider[] = null,
                 projectableNodes: any[][] = null): HostViewRef {
    if (index == -1) index = this.length;
    var vm = this._element.parentView.viewManager;
    return vm.createHostViewInContainer(this._element.ref, index, hostViewFactoryRef,
                                        dynamicallyCreatedProviders, projectableNodes);
  }

  // TODO(i): refactor insert+remove into move
  insert(viewRef: ViewRef, index: number = -1): EmbeddedViewRef {
    if (index == -1) index = this.length;
    var vm = this._element.parentView.viewManager;
    return vm.attachViewInContainer(this._element.ref, index, viewRef);
  }

  indexOf(viewRef: ViewRef): number {
    return ListWrapper.indexOf(this._element.nestedViews, (<ViewRef_>viewRef).internalView);
  }

  // TODO(i): rename to destroy
  remove(index: number = -1): void {
    if (index == -1) index = this.length - 1;
    var vm = this._element.parentView.viewManager;
    return vm.destroyViewInContainer(this._element.ref, index);
    // view is intentionally not returned to the client.
  }

  // TODO(i): refactor insert+remove into move
  detach(index: number = -1): EmbeddedViewRef {
    if (index == -1) index = this.length - 1;
    var vm = this._element.parentView.viewManager;
    return vm.detachViewInContainer(this._element.ref, index);
  }
}


text:
module.exports = function (grunt) {
    grunt.config(['replace', 'prepStageDeploy'], {
        src: ['tmp/*/**.*'],
        overwrite: true,
        replacements: [{
            from: '<%= env.local.domain %>',
            to:   '<%= env.stage.domain %>'
        }, {
            from: '<%= env.local.domainStatic %>',
            to:   '<%= env.stage.domainStatic %>'
        }]
    });
    grunt.config(['copy', 'stageDeploy'], {
        files: [
            {expand: true, cwd: 'tmp', src: ['**'], dest: '<%= env.stage.mount %>/news/special/<%= config.year %>/newsspec_<%= config.project_number %>/content'}
        ]
    });
    grunt.loadNpmTasks('grunt-text-replace');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.registerTask('stage', ['shell:checkMounts', 'stage_checklist', 'prepDeploy', 'replace:prepStageDeploy', 'copy:stageDeploy', 'clean:main']);
};


text:
require 'polisher/gem'

module Polisher
  # Mixin included in components that contain lists of dependencies
  # which include version information
  #
  # Requires module define 'deps' method which returns list
  # of gem names representing component dependencies. List
  # will be iterated over, versions will be looked up
  # recursively and returned
  module VersionedDependencies
    # Return specified dependency
    def dependency_for(name)
      deps.detect { |dep| dep.name == name }
    end

    # Return list of versions of dependencies of component.
    def dependency_versions(args = {}, &bl)
      versions = {}
      args = {:recursive => true, :dev_deps  => true, :versions => versions}.merge(args)
      deps.each do |dep|
        gem = Polisher::Gem.retrieve(dep.name)
        versions.merge!(gem.versions(args, &bl))
      end
      versions
    end

    # Return mapping of gems to dependency versions
    def dependency_tree(args = {}, &bl)
      dependencies = {}
      args = {:recursive    => true,
              :dev_deps     => true,
              :matching     => :latest,
              :dependencies => dependencies}.merge(args)

      process = []
      deps.each do |dep|
        resolved = nil
        begin
          resolved = Polisher::Gem.matching(dep, args[:matching])
        rescue
        end
        yield self, dep, resolved
        process << resolved unless resolved.nil?
      end

      process.each { |dep|
        dependencies.merge!(dep.dependency_tree(args, &bl))
      }

      dependencies
    end

    # Return missing dependencies
    def missing_dependencies
      missing = []
      dependency_versions(:recursive => false).each do |pkg, target_versions|
        found = false
        target_versions.each do |_target, versions|
          dependency = dependency_for(pkg)
          found = versions.any? { |version| dependency.match?(pkg, version) }
        end
        missing << pkg unless found
      end
      missing
    end

    # Return bool indicating if all dependencies are satisfied
    def dependencies_satisfied?
      missing_dependencies.empty?
    end

    # Return list of states which gem dependencies are in
    def dependency_states
      states = {}
      deps.each do |dep|
        gem = Polisher::Gem.new :name => dep.name
        states.merge! dep.name => gem.state(:check => dep)
      end
      states
    end
  end
end


text:
package workbench.db.h2database;

import org.junit.AfterClass;
import org.junit.Test;
import workbench.TestUtil;
import workbench.WbTestCase;
import workbench.db.ConnectionMgr;
import workbench.db.IndexReader;
import workbench.db.TableIdentifier;
import workbench.db.WbConnection;
import static org.junit.Assert.*;
import workbench.db.*;

/**
 *
 * @author Thomas Kellerer
 */
public class H2IndexReaderTest
	extends WbTestCase
{

	public H2IndexReaderTest()
	{
		super("H2IndexReaderTest");
	}

	@AfterClass
	public static void tearDownClass()
		throws Exception
	{
		ConnectionMgr.getInstance().disconnectAll();
	}

	@Test
	public void testGetPrimaryKeyIndex()
		throws Exception
	{
		TestUtil util = getTestUtil();
		WbConnection con = util.getConnection();
		TestUtil.executeScript(con, "create table person (id integer primary key, person_name varchar(100));");
		TableIdentifier tbl = new TableIdentifier("PERSON");
		IndexReader reader = con.getMetadata().getIndexReader();
		assertTrue(reader instanceof H2IndexReader);
		PkDefinition pk = reader.getPrimaryKey(tbl);
		assertNotNull(pk);
		assertEquals(1, pk.getColumns().size());
		assertEquals("ID", pk.getColumns().get(0));
		assertTrue(pk.getPkName().startsWith("CONSTRAINT"));
	}
}


text:
package org.apache.slide.projector.processor.resolver;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;

import org.apache.slide.projector.Context;
import org.apache.slide.projector.descriptor.ParameterDescriptor;
import org.apache.slide.projector.descriptor.ResultEntryDescriptor;
import org.apache.slide.projector.descriptor.StringValueDescriptor;
import org.apache.slide.projector.i18n.DefaultMessage;
import org.apache.slide.projector.i18n.ParameterMessage;
import org.apache.slide.projector.processor.SimpleProcessor;
import org.apache.slide.projector.value.LocaleValue;
import org.apache.slide.projector.value.StringValue;
import org.apache.slide.projector.value.Value;

/**
 * @version $Revision: 1.2 $
 */
public class LocaleResolver extends SimpleProcessor {
    private final static ParameterDescriptor parameterDescriptor = new ParameterDescriptor(INPUT, new ParameterMessage("localeResolver/locale"), new StringValueDescriptor(), new StringValue(Locale.getDefault().toString()));
    private final static ResultEntryDescriptor resultEntryDescriptor =  new ResultEntryDescriptor(SimpleProcessor.OUTPUT, new DefaultMessage("locale/result/output"), LocaleValue.CONTENT_TYPE, false);

    public Value process(Value input, Context context) throws Exception {
        List acceptedLanguages = new ArrayList();
        StringTokenizer tokenizer = new StringTokenizer(input.toString(), ",");
        while ( tokenizer.hasMoreTokens() ) {
            String localeToken = tokenizer.nextToken();
            double q = 1.0;
            int qIndex = localeToken.indexOf(";q=");
            if ( qIndex > 0 ) {
                q = Double.parseDouble(localeToken.substring(qIndex+3));
                localeToken = localeToken.substring(0, qIndex);
            }
            // FIXME: Only add values that are supported by the current webapp (configure globally)
            acceptedLanguages.add(new AcceptedLanguage(q, new Locale(localeToken)));
        }
        Collections.sort(acceptedLanguages);
        return new LocaleValue(((AcceptedLanguage)acceptedLanguages.get(0)).getLocale());
    }

    public ParameterDescriptor getParameterDescriptor() {
        return parameterDescriptor;
    }

    public ResultEntryDescriptor getResultEntryDescriptor() {
        return resultEntryDescriptor;
    }

    class AcceptedLanguage implements Comparable {
        double q;
        Locale locale;

        public AcceptedLanguage(double q, Locale locale) {
            this.q = q;
            this.locale = locale;
        }

        public Locale getLocale() {
            return locale;
        }

        public double getQ() {
            return q;
        }

        public int compareTo(Object a) {
            if ( ((AcceptedLanguage)a).getQ() < q ) return -1;
            if ( ((AcceptedLanguage)a).getQ() > q ) return 1;
            return 0;
        }
    }
}


text:
package org.arquillian.cube.openshift.impl.adapter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;
import org.arquillian.cube.openshift.impl.client.CubeOpenShiftConfiguration;
import org.arquillian.cube.openshift.impl.proxy.Proxy;
import org.arquillian.cube.openshift.impl.resources.OpenShiftResourceHandle;
import org.arquillian.cube.openshift.impl.utils.Checker;
import org.arquillian.cube.openshift.impl.utils.Containers;
import org.arquillian.cube.openshift.impl.utils.DeploymentContext;
import org.arquillian.cube.openshift.impl.utils.Operator;
import org.arquillian.cube.openshift.impl.utils.ReflectionUtils;
import org.jboss.arquillian.container.spi.client.protocol.metadata.ProtocolMetaData;
import org.jboss.arquillian.core.api.Instance;
import org.jolokia.client.request.J4pRequest;
import org.jolokia.client.request.J4pResponse;
import org.json.simple.JSONAware;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

/**
 * @author Ales Justin
 */
public abstract class AbstractOpenShiftAdapter implements OpenShiftAdapter {
    protected final Logger log = Logger.getLogger(getClass().getName());

    protected final CubeOpenShiftConfiguration configuration;
    private Map<String, List<OpenShiftResourceHandle>> resourcesMap = new ConcurrentHashMap<>();
    private Proxy proxy;
    private Instance<ProtocolMetaData> pmdInstance;

    protected AbstractOpenShiftAdapter(CubeOpenShiftConfiguration configuration) {
        this.configuration = configuration;
    }

    public void setProtocolMetaData(Instance<ProtocolMetaData> pmd) {
        this.pmdInstance = pmd;
    }

    protected abstract Proxy createProxy();

    public String url(String podName, int port, String path, String parameters) {
        return getProxy().url(podName, port, path, parameters);
    }

    public InputStream execute(String podName, int port, String path) throws Exception {
        return getProxy().post(podName, port, path);
    }

    public InputStream execute(int pod, int port, String path) throws Exception {
        ProtocolMetaData pmd = pmdInstance.get();
        if (pmd != null) {
            Map<String, String> labels = DeploymentContext.getDeploymentContext(pmd).getLabels();
            return execute(labels, pod, port, path);
        } else {
            throw new IllegalStateException("No ProtocolMetaData set!");
        }
    }

    public InputStream execute(Map<String, String> labels, int pod, int port, String path) throws Exception {
        return getProxy().post(labels, pod, port, path);
    }

    public synchronized Proxy getProxy() {
        if (proxy == null) {
            proxy = createProxy();
        }
        return proxy;
    }

    private void addResourceHandle(String resourcesKey, OpenShiftResourceHandle handle) {
        List<OpenShiftResourceHandle> list = resourcesMap.get(resourcesKey);
        if (list == null) {
            list = new ArrayList<>();
            resourcesMap.put(resourcesKey, list);
        }
        list.add(handle);
    }

    protected abstract OpenShiftResourceHandle createResourceFromStream(InputStream stream) throws IOException;

    public Object createResource(String resourcesKey, InputStream stream) throws IOException {
        OpenShiftResourceHandle resourceHandle = createResourceFromStream(stream);
        addResourceHandle(resourcesKey, resourceHandle);
        return resourceHandle;
    }

    public Object deleteResources(String resourcesKey) {
        List<OpenShiftResourceHandle> list = resourcesMap.remove(resourcesKey);
        if (list != null) {
            for (OpenShiftResourceHandle resource : list) {
                resource.delete();
            }
        }
        return list;
    }

    protected abstract OpenShiftResourceHandle createRoleBinding(String roleRefName, String userName);

    public Object addRoleBinding(String resourcesKey, String roleRefName, String userName) {
        OpenShiftResourceHandle handle = createRoleBinding(roleRefName, userName);
        addResourceHandle(resourcesKey, handle);
        return handle;
    }

    protected abstract Map<String, String> getLabels(String prefix) throws Exception;

    public void waitForReadyPods(String prefix, int replicas) throws Exception {
        final Map<String, String> labels = getLabels(prefix);
        Containers.delay(configuration.getStartupTimeout(), 4000L, new PodCountChecker(labels, Operator.EQUAL, replicas));
    }

    public void replacePods(String prefix, int size, final int replicas) throws Exception {
        final Map<String, String> labels = getLabels(prefix);

        final Set<String> deleted = new HashSet<>();
        for (String pod : getProxy().getReadyPods(labels)) {
            if (size <= 0) {
                break;
            }
            deleted.add(pod);
            deletePod(pod, -1); // use default grace period?
            size--;
        }

        Containers.delay(configuration.getStartupTimeout(), 4000L, new PodCountChecker(labels, Operator.EQUAL, replicas) {
            @Override
            protected Set<String> getReadyPods() {
                Set<String> pods = super.getReadyPods();
                pods.removeAll(deleted);
                return pods;
            }
        });
    }

    public Set<String> getReadyPods(String prefix) throws Exception {
        return getProxy().getReadyPods(getLabels(prefix));
    }

    public List<String> getPods() throws Exception {
        return getPods(null);
    }

    public void delay(final Map<String, String> labels, final int replicas, final Operator op) throws Exception {
        Containers.delay(configuration.getStartupTimeout(), 4000L, new PodCountChecker(labels, op, replicas));
    }

    public <T> T jolokia(Class<T> expectedReturnType, String podName, Object input) throws Exception {
        if (input instanceof J4pRequest == false) {
            throw new IllegalArgumentException("Input must be a J4pRequest instance!");
        }

        Proxy proxy = getProxy();

        String url = proxy.url(podName, "https", 8778, "/jolokia/", null);
        log.info(String.format("Jolokia URL: %s", url));

        J4pRequest request = (J4pRequest) input;
        JSONObject jsonObject = ReflectionUtils.invoke(J4pRequest.class, "toJson", new Class[0], request, new Object[0], JSONObject.class);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (OutputStreamWriter out = new OutputStreamWriter(baos)) {
            jsonObject.writeJSONString(out);
            out.flush();
        }

        byte[] bytes = baos.toByteArray(); // copy
        baos.reset(); // re-use
        try (InputStream stream = proxy.post(url, "application/json", bytes)) {
            byte[] buffer = new byte[512];
            int numRead;
            while ((numRead = stream.read(buffer, 0, buffer.length)) >= 0) {
                baos.write(buffer, 0, numRead);
            }
        }
        String content = baos.toString();

        JSONParser parser = new JSONParser();
        JSONAware parseResult;
        try {
            parseResult = (JSONAware) parser.parse(content);
        } catch (ParseException e) {
            throw new IllegalArgumentException("Invalid Jolokia response: " + content);
        }
        if (parseResult instanceof JSONObject == false) {
            throw new IllegalStateException("Invalid JSON answer for a single request (expected a map but got a " + parseResult.getClass() + ")");
        }
        J4pResponse response = ReflectionUtils.invoke(J4pRequest.class, "createResponse", new Class[]{JSONObject.class}, request, new Object[]{parseResult}, J4pResponse.class);
        return expectedReturnType.cast(response.getValue());
    }

    private class PodCountChecker implements Checker {
        private final Map<String, String> labels;
        private final Operator op;
        private final int replicas;

        public PodCountChecker(Map<String, String> labels, Operator op, int replicas) {
            this.labels = labels;
            this.op = op;
            this.replicas = replicas;
        }

        public boolean check() {
            Set<String> pods = getReadyPods();
            boolean result = op.op(pods.size(), replicas);
            if (result) {
                log.info(String.format("Condition satisfied: number of pod(s) matching labels: %s is %s %s (pods: %s)", labels, op, replicas, pods));
            }
            return result;
        }

        protected Set<String> getReadyPods() {
            return getProxy().getReadyPods(labels);
        }

        @Override
        public String toString() {
            return String.format("Number of pod(s) matching labels: %s is %s %s", labels, op, replicas);
        }
    }
}


text:
class CreateDataSrcs < ActiveRecord::Migration
  def change
    create_table :data_srcs do |t|
      t.string :code
      t.string :name
      t.text :remark

      t.timestamps
    end
  end
end


text:
<?php

namespace {{ namespace }}\Controller;

use Kunstmaan\AdminListBundle\AdminList\Configurator\AdminListConfiguratorInterface;
use Kunstmaan\AdminListBundle\Controller\AdminListController;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use {{ namespace }}\AdminList\{{ entity_class }}AdminListConfigurator;

/**
 * The admin list controller for {{ entity_class }}
 */
class {{ entity_class }}AdminListController extends AdminListController
{
    /**
     * @var AdminListConfiguratorInterface
     */
    private $configurator;

    /**
     * @return AdminListConfiguratorInterface
     */
    public function getAdminListConfigurator()
    {
        if (!isset($this->configurator)) {
            $this->configurator = new {{ entity_class }}AdminListConfigurator($this->getEntityManager());
        }

        return $this->configurator;
    }

    /**
     * The index action
     *
     * @Route("/", name="{{ bundle.getName()|lower }}_admin_{{ entity_class|lower }}")
     */
    public function indexAction(Request $request)
    {
        return parent::doIndexAction($this->getAdminListConfigurator(), $request);
    }

    /**
     * The add action
     *
     * @Route("/add", name="{{ bundle.getName()|lower }}_admin_{{ entity_class|lower }}_add", methods={"GET", "POST"})
     * @return array
     */
    public function addAction(Request $request)
    {
        return parent::doAddAction($this->getAdminListConfigurator(), null, $request);
    }

    /**
     * The edit action
     *
     * @param int $id
     *
     * @Route("/{id}", requirements={"id" = "\d+"}, name="{{ bundle.getName()|lower }}_admin_{{ entity_class|lower }}_edit", methods={"GET", "POST"})
     *
     * @return array
     */
    public function editAction(Request $request, $id)
    {
        return parent::doEditAction($this->getAdminListConfigurator(), $id, $request);
    }

    /**
     * The view action
     *
     * @param int $id
     *
     * @Route("/{id}/view", requirements={"id" = "\d+"}, name="{{ bundle.getName()|lower }}_admin_{{ entity_class|lower }}_view", methods={"GET"})
     *
     * @return array
     */
    public function viewAction(Request $request, $id)
    {
        return parent::doViewAction($this->getAdminListConfigurator(), $id, $request);
    }

    /**
     * The delete action
     *
     * @param int $id
     *
     * @Route("/{id}/delete", requirements={"id" = "\d+"}, name="{{ bundle.getName()|lower }}_admin_{{ entity_class|lower }}_delete", methods={"GET", "POST"})
     *
     * @return array
     */
    public function deleteAction(Request $request, $id)
    {
        return parent::doDeleteAction($this->getAdminListConfigurator(), $id, $request);
    }

    /**
     * The export action
     *
     * @param string $_format
     *
     * @Route("/export.{_format}", requirements={"_format" = "{{ export_extensions }}"}, name="{{ bundle.getName()|lower }}_admin_{{ entity_class|lower }}_export", methods={"GET", "POST"})
     * @return array
     */
    public function exportAction(Request $request, $_format)
    {
        return parent::doExportAction($this->getAdminListConfigurator(), $_format, $request);
    }

{% if sortField %}
    /**
     * The move up action
     *
     * @param int $id
     *
     * @Route("/{id}/move-up", requirements={"id" = "\d+"}, name="{{ bundle.getName()|lower }}_admin_{{ entity_class|lower }}_move_up", methods={"GET"})
     *
     * @return array
     */
    public function moveUpAction(Request $request, $id)
    {
    return parent::doMoveUpAction($this->getAdminListConfigurator(), $id, $request);
    }

    /**
     * The move down action
     *
     * @param int $id
     *
     * @Route("/{id}/move-down", requirements={"id" = "\d+"}, name="{{ bundle.getName()|lower }}_admin_{{ entity_class|lower }}_move_down", methods={"GET"})
     *
     * @return array
     */
    public function moveDownAction(Request $request, $id)
    {
    return parent::doMoveDownAction($this->getAdminListConfigurator(), $id, $request);
    }
{% endif %}

}


text:
module Types
  class GroupType < NamespaceType
    graphql_name 'Group'

    authorize :read_group

    expose_permissions Types::PermissionTypes::Group

    field :web_url, GraphQL::STRING_TYPE, null: false # rubocop:disable Graphql/Descriptions

    field :avatar_url, GraphQL::STRING_TYPE, null: true, resolve: -> (group, args, ctx) do # rubocop:disable Graphql/Descriptions
      group.avatar_url(only_path: false)
    end

    field :parent, GroupType, # rubocop:disable Graphql/Descriptions
          null: true,
          resolve: -> (obj, _args, _ctx) { Gitlab::Graphql::Loaders::BatchModelLoader.new(Group, obj.parent_id).find }
  end
end

Types::GroupType.prepend_if_ee('EE::Types::GroupType')


text:
package wsimport.extension_jms_transport.server;

import jakarta.jws.WebMethod;
import jakarta.jws.WebResult;
import jakarta.jws.WebParam;
import jakarta.jws.WebService;

/**
 * @author Rama Pulavarthi
 */
@WebService(endpointInterface = "wsimport.extension_jms_transport.server.EchoServicePortType")
public class EchoImpl implements wsimport.extension_jms_transport.server.EchoServicePortType{
    @WebMethod(action = "echoOperation")
    @WebResult(name = "echoStringResponse", targetNamespace = "http://wssample/sei/echo/", partName = "parameter")
    public EchoStringResponse echoOperation(@WebParam(name = "echoStringInput", targetNamespace = "http://wssample/sei/echo/", partName = "parameter")
    EchoStringInput parameter) {
        //dummy impl
        return null;
    }
}


text:
app.controller('AdminEntryTypeCtrl', ['$scope', 'business', '$rootScope', '$uiModal', '$timeout', 'FileUploader',
  function ($scope, Business, $rootScope, $uiModal, $timeout, FileUploader) {

    $scope.addEntryType = function () {
      var modalInstance = $uiModal.open({
        templateUrl: 'views/admin/data_management/editEntryTypeForm.html',
        controller: 'AdminEntryTypeFormCtrl',
        backdrop: 'static',
        size: 'sm',
        resolve: {
        }
      });
    };

  }
]);

app.controller('AdminEntryTypeFormCtrl', ['$scope', 'business', '$uiModal', '$uiModalInstance',
  function ($scope, Business, $uiModal, $uiModalInstance) {

    $scope.close = function () {
      $uiModalInstance.dismiss('cancel');
    };
  }
]);


text:
#region License

#endregion

using System.Numerics;

namespace Revise.Files.ZSC {
    /// <summary>
    /// Represents a model list part.
    /// </summary>
    public class ModelListPart {
        #region Constants

        public const int MONSTER_ANIMATION_COUNT = 5;
        public const int AVATAR_ANIMATION_COUNT = 16;
        public const int ANIMATION_COUNT = MONSTER_ANIMATION_COUNT + AVATAR_ANIMATION_COUNT;

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the model.
        /// </summary>
        public short Model {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the texture.
        /// </summary>
        public short Texture {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the position.
        /// </summary>
        public Vector3 Position {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the rotation.
        /// </summary>
        public Quaternion Rotation {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the scale.
        /// </summary>
        public Vector3 Scale {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the axis rotation.
        /// </summary>
        public Quaternion AxisRotation {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the parent.
        /// </summary>
        public short Parent {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the collision type and flags.
        /// </summary>
        public CollisionType Collision {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the animation file path.
        /// </summary>
        public string AnimationFilePath {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the visible range set to use from the RangeSet.STB <see cref="DataFile"/>.
        /// </summary>
        public short VisibleRangeSet {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a value indicating whether to use lightmaps.
        /// </summary>
        public bool UseLightmap {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the bone index.
        /// </summary>
        public short BoneIndex {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the dummy bone index.
        /// </summary>
        public short DummyIndex {
            get;
            set;
        }

        /// <summary>
        /// Gets the monster animation file paths.
        /// </summary>
        public string[] MonsterAnimations {
            get;
            private set;
        }

        /// <summary>
        /// Gets the avatar animation file paths.
        /// </summary>
        public string[] AvatarAnimations {
            get;
            private set;
        }

        #endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="ModelListPart"/> class.
        /// </summary>
        public ModelListPart() {
            AnimationFilePath = string.Empty;
            MonsterAnimations = new string[MONSTER_ANIMATION_COUNT];
            AvatarAnimations = new string[AVATAR_ANIMATION_COUNT];

            for (int i = 0; i < MONSTER_ANIMATION_COUNT; i++) {
                MonsterAnimations[i] = string.Empty;
            }

            for (int i = 0; i < AVATAR_ANIMATION_COUNT; i++) {
                AvatarAnimations[i] = string.Empty;
            }
        }
    }
}


text:
\documentclass{article}

\usepackage{arxiv}

\usepackage[utf8]{inputenc} % allow utf-8 input
\usepackage[T1]{fontenc}    % use 8-bit T1 fonts
\usepackage{hyperref}       % hyperlinks
\usepackage{url}            % simple URL typesetting
\usepackage{booktabs}       % professional-quality tables
\usepackage{amsfonts}       % blackboard math symbols
\usepackage{nicefrac}       % compact symbols for 1/2, etc.
\usepackage{microtype}      % microtypography
\usepackage{lipsum}

\usepackage{hyperref}

\usepackage{amsmath}

\usepackage{graphicx}

\usepackage[justification=centering]{caption}
\usepackage{subcaption}

\usepackage{listings}
\usepackage{xcolor}
\lstset{
    numbers=left,
    numberstyle= \tiny,
    keywordstyle= \color{ blue!70},
    commentstyle= \color{red!50!green!50!blue!50},
    frame=shadowbox,
    rulesepcolor= \color{ red!20!green!20!blue!20} ,
    escapeinside=``,
    xleftmargin=2em,xrightmargin=2em, aboveskip=1em,
    framexleftmargin=2em
}

\title{Deep Learning Specialization\thanks{This is the specialization at Coursera taught by Professor Andrew Ng.}}

\author{
    Kai Yi\thanks{The author received his B.Eng with honor from Department of Software Engineering, Xi'an Jiaotong University in June 2019. His current research interests include cognition-based artificial intelligence, machine learning, computer vision and conputational psychology. His homepage is kaiyi.me. Now, he is planning to pursue PhD studies.}\\
%   Department of Computer Science\\
%   Cranberry-Lemon University\\
%   Pittsburgh, PA 15213 \\
  \texttt{williamyi96@gmail.com} \\

}

\begin{document}
\maketitle

\begin{abstract}
% \lipsum[1]

% \lipsum[2]

% \lipsum[3]

% \lipsum[4]
This paper is the notes of Deep Learning Specialization at Coursera taught by Prof. Andrew Ng. There are five courses in this specialization. They are \textit{Neural Network and Deep Learning (NN Overview)}. \textit{Improving Deep Neural Networks : Hyperparameter tuning, Regularization and Optimization (Optimization)}, \textit{Structuring Machine Learning Projects (NN-Projects)}, \textit{Convolutional Neural Networks (CNNs)} and \textit{Sequence Model (SNNs)}, respectively.

Course \textit{NN Overview} mainly talks about the foundations of deep learning. It includes the major technology trends driving deep learning, the  building, training and applying of fully connected deep neural network, the vectorization technology improving network efficiency and the key parameters in a neural network's architecture. Course \textit{Optimization} represents the key rules to improve neural networks' performance. It includes the industry best-practices for building deep learning applications, and a variety of tricks about hyperparameter tuning, regularization and optimization. More information about the rest three courses will conclude here later.

\end{abstract}

\newpage
\tableofcontents
\newpage
\listoffigures
\newpage
\listoftables
\newpage

% keywords can be removed
% \keywords{First keyword \and Second keyword \and More}

% \input{update.tex}
% \input{introduction.tex}
% \input{data-preprocessing}
\input{Course1.tex}
\input{Course2.tex}
\input{Course3.tex}
\input{Course4.tex}
\input{Course5.tex}
% \input{experiments.tex}

% \input{cnn-encoder.tex}

\section*{Acknowledgements}
This note is heavily based on Prof. Andrew Ng's course at Coursera. Thanks Andrew for taking this wonderful course, I've learnt a lot from that. Besides, thanks Coursera for providing me full-funded financial aids to finish all the five courses in the specialization. Moreover, parts of the note are borrowed from Mahmoud Badry's github repository\footnote{https://github.com/mbadry1/DeepLearning.ai-Summary}. It gives me a clear panorama of what is the most important.

\bibliographystyle{unsrt}
\bibliography{references}  %%% Remove comment to use the external .bib file (using bibtex).
%%% and comment out the ``thebibliography'' section.

% \input{appendix.tex}

\end{document}


text:
/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * class NestedInteger {
 *   public:
 *     // Constructor initializes an empty nested list.
 *     NestedInteger();
 *
 *     // Constructor initializes a single integer.
 *     NestedInteger(int value);
 *
 *     // Return true if this NestedInteger holds a single integer, rather than a nested list.
 *     bool isInteger() const;
 *
 *     // Return the single integer that this NestedInteger holds, if it holds a single integer
 *     // The result is undefined if this NestedInteger holds a nested list
 *     int getInteger() const;
 *
 *     // Set this NestedInteger to hold a single integer.
 *     void setInteger(int value);
 *
 *     // Set this NestedInteger to hold a nested list and adds a nested integer to it.
 *     void add(const NestedInteger &ni);
 *
 *     // Return the nested list that this NestedInteger holds, if it holds a nested list
 *     // The result is undefined if this NestedInteger holds a single integer
 *     const vector<NestedInteger> &getList() const;
 * };
 */
class Solution {
    public:
        NestedInteger deserialize(string s) {
            int pos = 0;
            return deserialize(s, pos);
        }
        NestedInteger deserialize(string s, int &pos) {
            // number
            if (s[pos] == '-' || isdigit(s[pos])) {
                int start = pos;
                while (s[pos] == '-' || isdigit(s[pos])) pos++;
                return NestedInteger(stoi(s.substr(start, pos - start)));
            }
            // list
            pos++; // skip [
            NestedInteger ret;
            while (s[pos] != ']') {
                if (s[pos] == ',') pos++;
                ret.add(deserialize(s, pos));
            }
            pos++; // skip ]
            return ret;
        }
};


text:
import Bench from 'benchmark'
import { writeFile, ensureDir } from 'fs-extra'
import { dirname } from 'path'
import { cloneDeep } from 'lodash'

export class Benchmark {
  key;
  config;

  constructor (key, config = {}) {
    Object.assign(this, { key, config })
  }

  async run (task) {
    async function fn (defer) {
      await task()
      defer.resolve()
    }

    this.results = []

    await new Promise((resolve) => {
      const bench = new Bench(this.key, {
        defer: true,
        async: true,
        onComplete: resolve,
        onCycle: (event) => {
          this.results.push(cloneDeep(event.target))

          if (this.config.onCycle) { this.config.onCycle(event) }
        },
        fn,
        ...this.config
      })

      bench.run()
    })

    return this
  }

  serialize (results = this.results) {
    return results.slice(-3).map((result) => {
      return String(result)
    }).join('\n')
  }

  async saveSnapshot (filePath, results = this.results) {
    const dir = dirname(filePath)

    await ensureDir(dir)
    return writeFile(filePath, this.serialize(results), 'utf8')
  }
}


text:
package com.unkonw.testapp.libs.base;

import android.content.Context;
import android.graphics.Bitmap;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.utils.L;
import com.unkonw.testapp.libs.common.ActivityPageManager;

import solid.ren.skinlibrary.base.SkinBaseApplication;

/**
 * 基础的Application
 **/
public class BaseApplication extends SkinBaseApplication {
    private final String tag = BaseApplication.class.getSimpleName();
    private static DisplayImageOptions options;
    private static BaseApplication instance;
    public static Context myContext;
    /*
     * 是否完成  整个项目
     */
    public static boolean isCompleteProject = false;

    public static ImageLoader imageLoader;
    public static final boolean ISDEBUG = false;

    public static BaseApplication getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        myContext = this;
        init();

    }

    /**
     * 初始化
     */
    private void init() {

//        LogUtil.setDebug(!isCompleteProject);
//        LogUtil.e(tag, "isDebug: " + !isCompleteProject);
        initImageLoader();

//        CrashHandler.create(this);

//        JPushInterface.init(this); // 初始化JPush
//        JPushInterface.setDebugMode(true);  // 设置日志,发布时请关闭日志

    }

    private void initImageLoader() {

        //获取系统分配给每个应用程序的最大内存,每个应用系统分配32M
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int mCacheSize = maxMemory / 8;
        //给LruCache分配1/8 4M

        options =new DisplayImageOptions.Builder()
                .cacheInMemory(true).cacheOnDisk(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .resetViewBeforeLoading(true)
                .considerExifParams(true)
                .build();

        //初始化图片下载组件
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .diskCacheSize(100 * 1024 * 1024)
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .memoryCache(new LruMemoryCache(mCacheSize))
                .imageDownloader(new AuthImageDownloader(this))
                .defaultDisplayImageOptions(options)

                .build();
        ImageLoader.getInstance().init(config);
        imageLoader = ImageLoader.getInstance();
        //关闭 打开log  imgelog
        L.writeLogs(false);

    }

    /**
     * 退出应用
     */
    public void exit() {
        ActivityPageManager.getInstance().exit(this);
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 11(5): 452 (1913)

#### Original name
Lembosia cliftoniae Tracy & Earle

### Remarks
null


text:
#ifndef BOOST_MPL_SEQUENCE_TAG_HPP_INCLUDED
#define BOOST_MPL_SEQUENCE_TAG_HPP_INCLUDED

// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.lslboost.org/LICENSE_1_0.txt)
//
// See http://www.lslboost.org/libs/mpl for documentation.

// $Id: sequence_tag.hpp 49267 2008-10-11 06:19:02Z agurtovoy $
// $Date: 2008-10-11 02:19:02 -0400 (Sat, 11 Oct 2008) $
// $Revision: 49267 $

#include <lslboost/mpl/sequence_tag_fwd.hpp>
#include <lslboost/mpl/aux_/has_tag.hpp>
#include <lslboost/mpl/aux_/has_begin.hpp>
#include <lslboost/mpl/aux_/na_spec.hpp>
#include <lslboost/mpl/aux_/is_msvc_eti_arg.hpp>
#include <lslboost/mpl/aux_/config/eti.hpp>
#include <lslboost/mpl/aux_/yes_no.hpp>
#include <lslboost/mpl/aux_/config/workaround.hpp>

namespace lslboost { namespace mpl {

// agurt, 27/nov/02: have to use a simplistic 'sequence_tag' implementation
// on MSVC to avoid dreadful "internal structure overflow" error
#if BOOST_WORKAROUND(BOOST_MSVC, < 1300) \
    || defined(BOOST_MPL_CFG_NO_HAS_XXX)

template<
      typename BOOST_MPL_AUX_NA_PARAM(Sequence)
    >
struct sequence_tag
{
    typedef typename Sequence::tag type;
};

#elif BOOST_WORKAROUND(BOOST_MSVC, == 1300)

// agurt, 07/feb/03: workaround for what seems to be MSVC 7.0-specific ETI issue

namespace aux {

template< bool >
struct sequence_tag_impl
{
    template< typename Sequence > struct result_
    {
        typedef typename Sequence::tag type;
    };
};

template<>
struct sequence_tag_impl<false>
{
    template< typename Sequence > struct result_
    {
        typedef int type;
    };
};

} // namespace aux

template<
      typename BOOST_MPL_AUX_NA_PARAM(Sequence)
    >
struct sequence_tag
    : aux::sequence_tag_impl< !aux::is_msvc_eti_arg<Sequence>::value >
        ::template result_<Sequence>
{
};

#else

namespace aux {

template< bool has_tag_, bool has_begin_ >
struct sequence_tag_impl
{
    // agurt 24/nov/02: MSVC 6.5 gets confused in 'sequence_tag_impl<true>'
    // specialization below, if we name it 'result_' here
    template< typename Sequence > struct result2_;
};

#   define AUX_CLASS_SEQUENCE_TAG_SPEC(has_tag, has_begin, result_type) \
template<> struct sequence_tag_impl<has_tag,has_begin> \
{ \
    template< typename Sequence > struct result2_ \
    { \
        typedef result_type type; \
    }; \
}; \
/**/

AUX_CLASS_SEQUENCE_TAG_SPEC(true, true, typename Sequence::tag)
AUX_CLASS_SEQUENCE_TAG_SPEC(true, false, typename Sequence::tag)
AUX_CLASS_SEQUENCE_TAG_SPEC(false, true, nested_begin_end_tag)
AUX_CLASS_SEQUENCE_TAG_SPEC(false, false, non_sequence_tag)

#   undef AUX_CLASS_SEQUENCE_TAG_SPEC

} // namespace aux

template<
      typename BOOST_MPL_AUX_NA_PARAM(Sequence)
    >
struct sequence_tag
    : aux::sequence_tag_impl<
          ::lslboost::mpl::aux::has_tag<Sequence>::value
        , ::lslboost::mpl::aux::has_begin<Sequence>::value
        >::template result2_<Sequence>
{
};

#endif // BOOST_MSVC

BOOST_MPL_AUX_NA_SPEC(1, sequence_tag)

}}

#endif // BOOST_MPL_SEQUENCE_TAG_HPP_INCLUDED


text:
/**
 * Strict Classifier
 */

module.exports = class StrictClassifier {

/**
 * Constructor
 *
 * @access public
 * @return void
 */
	constructor() {
		this.data = [];
	}

/**
 * Train
 *
 * @param string intent
 * @param string keyword
 * @access public
 * @return void
 */
	train(intent, keyword) {
		this.data.push([keyword, intent]);
	}

/**
 * Find
 *
 * @param string str
 * @access public
 * @return mixed
 */
	find(str) {

		for(var ii=0; ii<this.data.length; ii++) {
			//Vars
			var keyword = this.data[ii][0];
			var intent = this.data[ii][1];

			//Check if regex
			if(keyword instanceof RegExp) {
				if(str.match(keyword)) {
					return {
						confidence: 0.9,
						result: intent
					};
				}
			}
			else if(this.data[ii][0] == str) {
				//String to string
				return {
					confidence: 1,
					result: intent
				};
			}

		}

		return false;
	}

}


text:
// -*- c++ -*-

/*
 * Hamming distances. The binary vector dimensionality should be a
 * multiple of 8, as the elementary operations operate on bytes. If
 * you need other sizes, just pad with 0s (this is done by function
 * fvecs2bitvecs).
 *
 * User-defined type hamdis_t is used for distances because at this time
 * it is still uncler clear how we will need to balance
 * - flexibility in vector size (may need 16- or even 8-bit vectors)
 * - memory usage
 * - cache-misses when dealing with large volumes of data (fewer bits is better)
 *
 */

#ifndef FAISS_hamming_h
#define FAISS_hamming_h

#include <stdint.h>

#include <faiss/impl/platform_macros.h>
#include <faiss/utils/Heap.h>

/* The Hamming distance type */
typedef int32_t hamdis_t;

namespace faiss {

/**************************************************
 * General bit vector functions
 **************************************************/

struct RangeSearchResult;

void bitvec_print(const uint8_t* b, size_t d);

/* Functions for casting vectors of regular types to compact bits.
   They assume proper allocation done beforehand, meaning that b
   should be be able to receive as many bits as x may produce.  */

/* Makes an array of bits from the signs of a float array. The length
   of the output array b is rounded up to byte size (allocate
   accordingly) */
void fvecs2bitvecs(const float* x, uint8_t* b, size_t d, size_t n);

void bitvecs2fvecs(const uint8_t* b, float* x, size_t d, size_t n);

void fvec2bitvec(const float* x, uint8_t* b, size_t d);

/** Shuffle the bits from b(i, j) := a(i, order[j])
 */
void bitvec_shuffle(
        size_t n,
        size_t da,
        size_t db,
        const int* order,
        const uint8_t* a,
        uint8_t* b);

/***********************************************
 * Generic reader/writer for bit strings
 ***********************************************/

struct BitstringWriter {
    uint8_t* code;
    size_t code_size;
    size_t i; // current bit offset

    // code_size in bytes
    BitstringWriter(uint8_t* code, size_t code_size);

    // write the nbit low bits of x
    void write(uint64_t x, int nbit);
};

struct BitstringReader {
    const uint8_t* code;
    size_t code_size;
    size_t i;

    // code_size in bytes
    BitstringReader(const uint8_t* code, size_t code_size);

    // read nbit bits from the code
    uint64_t read(int nbit);
};

/**************************************************
 * Hamming distance computation functions
 **************************************************/

FAISS_API extern size_t hamming_batch_size;

inline int popcount64(uint64_t x) {
    return __builtin_popcountl(x);
}

/** Compute a set of Hamming distances between na and nb binary vectors
 *
 * @param  a             size na * nbytespercode
 * @param  b             size nb * nbytespercode
 * @param  nbytespercode should be multiple of 8
 * @param  dis           output distances, size na * nb
 */
void hammings(
        const uint8_t* a,
        const uint8_t* b,
        size_t na,
        size_t nb,
        size_t nbytespercode,
        hamdis_t* dis);

/** Return the k smallest Hamming distances for a set of binary query vectors,
 * using a max heap.
 * @param a       queries, size ha->nh * ncodes
 * @param b       database, size nb * ncodes
 * @param nb      number of database vectors
 * @param ncodes  size of the binary codes (bytes)
 * @param ordered if != 0: order the results by decreasing distance
 *                (may be bottleneck for k/n > 0.01) */
void hammings_knn_hc(
        int_maxheap_array_t* ha,
        const uint8_t* a,
        const uint8_t* b,
        size_t nb,
        size_t ncodes,
        int ordered);

/* Legacy alias to hammings_knn_hc. */
void hammings_knn(
        int_maxheap_array_t* ha,
        const uint8_t* a,
        const uint8_t* b,
        size_t nb,
        size_t ncodes,
        int ordered);

/** Return the k smallest Hamming distances for a set of binary query vectors,
 * using counting max.
 * @param a       queries, size na * ncodes
 * @param b       database, size nb * ncodes
 * @param na      number of query vectors
 * @param nb      number of database vectors
 * @param k       number of vectors/distances to return
 * @param ncodes  size of the binary codes (bytes)
 * @param distances output distances from each query vector to its k nearest
 *                neighbors
 * @param labels  output ids of the k nearest neighbors to each query vector
 */
void hammings_knn_mc(
        const uint8_t* a,
        const uint8_t* b,
        size_t na,
        size_t nb,
        size_t k,
        size_t ncodes,
        int32_t* distances,
        int64_t* labels);

/** same as hammings_knn except we are doing a range search with radius */
void hamming_range_search(
        const uint8_t* a,
        const uint8_t* b,
        size_t na,
        size_t nb,
        int radius,
        size_t ncodes,
        RangeSearchResult* result);

/* Counting the number of matches or of cross-matches (without returning them)
   For use with function that assume pre-allocated memory */
void hamming_count_thres(
        const uint8_t* bs1,
        const uint8_t* bs2,
        size_t n1,
        size_t n2,
        hamdis_t ht,
        size_t ncodes,
        size_t* nptr);

/* Return all Hamming distances/index passing a thres. Pre-allocation of output
   is required. Use hamming_count_thres to determine the proper size. */
size_t match_hamming_thres(
        const uint8_t* bs1,
        const uint8_t* bs2,
        size_t n1,
        size_t n2,
        hamdis_t ht,
        size_t ncodes,
        int64_t* idx,
        hamdis_t* dis);

/* Cross-matching in a set of vectors */
void crosshamming_count_thres(
        const uint8_t* dbs,
        size_t n,
        hamdis_t ht,
        size_t ncodes,
        size_t* nptr);

/* compute the Hamming distances between two codewords of nwords*64 bits */
hamdis_t hamming(const uint64_t* bs1, const uint64_t* bs2, size_t nwords);

} // namespace faiss

// inlined definitions of HammingComputerXX and GenHammingComputerXX

#include <faiss/utils/hamming-inl.h>

#endif /* FAISS_hamming_h */


text:
package db

import (
	"bytes"
	"crypto/rand"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"math"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/Sirupsen/logrus"
	"github.com/daticahealth/cli/commands/services"
	"github.com/daticahealth/cli/lib/crypto"
	"github.com/daticahealth/cli/lib/jobs"
	"github.com/daticahealth/cli/lib/prompts"
	"github.com/daticahealth/cli/lib/transfer"
	"github.com/daticahealth/cli/models"
)

func CmdImport(databaseName, filePath, mongoCollection, mongoDatabase string, skipBackup bool, id IDb, ip prompts.IPrompts, is services.IServices, ij jobs.IJobs) error {
	singleUploadMode := false
	versionInfo, err := id.RetrievePodApiVersion()
	if versionInfo.Version < "4.1.0" {
		singleUploadMode = true
	}

	if _, err = os.Stat(filePath); os.IsNotExist(err) {
		return fmt.Errorf("A file does not exist at path '%s'", filePath)
	}
	service, err := is.RetrieveByLabel(databaseName)
	if err != nil {
		return err
	}
	if service == nil {
		return fmt.Errorf("Could not find a service with the label \"%s\". You can list services with the \"datica services list\" command.", databaseName)
	}
	if service.Name == "postgresql" {
		fmt.Println("WARNING: Import cannot DROP DATABASE \"catalyzeDB\". Ensure your import individually removes any necessary \"catalyzeDB\" objects, or import only into newly created postgres services where the \"catalyzeDB\" database is already empty.")
	}
	key := make([]byte, crypto.KeySize)
	iv := make([]byte, crypto.IVSize)
	rand.Read(key)
	rand.Read(iv)
	file, err := os.Open(filePath)
	if err != nil {
		return err
	}
	defer file.Close()
	fi, err := file.Stat()
	if err != nil {
		return err
	}
	encryptFileReader, err := id.NewEncryptReader(file, key, iv)
	if err != nil {
		return err
	}
	uploadSize := encryptFileReader.CalculateTotalSize(int(fi.Size()))
	fiveGB := transfer.GB * 5
	if singleUploadMode && transfer.ByteSize(uploadSize) > fiveGB {
		return fmt.Errorf("The encrypted size of %s exceeds the maximum upload size of %s", filePath, fiveGB)
	}
	fiveTB := transfer.TB * 5
	if transfer.ByteSize(uploadSize) > fiveTB {
		return fmt.Errorf("The encrypted size of %s exceeds the maximum upload size of %s", filePath, fiveTB)
	}
	rt := transfer.NewReaderTransfer(encryptFileReader, uploadSize)
	if !skipBackup {
		logrus.Printf("Backing up \"%s\" before performing the import", databaseName)
		job, err := id.Backup(service)
		if err != nil {
			return err
		}
		logrus.Printf("Backup started (job ID = %s)", job.ID)

		// all because logrus treats print, println, and printf the same
		logrus.Println("Polling until backup finishes.")
		if job.IsSnapshotBackup != nil && *job.IsSnapshotBackup {
			logrus.Printf("This is a snapshot backup, it may be a while before this backup shows up in the \"datica db list %s\" command.", databaseName)
			err = ij.WaitToAppear(job.ID, service.ID)
			if err != nil {
				return err
			}
		}
		status, err := ij.PollTillFinished(job.ID, service.ID)
		if err != nil {
			return err
		}
		job.Status = status
		logrus.Printf("Ended in status '%s'", job.Status)
		err = id.DumpLogs("backup", job, service)
		if err != nil {
			return err
		}
		if job.Status != "finished" {
			return fmt.Errorf("Job finished with invalid status %s", job.Status)
		}
	} else {
		err := ip.YesNo("", "Are you sure you want to import data into your database without backing it up first? (y/n) ")
		if err != nil {
			return err
		}
	}
	logrus.Printf("Importing '%s' into %s (ID = %s)", filePath, databaseName, service.ID)
	job, err := id.Import(rt, key, iv, mongoCollection, mongoDatabase, service, singleUploadMode)
	if err != nil {
		return err
	}
	// all because logrus treats print, println, and printf the same
	logrus.StandardLogger().Out.Write([]byte(fmt.Sprintf("Processing import (job ID = %s).", job.ID)))

	status, err := ij.PollTillFinished(job.ID, service.ID)
	if err != nil {
		return err
	}
	job.Status = status
	logrus.Printf("\nImport complete (end status = '%s')", job.Status)
	err = id.DumpLogs("restore", job, service)
	if err != nil {
		return err
	}
	if job.Status != "finished" {
		return fmt.Errorf("Finished with invalid status %s", job.Status)
	}
	return nil
}

// Import imports data into a database service. The import is accomplished
// by encrypting the file locally, requesting a location that it can be uploaded
// to, then uploads the file. Once uploaded an automated service processes the
// file and acts according to the given parameters.
//
// The type of file that should be imported depends on the database. For
// PostgreSQL and MySQL, this should be a single `.sql` file. For Mongo, this
// should be a single tar'ed, gzipped archive (`.tar.gz`) of the database dump
// that you want to import.
func (d *SDb) Import(rt *transfer.ReaderTransfer, key, iv []byte, mongoCollection, mongoDatabase string, service *models.Service, singleUploadMode bool) (*models.Job, error) {
	options := map[string]string{}
	if mongoCollection != "" {
		options["databaseCollection"] = mongoCollection
	}
	if mongoDatabase != "" {
		options["database"] = mongoDatabase
	}

	uploadFilename := ""

	if singleUploadMode {
		tmpURL, err := d.TempUploadURLSingleUploadMode(service)
		if err != nil {
			return nil, err
		}
		u, err := url.Parse(tmpURL.URL)
		if err != nil {
			return nil, err
		}
		req, err := http.NewRequest("PUT", tmpURL.URL, rt)
		req.Header.Set("x-amz-server-side-encryption", "AES256")
		req.ContentLength = int64(rt.Length())
		done := make(chan bool)
		go printTransferStatus(false, rt, 0, 0, done)
		uploadResp, err := http.DefaultClient.Do(req)
		if err != nil {
			done <- false
			return nil, err
		}
		defer uploadResp.Body.Close()
		if uploadResp.StatusCode != 200 {
			done <- false
			b, err := ioutil.ReadAll(uploadResp.Body)
			logrus.Debugf("Error uploading import file: %d %s %s", uploadResp.StatusCode, string(b), err)
			return nil, fmt.Errorf("Failed to upload import file - received status code %d", uploadResp.StatusCode)
		}
		uploadFilename = strings.TrimLeft(u.Path, "/")
		done <- true
	} else {
		var uploadInfo *models.MultipartUploadInfo
		var err error
		for attempt := 0; attempt < 5; attempt++ {
			uploadInfo, err = d.InitiateMultiPartUpload(service)
			if err == nil {
				break
			}
		}
		if err != nil {
			return nil, fmt.Errorf("Failed to initiate upload - %s", err)
		}

		chunkSize := transfer.MB * 100
		if rt.Length() > transfer.TB {
			chunkSize = transfer.MB * 500
		}

		numChunks := int(math.Ceil(float64(rt.Length() / chunkSize)))
		parts := []map[string]interface{}{}
		for i := 1; i <= numChunks; i++ {
			tmpURL, err := d.TempUploadURL(service, uploadInfo.FileName, strconv.Itoa(i), uploadInfo.UploadID)
			if err != nil {
				return nil, err
			}

			if i == numChunks {
				chunkSize = (transfer.ByteSize)(int(rt.Length()) - int(rt.Transferred()))
			}

			readBuffer := make([]byte, int(chunkSize))
			bytesRead, err := rt.Read(readBuffer)
			if err != nil {
				return nil, err
			}
			if bytesRead < int(chunkSize) {
				return nil, fmt.Errorf("Failed to read from file - attempted to read %v but read %v. Import failed.", int(chunkSize), bytesRead)
			}

			var uploadResp *http.Response
			for attempt := 0; attempt < 5; attempt++ {
				tempReader := bytes.NewReader(readBuffer)
				chunkRT := transfer.NewReaderTransfer(io.LimitReader(tempReader, int64(chunkSize)), int(chunkSize))

				done := make(chan bool)
				go printTransferStatus(false, chunkRT, i, numChunks, done)

				req, err := http.NewRequest("PUT", tmpURL.URL, chunkRT)
				req.ContentLength = int64(chunkRT.Length())

				uploadResp, err = http.DefaultClient.Do(req)
				if err == nil && uploadResp.StatusCode == 200 {
					done <- true
					break
				}
				if uploadResp == nil {
					logrus.Printf("\nChunk upload %s failed.\nErr: %s\nRetrying...", strconv.Itoa(i), fmt.Errorf("No response from server"))
				} else {
					logrus.Printf("\nChunk upload %s failed.\nResponse code: %s\nErr: %s\nRetrying...", strconv.Itoa(i), strconv.Itoa(uploadResp.StatusCode), err)
				}
				done <- false
				time.Sleep(time.Second * 15)
			}
			if err != nil {
				return nil, err
			}
			if uploadResp == nil {
				return nil, fmt.Errorf("Failed to upload import file - %s", fmt.Errorf("No response from server"))
			} else {
				defer uploadResp.Body.Close()
				if uploadResp.StatusCode != 200 {
					b, err := ioutil.ReadAll(uploadResp.Body)
					return nil, fmt.Errorf("Failed to upload import file - received status code %d %s %s", uploadResp.StatusCode, string(b), err)
				}
				etag := uploadResp.Header.Get("ETag")
				parts = append(parts, map[string]interface{}{
					"ETag":       etag,
					"PartNumber": i,
				})
			}
			uploadFilename = uploadInfo.FileName
		}

		for attempt := 0; attempt < 5; attempt++ {
			_, err = d.CompleteMultiPartUpload(service, uploadInfo.FileName, uploadInfo.UploadID, parts)
			if err == nil {
				break
			}
		}
		if err != nil {
			return nil, fmt.Errorf("Failed to complete upload - %s", err)
		}
	}

	importParams := map[string]interface{}{}
	for key, value := range options {
		importParams[key] = value
	}
	importParams["filename"] = uploadFilename
	importParams["encryptionKey"] = string(d.Crypto.Hex(key, crypto.KeySize*2))
	importParams["encryptionIV"] = string(d.Crypto.Hex(iv, crypto.IVSize*2))
	importParams["dropDatabase"] = false
	if mongoDatabase != "" {
		importParams["database"] = mongoDatabase
	}
	if mongoCollection != "" {
		importParams["databaseCollection"] = mongoCollection
	}

	b, err := json.Marshal(importParams)
	if err != nil {
		return nil, err
	}
	headers := d.Settings.HTTPManager.GetHeaders(d.Settings.SessionToken, d.Settings.Version, d.Settings.Pod, d.Settings.UsersID)
	resp, statusCode, err := d.Settings.HTTPManager.Post(b, fmt.Sprintf("%s%s/environments/%s/services/%s/import", d.Settings.PaasHost, d.Settings.PaasHostVersion, d.Settings.EnvironmentID, service.ID), headers)
	if err != nil {
		return nil, err
	}
	var job models.Job
	err = d.Settings.HTTPManager.ConvertResp(resp, statusCode, &job)
	if err != nil {
		return nil, err
	}
	return &job, nil
}

func (d *SDb) InitiateMultiPartUpload(service *models.Service) (*models.MultipartUploadInfo, error) {
	headers := d.Settings.HTTPManager.GetHeaders(d.Settings.SessionToken, d.Settings.Version, d.Settings.Pod, d.Settings.UsersID)
	resp, statusCode, err := d.Settings.HTTPManager.Post(nil, fmt.Sprintf("%s%s/environments/%s/services/%s/initiate-multipart-upload", d.Settings.PaasHost, d.Settings.PaasHostVersion, d.Settings.EnvironmentID, service.ID), headers)
	if err != nil {
		return nil, err
	}
	var uploadInfo models.MultipartUploadInfo
	err = d.Settings.HTTPManager.ConvertResp(resp, statusCode, &uploadInfo)
	if err != nil {
		return nil, err
	}
	return &uploadInfo, nil
}

func (d *SDb) CompleteMultiPartUpload(service *models.Service, fileName string, uploadID string, parts []map[string]interface{}) (*models.Location, error) {
	headers := d.Settings.HTTPManager.GetHeaders(d.Settings.SessionToken, d.Settings.Version, d.Settings.Pod, d.Settings.UsersID)
	body, err := json.Marshal(parts)
	if err != nil {
		return nil, err
	}
	resp, statusCode, err := d.Settings.HTTPManager.Post(body, fmt.Sprintf("%s%s/environments/%s/services/%s/complete-multipart-upload?fileName=%s&uploadId=%s", d.Settings.PaasHost, d.Settings.PaasHostVersion, d.Settings.EnvironmentID, service.ID, fileName, uploadID), headers)
	if err != nil {
		return nil, err
	}
	var location models.Location
	err = d.Settings.HTTPManager.ConvertResp(resp, statusCode, &location)
	if err != nil {
		return nil, err
	}
	return &location, nil
}

func (d *SDb) TempUploadURL(service *models.Service, fileName string, partNumber string, uploadID string) (*models.TempURL, error) {
	headers := d.Settings.HTTPManager.GetHeaders(d.Settings.SessionToken, d.Settings.Version, d.Settings.Pod, d.Settings.UsersID)
	resp, statusCode, err := d.Settings.HTTPManager.Get(nil, fmt.Sprintf("%s%s/environments/%s/services/%s/multipart-upload-url?fileName=%s&partNumber=%s&uploadId=%s", d.Settings.PaasHost, d.Settings.PaasHostVersion, d.Settings.EnvironmentID, service.ID, fileName, partNumber, uploadID), headers)
	if err != nil {
		return nil, err
	}
	var tempURL models.TempURL
	err = d.Settings.HTTPManager.ConvertResp(resp, statusCode, &tempURL)
	if err != nil {
		return nil, err
	}
	return &tempURL, nil
}

func (d *SDb) TempUploadURLSingleUploadMode(service *models.Service) (*models.TempURL, error) {
	headers := d.Settings.HTTPManager.GetHeaders(d.Settings.SessionToken, d.Settings.Version, d.Settings.Pod, d.Settings.UsersID)
	resp, statusCode, err := d.Settings.HTTPManager.Get(nil, fmt.Sprintf("%s%s/environments/%s/services/%s/restore-url", d.Settings.PaasHost, d.Settings.PaasHostVersion, d.Settings.EnvironmentID, service.ID), headers)
	if err != nil {
		return nil, err
	}
	var tempURL models.TempURL
	err = d.Settings.HTTPManager.ConvertResp(resp, statusCode, &tempURL)
	if err != nil {
		return nil, err
	}
	return &tempURL, nil
}

func (d *SDb) RetrievePodApiVersion() (*models.VersionInfo, error) {
	headers := d.Settings.HTTPManager.GetHeaders(d.Settings.SessionToken, d.Settings.Version, d.Settings.Pod, d.Settings.UsersID)
	resp, statusCode, err := d.Settings.HTTPManager.Get(nil, fmt.Sprintf("%s%s/healthcheck", d.Settings.PaasHost, d.Settings.PaasHostVersion), headers)
	if err != nil {
		return nil, err
	}
	var versionInfo models.VersionInfo
	err = d.Settings.HTTPManager.ConvertResp(resp, statusCode, &versionInfo)
	if err != nil {
		return nil, err
	}
	return &versionInfo, nil
}


text:
'''

@author: frank
'''
import unittest
import time
from sftpbackupstorage import sftpbackupstorage
from zstacklib.utils import http
from zstacklib.utils import jsonobject

class Test(unittest.TestCase):
    def testName(self):
        server = sftpbackupstorage.SftpBackupStorageAgent()
        server.http_server.start_in_thread()
        time.sleep(2)

        cmd = sftpbackupstorage.ConnectCmd()
        cmd.storagePath = "/tmp"
        #url = sftpbackupstorage._build_url_for_test([sftpbackupstorage.SftpBackupStorageAgent.CONNECT_PATH])
        url = 'http://localhost:7171%s' % sftpbackupstorage.SftpBackupStorageAgent.CONNECT_PATH
        print url
        rsp = http.json_dump_post(url, cmd)
        jrsp = jsonobject.loads(rsp)
        print "total: %s, used: %s" % (jrsp.totalBackupStorageSize, jrsp.usedBackupStorageSize)

        server.http_server.stop()

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()


text:
import * as React from 'react';
import {rem} from 'polished';
import styled, {keyframes, css} from 'styled-components';

import AmpImage from '/component/amp/AmpImage';
import AmpStoryPage from '/component/amp/AmpStoryPage';

import {HeadingSerif as Heading, Text as SharedText} from './shared';

const ANIMATION_DURATION = 7000;

const CAROUSEL_IMGS = [
  '/static/stories/millennials/intro_1.jpg',
  '/static/stories/millennials/intro_2.jpg',
  '/static/stories/millennials/intro_3.jpg',
  '/static/stories/millennials/intro_4.jpg',
  '/static/stories/millennials/intro_5.jpg',
  '/static/stories/millennials/intro_6.jpg',
];

const pulse = keyframes`
  0%, 40%, 60%, 80%, 100% {
    opacity: 0;
  }
  20% {
    opacity: 1;
  }
`;

// eslint-disable-next-line no-unused-vars
const CarouselImage = styled(({key, index, carouselLength, ...props}) => (
  <AmpImage {...props} />
))`
  opacity: 0;
  & img {
    object-fit: cover;
  }

  [active] & {
    animation: ${({index, carouselLength}) =>
      css`${pulse} ${ANIMATION_DURATION}ms ease ${(ANIMATION_DURATION * index) /
        carouselLength}ms infinite`};
  }
`;

const ImageCarousel = styled.div`
  background: ${({theme}) => theme.colors.black};
`;

const SubHeading = styled(SharedText)`
  font-size: ${rem(50)};
`;

const CtaButton = styled.p`
  color: #ff005b;
  font-size: ${rem(16)};
  text-align: left;
`;

const StoryPage1 = () => {
  return (
    <AmpStoryPage id="StoryPage1">
      <amp-story-grid-layer
        template="vertical"
        style={{gridTemplateRows: '1fr', padding: 0}}
      >
        <ImageCarousel>
          {CAROUSEL_IMGS.map((imgSrc, i) => (
            <CarouselImage
              layout="fill"
              src={imgSrc}
              key={imgSrc}
              index={i}
              carouselLength={CAROUSEL_IMGS.length}
            />
          ))}
        </ImageCarousel>
      </amp-story-grid-layer>
      <amp-story-grid-layer
        template="vertical"
        style={{alignContent: 'center'}}
      >
        <Heading>Millennials</Heading>
        <SubHeading>
          The rise of millions of photo- <br />
          graphers
        </SubHeading>
        <CtaButton>Tap to start</CtaButton>
      </amp-story-grid-layer>
    </AmpStoryPage>
  );
};

export default StoryPage1;


text:
//
// Copyright (c) 2017 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//
using nanoFramework.Tools.Debugger;

namespace nanoFramework.Tools.VisualStudio.Extension.ToolWindow
{
    public class NFSerialDebugClientService : INFSerialDebugClientService
    {
        public PortBase SerialDebugClient { get; private set; }

        public NFSerialDebugClientService(PortBase client)
        {
            this.SerialDebugClient = client;
        }

    }
}


text:
package net.ncguy.argent.editor.lwjgl;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Window;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.Disposable;
import net.ncguy.argent.editor.IEditorRoot;
import net.ncguy.argent.editor.lwjgl.app.LwjglEditorListener;
import net.ncguy.argent.editor.swing.EditorRootConfig;
import net.ncguy.argent.view.ArgentWindowFactory;

/**
 * Created by Guy on 04/07/2016.
 */
public class LwjglEditorRoot<T> implements IEditorRoot, Disposable {

    private final EditorRootConfig<T> editorCfg;
    private Lwjgl3Window editorWindow;

    protected InputListener keyPressListener;
    protected int keyCode = Input.Keys.P;
    protected int requiredModifier = Input.Keys.SHIFT_LEFT;

    public LwjglEditorRoot(EditorRootConfig<T> editorCfg) {
        this.editorCfg = editorCfg;
        keyPressListener = new InputListener(){
            @Override
            public boolean keyDown(InputEvent event, int keycode) {
                if(keycode == keyCode) {
                    if(Gdx.input.isKeyPressed(requiredModifier) || requiredModifier <= -1)
                        spawnWindow();
                }
                return super.keyDown(event, keycode);
            }
        };
    }

    public void spawnWindow() {
        if(editorWindow == null)
            editorWindow = ArgentWindowFactory.instance().window(new LwjglEditorListener());
    }

    @Override
    public void dispose() {
        editorWindow.dispose();
    }

    @Override
    public void addToStage(Stage stage) {
        stage.addListener(keyPressListener);
    }

    @Override
    public void removeFromStage(Stage stage) {
        stage.removeListener(keyPressListener);
    }
}


text:
<!DOCTYPE HTML>

<title>Home Page</title>

	<meta http-equiv="Content-Security-Policy"
     content="default-src *;
              style-src 'self' 'unsafe-inline' 'unsafe-eval';
              script-src 'self' 'unsafe-inline' 'unsafe-eval';">
    <link rel="stylesheet" href="design.css"/>

			About us

				Contact us

				Support

				 Feedback

		ALERT!

press for 5 seconds to send Distress Message

other functions


text:
/**
 * Basic building blocks around a position, trade and portfolio.
 */
package com.opengamma.core.position.impl;