text:
from django.contrib import admin
from genericfile.models import FileStore

admin.site.register(FileStore)


text:
from app import app_factory

if __name__ == '__main__':
    app_factory().run()

redpajama_set_name: RedPajamaGithub


text:
package com.licel.jcardsim.crypto;

import javacard.security.CryptoException;
import javacard.security.KeyBuilder;
import javacard.security.RSAPrivateCrtKey;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;

/**
 * Implementation RSAPrivateCrtKey based
 * on BouncyCastle CryptoAPI.
 * @see RSAPrivateCrtKey
 * @see RSAPrivateCrtKeyParameters
 */
public class RSAPrivateCrtKeyImpl extends RSAKeyImpl implements RSAPrivateCrtKey {

    protected ByteContainer p = new ByteContainer();
    protected ByteContainer q = new ByteContainer();
    protected ByteContainer dp1 = new ByteContainer();
    protected ByteContainer dq1 = new ByteContainer();
    protected ByteContainer pq = new ByteContainer();

    /**
     * Construct not-initialized rsa private crt key
     * @param keySize key size it bits (modulus size)
     * @see KeyBuilder
     */
    public RSAPrivateCrtKeyImpl(short keySize) {
        super(true, keySize);
        type = KeyBuilder.TYPE_RSA_CRT_PRIVATE;
    }

    /**
     * Construct and initialize rsa key with RSAPrivateCrtKeyParameters.
     * Use in KeyPairImpl
     * @see javacard.security.KeyPair
     * @see RSAPrivateCrtKeyParameters
     * @param params key params from BouncyCastle API
     */
    public RSAPrivateCrtKeyImpl(RSAPrivateCrtKeyParameters params) {
        super(new RSAKeyParameters(true, params.getModulus(), params.getExponent()));
        type = KeyBuilder.TYPE_RSA_CRT_PRIVATE;
        setParameters(params);
    }

     public void setParameters(CipherParameters params){
        p.setBigInteger(((RSAPrivateCrtKeyParameters)params).getP());
        q.setBigInteger(((RSAPrivateCrtKeyParameters)params).getQ());
        dp1.setBigInteger(((RSAPrivateCrtKeyParameters)params).getDP());
        dq1.setBigInteger(((RSAPrivateCrtKeyParameters)params).getDQ());
        pq.setBigInteger(((RSAPrivateCrtKeyParameters)params).getQInv());
    }

    public void setP(byte[] buffer, short offset, short length) throws CryptoException {
        p.setBytes(buffer, offset, length);
    }

    public void setQ(byte[] buffer, short offset, short length) throws CryptoException {
        q.setBytes(buffer, offset, length);
    }

    public void setDP1(byte[] buffer, short offset, short length) throws CryptoException {
        dp1.setBytes(buffer, offset, length);
    }

    public void setDQ1(byte[] buffer, short offset, short length) throws CryptoException {
        dq1.setBytes(buffer, offset, length);
    }

    public void setPQ(byte[] buffer, short offset, short length) throws CryptoException {
        pq.setBytes(buffer, offset, length);
    }

    public short getP(byte[] buffer, short offset) {
        return p.getBytes(buffer, offset);
    }

    public short getQ(byte[] buffer, short offset) {
        return q.getBytes(buffer, offset);
    }

    public short getDP1(byte[] buffer, short offset) {
        return dp1.getBytes(buffer, offset);
    }

    public short getDQ1(byte[] buffer, short offset) {
        return dq1.getBytes(buffer, offset);
    }

    public short getPQ(byte[] buffer, short offset) {
        return pq.getBytes(buffer, offset);
    }

    public void clearKey() {
        super.clearKey();
        p.clear();
        q.clear();
        dp1.clear();
        dq1.clear();
        pq.clear();
    }

    public boolean isInitialized() {
        return (p.isInitialized() && q.isInitialized()
                && dp1.isInitialized() && dq1.isInitialized()
                && pq.isInitialized());
    }

    public CipherParameters getParameters() {
        if (!isInitialized()) {
            CryptoException.throwIt(CryptoException.UNINITIALIZED_KEY);
        }
        // modulus = p * q;
        return new RSAPrivateCrtKeyParameters(p.getBigInteger().multiply(q.getBigInteger()), null,
                null, p.getBigInteger(), q.getBigInteger(),
                dp1.getBigInteger(), dq1.getBigInteger(), pq.getBigInteger());
    }
}


text:
from setuptools import setup
from cycli import __version__

setup(name='cycli',
      version=__version__,
      description='A Command Line Interface for Cypher.',
      long_description='Syntax highlighting and autocomplete.',
      keywords='neo4j cypher cli syntax autocomplete',
      url='https://github.com/nicolewhite/cycli',
      author='Nicole White',
      author_email='nicole@neotechnology.com',
      license='MIT',
      packages=['cycli'],
      install_requires=[
        'click==4.1',
        'prompt-toolkit==0.43',
        'Pygments==2.0.2',
        'py2neo==2.0.7',
        'requests==2.7.0',
      ],
      include_package_data=True,
      zip_safe=False,
      entry_points={
        'console_scripts': [
            'cycli = cycli.main:run'
        ]
    })


text:
/*jslint nomen: true, vars: true, unparam: true*/
/*global require, exports, console*/
(function () {
    'use strict';

    /**
     * Module dependencies.
     */
    var messageHandler = require('../services/messaging/messageHandler');

    /**
     * Create a Device
     */
    exports.messageReceived = function (req, res) {
        var message = req.body;
        messageHandler.handleMessage(message).then(function (result) {
            res.jsonp(result);
        }, function (errorMessage) {
            res.status(400).send({
                message: errorMessage
            });
        });
    };

}());


text:
// Copyright 2022, University of Colorado Boulder

/**
 * A single tab of the PreferencesDialog. Selecting this PreferencesTab makes its associated PreferencesPanel
 * visible in the dialog.
 *
 * @author Jesse Greenberg
 */

import joist from '../joist.js';
import { FocusHighlightPath, HBox, Line, Node, NodeOptions, PressListener, Rectangle, Text, Voicing, VoicingOptions } from '../../../scenery/js/imports.js';
import PreferencesType from './PreferencesType.js';
import TReadOnlyProperty from '../../../axon/js/TReadOnlyProperty.js';
import TProperty from '../../../axon/js/TProperty.js';
import optionize from '../../../phet-core/js/optionize.js';
import PreferencesDialog from './PreferencesDialog.js';
import Multilink from '../../../axon/js/Multilink.js';
import JoistStrings from '../JoistStrings.js';
import Tandem from '../../../tandem/js/Tandem.js';
import PickRequired from '../../../phet-core/js/types/PickRequired.js';
import StrictOmit from '../../../phet-core/js/types/StrictOmit.js';

import PatternStringProperty from '../../../axon/js/PatternStringProperty.js';
type SelfOptions = {

  // An additional icon to display to the right of the label text for this tab.
  iconNode?: Node | null;
};
type PreferencesTabOptions = SelfOptions & PickRequired<NodeOptions, 'tandem'> & StrictOmit<NodeOptions, 'children'>;
type ParentOptions = NodeOptions & VoicingOptions;

class PreferencesTab extends Voicing( Node ) {

  // The value of this tab, when this tab is Pressed, the panel of this PreferencesType will be displayed.
  public readonly value: PreferencesType;

  // garbage collection
  private readonly disposePreferencesTab: () => void;

  /**
   * @param labelProperty - text label for the tab
   * @param property
   * @param value - PreferencesType shown when this tab is selected
   * @param providedOptions
   */
  public constructor( labelProperty: TReadOnlyProperty<string>, property: TProperty<PreferencesType>, value: PreferencesType, providedOptions: PreferencesTabOptions ) {

    const options = optionize<PreferencesTabOptions, SelfOptions, ParentOptions>()( {
      iconNode: null,

      tandem: Tandem.REQUIRED,
      phetioFeatured: true,
      visiblePropertyOptions: {
        phetioFeatured: true
      },
      cursor: 'pointer',

      // pdom
      tagName: 'button',
      innerContent: labelProperty,
      ariaRole: 'tab',
      focusable: true,
      containerTagName: 'li'
    }, providedOptions );

    // Visual contents for the tab, label Text and optional icon Node
    const text = new Text( labelProperty, PreferencesDialog.TAB_OPTIONS );
    const tabContents: Node[] = [ text ];
    if ( options.iconNode ) {
      tabContents.push( options.iconNode );
    }
    const contentsBox = new HBox( {
      children: tabContents,
      spacing: 8
    } );

    // background Node behind the tab contents for layout spacing and to increase the clickable area of the tab
    const backgroundNode = new Rectangle( {
      children: [ contentsBox ]
    } );

    // Pink underline Node to indicate which tab is selected
    const underlineNode = new Line( 0, 0, 0, 0, {
      stroke: FocusHighlightPath.INNER_FOCUS_COLOR,
      lineWidth: 5
    } );
    contentsBox.boundsProperty.link( bounds => {
      backgroundNode.rectBounds = bounds.dilatedXY( 15, 10 );

      underlineNode.x2 = bounds.width;
      underlineNode.centerTop = bounds.centerBottom.plusXY( 0, 5 );
    } );

    super( options );
    this.children = [ backgroundNode, underlineNode ];

    this.value = value;

    const voicingPatternStringProperty = new PatternStringProperty( JoistStrings.a11y.preferences.tabs.tabResponsePatternStringProperty, {
      title: labelProperty
    } );
    this.voicingNameResponse = voicingPatternStringProperty;

    const pressListener = new PressListener( {
      press: () => {
        property.set( value );

        // speak the object response on activation
        this.voicingSpeakNameResponse();
      },

      // phet-io
      tandem: Tandem.OPT_OUT // We don't want to instrument components for preferences, https://github.com/phetsims/joist/issues/744#issuecomment-1196028362
    } );
    this.addInputListener( pressListener );

    const tabInputMultilink = Multilink.multilink( [ property, pressListener.isOverProperty ], ( selectedTab, isOver ) => {
      backgroundNode.opacity = selectedTab === value ? 1 :
                               isOver ? 0.8 :
                               0.6;

      this.focusable = selectedTab === value;
      underlineNode.visible = selectedTab === value;
    } );

    this.disposePreferencesTab = () => {
      tabInputMultilink.dispose();
      pressListener.dispose();
      voicingPatternStringProperty.dispose();
      contentsBox.dispose();
      backgroundNode.dispose();
      text.dispose();
    };
  }

  public override dispose(): void {
    this.disposePreferencesTab();
    super.dispose();
  }
}

joist.register( 'PreferencesTab', PreferencesTab );
export default PreferencesTab;


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/raw_data_list_item">

    <TextView android:id="@+id/raw_data_id"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="24sp" />

    <TextView android:id="@+id/raw_data_value"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="12sp"/>

    <TextView android:id="@+id/raw_data_slope"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="12sp"/>

    <TextView android:id="@+id/raw_data_timestamp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="12sp"/>

</LinearLayout>


text:
package org.cqrs.example;

import java.util.Date;
import java.util.concurrent.ExecutionException;

import org.cqrs.core.CQRS;
import org.cqrs.example.domain.FinalBankAccount;
import org.cqrs.example.domain.TransferTransaction;
import org.cqrs.example.handler.FinalBankAccountHandler;
import org.cqrs.example.handler.FinalBankAccountHandler.BankAccountCmd;
import org.cqrs.example.handler.TransferTransactionHandler;
import org.cqrs.example.handler.TransferTransactionHandler.TransferTransactionCmd;

import com.google.common.collect.ImmutableMap;

public class BankAccountTransferTest {

  public static void main(String[] args) throws InterruptedException, ExecutionException {

    CQRS cqrs = CQRS.get();
    new FinalBankAccountHandler(FinalBankAccount.class);
    new TransferTransactionHandler(TransferTransaction.class);

    String sourceId = cqrs.execute(BankAccountCmd.OPEN_ACCOUNT, ImmutableMap.of("name", "wrd", "balance", 1000.00));
    String targetId = cqrs.execute(BankAccountCmd.OPEN_ACCOUNT, ImmutableMap.of("name", "linkeer", "balance", 100.00));

    String transactionId = cqrs.execute(TransferTransactionCmd.BEGIN_START_TRANSFER,
        ImmutableMap.of(
            "sourceId", sourceId,
            "targetId", targetId,
            "amount", 300.00,
            "transferDateTime",
            new Date()));

    System.out.println("transactionId:" + transactionId);

    Thread.sleep(500);

    System.out.println(cqrs.domain(FinalBankAccount.class).aggregateRoot(sourceId));
    System.out.println(cqrs.domain(FinalBankAccount.class).aggregateRoot(targetId));

    cqrs.shutdown();
  }
}


text:
cask 'buttercup' do
  version '1.6.2'
  sha256 'e73748a31f8eda1fe74aeb38025f5aef314498e10049ffb48152118036f29b9a'

  # github.com/buttercup/buttercup-desktop was verified as official when first introduced to the cask
  url "https://github.com/buttercup/buttercup-desktop/releases/download/v#{version}/buttercup-desktop-#{version}-mac.zip"
  appcast 'https://github.com/buttercup/buttercup-desktop/releases.atom',
          checkpoint: 'ae5d4f2f2560672309a65359277815f140774e60bf15b6732a6b1aed70c0c84d'
  name 'Buttercup'
  homepage 'https://buttercup.pw/'

  app 'Buttercup.app'
end


text:
CC=gcc -arch x86_64 -arch i386 -arch ppc -mmacosx-version-min=10.5
TARGET=libsparkle_init.dylib
JNI_INCLUDE_PATH=/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Headers/
CFLAGS=-I$(JNI_INCLUDE_PATH) -I/System/Library/Frameworks/Sparkle.framework/Versions/A/Headers/
LIBS=-framework AppKit -framework Foundation -framework Sparkle
OBJS=net_java_sip_communicator_impl_sparkle_SparkleActivator.o

all:$(TARGET)

clean:
	rm -rf $(TARGET) $(OBJS) *~

install:$(TARGET)
	cp $(TARGET) ../../../../lib/native/mac/

libsparkle_init.dylib:$(OBJS)
	$(CC) -dynamiclib -o $(TARGET) $(LIBS) $(CFLAGS) $<
	install_name_tool -change "@loader_path/../Frameworks/Sparkle.framework/Versions/A/Sparkle" "@executable_path/../Frameworks/Sparkle.framework/Versions/A/Sparkle" libsparkle_init.dylib


text:
namespace remoting::protocol {

ChannelDispatcherBase::ChannelDispatcherBase(const std::string& channel_name)
    : channel_name_(channel_name) {}

ChannelDispatcherBase::~ChannelDispatcherBase() {
  if (channel_factory_)
    channel_factory_->CancelChannelCreation(channel_name_);
}

void ChannelDispatcherBase::Init(MessageChannelFactory* channel_factory,
                                 EventHandler* event_handler) {
  channel_factory_ = channel_factory;
  event_handler_ = event_handler;

  channel_factory_->CreateChannel(
      channel_name_, base::BindOnce(&ChannelDispatcherBase::OnChannelReady,
                                    base::Unretained(this)));
}

void ChannelDispatcherBase::Init(std::unique_ptr<MessagePipe> message_pipe,
                                 EventHandler* event_handler) {
  event_handler_ = event_handler;
  OnChannelReady(std::move(message_pipe));
}

void ChannelDispatcherBase::OnChannelReady(
    std::unique_ptr<MessagePipe> message_pipe) {
  channel_factory_ = nullptr;
  message_pipe_ = std::move(message_pipe);
  message_pipe_->Start(this);
}

void ChannelDispatcherBase::OnMessagePipeOpen() {
  DCHECK(!is_connected_);
  is_connected_ = true;
  event_handler_->OnChannelInitialized(this);
}

void ChannelDispatcherBase::OnMessageReceived(
    std::unique_ptr<CompoundBuffer> message) {
  OnIncomingMessage(std::move(message));
}

void ChannelDispatcherBase::OnMessagePipeClosed() {
  is_connected_ = false;
  message_pipe_.reset();
  event_handler_->OnChannelClosed(this);
}

}  // namespace remoting::protocol


text:
from subprocess import check_output, CalledProcessError
from charms.reactive import when
from charms.reactive import when_not
from charms.reactive import is_state
from charms.reactive import set_state
from charms.reactive import remove_state
from charms.reactive import toggle_state
from charms.reactive.helpers import data_changed
from charms.layer.hadoop_base import get_hadoop_base
from jujubigdata.handlers import HDFS
from jujubigdata import utils
from charmhelpers.core import hookenv
from charms import leadership
from charms.layer.apache_hadoop_namenode import get_cluster_nodes
from charms.layer.apache_hadoop_namenode import set_cluster_nodes

@when('namenode-cluster.joined')
def manage_cluster_hosts(cluster):
    utils.update_kv_hosts(cluster.hosts_map())
    utils.manage_etc_hosts()

@when('datanode.journalnode.joined')
def check_journalnode_quorum(datanode):
    nodes = datanode.nodes()
    quorum_size = hookenv.config('journalnode_quorum_size')
    toggle_state('journalnode.quorum', len(nodes) >= quorum_size)

@when('namenode-cluster.joined', 'journalnode.quorum')
@when('leadership.is_leader')
@when_not('leadership.set.namenode-ha')
def enable_ha(cluster):
    """
    Once we have two viable NameNodes and a quorum of JournalNodes,
    inform all cluster units that we are HA.

    Note that this flag is never removed (once HA, always HA) because we
    could temporarily lose JN quorum or viable NNs during fail-over or
    restart, and we don't want to arbitrarily revert to non-HA in that case.
    """
    leadership.leader_set({'namenode-ha': 'true'})

@when('leadership.set.ha-initialized')
@when('datanode.joined')
@when('namenode-cluster.joined')
@when('leadership.is_leader')
def check_cluster_nodes(cluster, datanode):
    """
    Check to see if any of the chosen cluster nodes have gone away and
    been replaced by viable replacements.

    Note that we only remove a chosen node if it is no longer part of
    the peer relation *and* has been replaced by a working node.  This
    ensures that reboots and intermittent node loses don't cause
    superfluous updates.
    """
    local_hostname = hookenv.local_unit().replace('/', '-')

    manage_cluster_hosts(cluster)  # ensure /etc/hosts is up-to-date

    chosen_nodes = set(get_cluster_nodes())
    current_nodes = set([local_hostname] + cluster.nodes())
    remaining_nodes = chosen_nodes & current_nodes
    added_nodes = current_nodes - chosen_nodes

    if len(remaining_nodes) < 2 and added_nodes:
        chosen_nodes = (sorted(remaining_nodes) + sorted(added_nodes))[:2]
        set_cluster_nodes(chosen_nodes)
        update_ha_config(datanode)  # ensure new config gets written

@when('leadership.set.ha-initialized', 'datanode.joined')
def update_ha_config(datanode):
    cluster_nodes = get_cluster_nodes()
    jn_nodes = sorted(datanode.nodes())
    jn_port = datanode.jn_port()
    started = is_state('namenode.started')
    new_cluster_config = data_changed('namenode.cluster-nodes', cluster_nodes)
    new_jn_config = data_changed('namenode.jn.config', (jn_nodes, jn_port))

    hadoop = get_hadoop_base()
    hdfs = HDFS(hadoop)
    hdfs.configure_namenode(cluster_nodes)
    hdfs.register_journalnodes(jn_nodes, jn_port)

    if started and new_cluster_config:
        hdfs.restart_namenode()
    elif started and new_jn_config:
        hdfs.reload_slaves()  # is this actually necessary?

@when('leadership.set.namenode-ha')
@when('namenode-cluster.joined')
@when('datanode.journalnode.joined')
@when_not('leadership.set.ha-initialized')
@when('leadership.is_leader')
def init_ha_active(datanode, cluster):
    """
    Do initial HA setup on the leader.
    """
    local_hostname = hookenv.local_unit().replace('/', '-')
    hadoop = get_hadoop_base()
    hdfs = HDFS(hadoop)
    hdfs.stop_namenode()
    remove_state('namenode.started')
    # initial cluster is us (active) plus a standby
    set_cluster_nodes([local_hostname, cluster.nodes()[0]])
    update_ha_config(datanode)
    hdfs.init_sharededits()
    hdfs.start_namenode()
    leadership.leader_set({'ha-initialized': 'true'})
    set_state('namenode.started')

@when('namenode-cluster.joined')
@when('datanode.journalnode.joined')
@when('leadership.set.ha-initialized')  # wait for leader to init HA
@when_not('namenode.started')
def init_ha_standby(datanode, cluster):
    """
    Once initial HA setup is done, any new NameNode is started as standby.
    """
    local_hostname = hookenv.local_unit().replace('/', '-')
    if local_hostname not in get_cluster_nodes():
        # can't even bootstrapStandby if not in the list of chosen nodes
        return
    update_ha_config(datanode)  # ensure the config is written
    hadoop = get_hadoop_base()
    hdfs = HDFS(hadoop)
    update_ha_config(datanode)
    hdfs.bootstrap_standby()
    hdfs.start_namenode()
    cluster.standby_ready()
    set_state('namenode.standby')
    hadoop.open_ports('namenode')
    set_state('namenode.started')

@when('leadership.set.ha-initialized')
@when('namenode.started')
@when_not('namenode.crontab')
def register_crontab():
    local_unit = hookenv.local_unit()
    try:
        crontab = check_output(['crontab', '-lu', 'hdfs'],
                               universal_newlines=True)
    except CalledProcessError:
        crontab = ''
    crontab += '*/1 * * * * ' \
               'juju-run %s "PYTHONPATH=lib reactive/namenode_status.py"\n' % (
                   local_unit)
    check_output(['crontab', '-', '-u', 'hdfs'],
                 input=crontab, universal_newlines=True)
    set_state('namenode.crontab')


text:
package cz.metacentrum.perun.webgui.json.membersManager;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.*;
import com.google.gwt.user.client.Window;
import cz.metacentrum.perun.webgui.client.PerunWebSession;
import cz.metacentrum.perun.webgui.json.JsonCallbackEvents;
import cz.metacentrum.perun.webgui.json.JsonPostClient;
import cz.metacentrum.perun.webgui.model.*;

/**
 * Ajax query to create member in VO from candidate or User
 *
 * @author Pavel Zlamal <256627@mail.muni.cz>
 */

public class CreateMember {

	// web session
	private PerunWebSession session = PerunWebSession.getInstance();
	// URL to call
	final String JSON_URL = "membersManager/createMember";
	// external events
	private JsonCallbackEvents events = new JsonCallbackEvents();
	// params
	private Candidate candidate = null;
	private int voId = 0;
	private Group group;

	/**
	 * Creates a new request
	 */
	public CreateMember() {}

	/**
	 * Creates a new request with custom events passed from tab or page
	 *
	 * @param events external events
	 */
	public CreateMember(final JsonCallbackEvents events) {
		this.events = events;
	}

	/**
	 * Attempts to create member in VO from candidate
	 *
	 * @param voId vo where member should be created
	 * @param candidate candidate to be member
	 *
	 */
	public void createMember(final int voId,final Candidate candidate) {
		createMember(voId, null, candidate);
	}

	/**
	 * Attempts to create member in VO from candidate
	 *
	 * @param voId vo where member should be created
	 * @param group where member should be created
	 * @param candidate candidate to be member
	 *
	 */
	public void createMember(final int voId, Group group, final Candidate candidate) {

		this.voId = voId;
		this.group = group;
		this.candidate = candidate;

		// test arguments
		if(!this.testAdding()){
			return;
		}

		if (!session.isVoAdmin(voId)) {
			// GROUP ADMIN HAVE OWN PROCESSING
			createMemberAsGroupAdmin(voId, group, candidate);
			return;
		}

		// new events
		JsonCallbackEvents newEvents = new JsonCallbackEvents(){
			public void onError(PerunError error) {
				session.getUiElements().setLogErrorText("Creating member: " + candidate.getDisplayName() + " failed.");
				events.onError(error);
			};

			public void onFinished(JavaScriptObject jso) {
				session.getUiElements().setLogSuccessText("Member "+ candidate.getDisplayName() +" created !");

				// call validation asynchronously
				Member mem = jso.cast();
				ValidateMemberAsync request = new ValidateMemberAsync();
				request.validateMemberAsync(mem);

				events.onFinished(jso);
			};

			public void onLoadingStart() {
				events.onLoadingStart();
			};
		};

		// sending data
		JsonPostClient jspc = new JsonPostClient(newEvents);
		jspc.sendData(JSON_URL, prepareJSONObject());

	}

	/**
	 * Attempts to create member in VO from candidate for Group admin
	 *
	 * @param voId vo where member should be created
	 * @param group where member should be created
	 * @param candidate candidate to be member
	 *
	 */
	public void createMemberAsGroupAdmin(final int voId, Group group, final Candidate candidate) {

		this.voId = voId;
		this.group = group;
		this.candidate = candidate;

		// test arguments
		if(!this.testAdding()){
			return;
		}

		// new events
		JsonCallbackEvents newEvents = new JsonCallbackEvents(){
			public void onError(PerunError error) {
				session.getUiElements().setLogErrorText("Creating member: " + candidate.getDisplayName() + " failed.");
				events.onError(error);
			};

			public void onFinished(JavaScriptObject jso) {
				session.getUiElements().setLogSuccessText("Member "+ candidate.getDisplayName() +" created !");
				events.onFinished(jso);
			};

			public void onLoadingStart() {
				events.onLoadingStart();
			};
		};

		// create whole JSON query
		JSONObject jsonQuery = new JSONObject();
		jsonQuery.put("vo", new JSONNumber(voId));

		if (group != null) {
			// GROUP OBJECT
			JSONObject oldGroup = new JSONObject(group);
			// RECONSTRUCT OBJECT
			JSONObject newGroup = new JSONObject();
			newGroup.put("id", oldGroup.get("id"));
			// fake new group short name as name in order to update
			newGroup.put("name", oldGroup.get("name"));
			newGroup.put("shortName", oldGroup.get("shortName"));
			newGroup.put("description", oldGroup.get("description"));
			newGroup.put("voId", oldGroup.get("voId"));
			newGroup.put("parentGroupId", oldGroup.get("parentGroupId"));
			newGroup.put("beanName", oldGroup.get("beanName"));

			JSONArray arr = new JSONArray();
			arr.set(0, newGroup);
			jsonQuery.put("groups", arr);
		}

		if (candidate != null) {
			ExtSource source = candidate.getUserExtSource().getExtSource();
			jsonQuery.put("extSource", new JSONNumber(source.getId()));
			jsonQuery.put("login", new JSONString(candidate.getUserExtSource().getLogin()));
		}

		// sending data
		JsonPostClient jspc = new JsonPostClient(newEvents);
		jspc.sendData(JSON_URL, jsonQuery);

	}

	/**
	 * Attempts to create member in VO from existing perun user
	 *
	 * @param voId vo where member should be created
	 * @param user user to be member
	 */
	public void createMember(final int voId, final User user) {
		createMember(voId, null, user);
	}

	/**
	 * Attempts to create member in VO from existing perun user
	 *
	 * @param voId vo where member should be created
	 * @param group where member should be created
	 * @param user user to be member
	 *
	 */
	public void createMember(final int voId, final Group group, final User user) {

		this.voId = voId;
		this.group = group;

		// test arguments
		if(!this.testAdding()){
			return;
		}

		// new events
		JsonCallbackEvents newEvents = new JsonCallbackEvents(){
			public void onError(PerunError error) {
				session.getUiElements().setLogErrorText("Creating member: " + user.getFullName() + " failed.");
				events.onError(error);
			};

			public void onFinished(JavaScriptObject jso) {
				session.getUiElements().setLogSuccessText("Member "+ user.getFullName() +" created !");

				// call validation asynchronously
				Member mem = jso.cast();
				ValidateMemberAsync request = new ValidateMemberAsync();
				request.validateMemberAsync(mem);

				events.onFinished(jso);

			};

			public void onLoadingStart() {
				events.onLoadingStart();
			};
		};

		JSONObject query = new JSONObject();
		query.put("vo", new JSONNumber(voId));
		query.put("user", new JSONNumber(user.getId()));
		if (group != null) {
			// GROUP OBJECT
			JSONObject oldGroup = new JSONObject(group);
			// RECONSTRUCT OBJECT
			JSONObject newGroup = new JSONObject();
			newGroup.put("id", oldGroup.get("id"));
			// fake new group short name as name in order to update
			newGroup.put("name", oldGroup.get("name"));
			newGroup.put("shortName", oldGroup.get("shortName"));
			newGroup.put("description", oldGroup.get("description"));
			newGroup.put("voId", oldGroup.get("voId"));
			newGroup.put("parentGroupId", oldGroup.get("parentGroupId"));
			newGroup.put("beanName", oldGroup.get("beanName"));

			JSONArray arr = new JSONArray();
			arr.set(0, newGroup);
			query.put("groups", arr);
		}

		// sending data
		JsonPostClient jspc = new JsonPostClient(newEvents);
		jspc.sendData(JSON_URL, query);

	}

	/**
	 * Tests the values, if the process can continue
	 *
	 * @return true/false for continue/stop
	 */
	private boolean testAdding()
	{
		boolean result = true;
		String errorMsg = "";

		if(voId == 0){
			errorMsg += "Wrong 'Vo' parameter.\n";
			result = false;
		}

		if(errorMsg.length()>0){
			Window.alert(errorMsg);
		}

		return result;
	}

	/**
	 * Prepares a JSON object
	 *
	 * @return JSONObject the whole query
	 */
	private JSONObject prepareJSONObject() {

		JSONNumber selectedVoId = new JSONNumber(voId);

		// create Json object from webgui candidate
		JSONObject toBeCandidate = new JSONObject(candidate);

		// get only interested in items (lost unknown $H property added by gwt)
		JSONValue attributes = toBeCandidate.get("attributes");
		JSONValue additionalUserExtSources = toBeCandidate.get("additionalUserExtSources");
		JSONValue userExtSource = toBeCandidate.get("userExtSource");
		JSONValue id = toBeCandidate.get("id");
		JSONValue firstName = toBeCandidate.get("firstName");
		JSONValue lastName = toBeCandidate.get("lastName");
		JSONValue middleName = toBeCandidate.get("middleName");
		JSONValue titleAfter = toBeCandidate.get("titleAfter");
		JSONValue titleBefore = toBeCandidate.get("titleBefore");

		// create new form of candidate
		JSONObject newCandidate = new JSONObject();
		newCandidate.put("attributes", attributes);
		newCandidate.put("additionalUserExtSources", additionalUserExtSources);
		newCandidate.put("userExtSource", userExtSource);
		newCandidate.put("id", id);
		newCandidate.put("firstName", firstName);
		newCandidate.put("lastName", lastName);
		newCandidate.put("middleName", middleName);
		newCandidate.put("titleAfter", titleAfter);
		newCandidate.put("titleBefore", titleBefore);

		// create whole JSON query
		JSONObject jsonQuery = new JSONObject();
		jsonQuery.put("vo", selectedVoId);
		jsonQuery.put("candidate", newCandidate);

		if (group != null) {
			// GROUP OBJECT
			JSONObject oldGroup = new JSONObject(group);
			// RECONSTRUCT OBJECT
			JSONObject newGroup = new JSONObject();
			newGroup.put("id", oldGroup.get("id"));
			// fake new group short name as name in order to update
			newGroup.put("name", oldGroup.get("name"));
			newGroup.put("shortName", oldGroup.get("shortName"));
			newGroup.put("description", oldGroup.get("description"));
			newGroup.put("voId", oldGroup.get("voId"));
			newGroup.put("parentGroupId", oldGroup.get("parentGroupId"));
			newGroup.put("beanName", oldGroup.get("beanName"));

			JSONArray arr = new JSONArray();
			arr.set(0, newGroup);
			jsonQuery.put("groups", arr);
		}

		return jsonQuery;

	}

}


text:
"""
串口RTU通道类
通过调用管理类对象的process_data函数实现信息的发送。
"""
import time
import logging

import serial
from pymodbus.client.sync import ModbusSerialClient

from libs.modbusdefine import *
from libs.base_channel import BaseChannel

logger = logging.getLogger('plugin')

class SerialRtuChannel(BaseChannel):
    def __init__(self, channel_params, devices_file_name, protocol, mqtt_client, network_name):
        BaseChannel.__init__(self, channel_params, devices_file_name, protocol, mqtt_client, network_name)
        # 配置项
        self.port = channel_params.get("port", "")
        self.baund = channel_params.get("baund", 9600)
        self.stopbits = channel_params.get("stopbits", serial.STOPBITS_ONE)
        self.parity = channel_params.get("parity", serial.PARITY_NONE)
        self.bytesize = channel_params.get("bytesize", serial.EIGHTBITS)
        self.timeout = channel_params.get("timeout", 2)
        self.protocol.set_device_info(self.port, self.baund)
        # modbus通信对象
        try:
            self.modbus_client = ModbusSerialClient(method='rtu',
                                                    port=self.port,
                                                    baudrate=self.baund,
                                                    stopbits=self.stopbits,
                                                    parity=self.parity,
                                                    bytesize=self.bytesize,
                                                    timeout=self.timeout)
            self.modbus_client.connect()
            logger.debug("连接串口成功.")
        except Exception, e:
            logger.error("连接串口失败,错误信息:%r." % e)
            self.modbus_client = None

    @staticmethod
    def check_config(channel_params):
        if "port" not in channel_params or "baund" not in channel_params:
            return False
        return BaseChannel.check_config(channel_params)

    def run(self):

        # 首先上报设备数据
        for device_id in self.devices_info_dict:
            device_info = self.devices_info_dict[device_id]
            device_msg = {
                "device_id": device_info["device_id"],
                "device_type": device_info["device_type"],
                "device_addr": device_info["device_addr"],
                "device_port": device_info["device_port"],
                "protocol": self.protocol.protocol_type,
                "data": ""
            }
            self.mqtt_client.publish_data(device_msg)

        while True:
            # 该线程保持空转
            time.sleep(5)

    def process_cmd(self, device_cmd_msg):
        device_info = None
        device_id = device_cmd_msg.get("device_id", "")
        device_cmd = device_cmd_msg["command"]
        if device_id in self.devices_info_dict:
            device_info = self.devices_info_dict[device_id]

        if device_info is None:
            logger.error("严重错误,设备%s未找到." % device_id)
            return

        if self.modbus_client is None:
            # 客户端异常,则重新连接
            try:
                self.modbus_client = ModbusSerialClient(method='rtu',
                                                        port=self.port,
                                                        baudrate=self.baund,
                                                        stopbits=self.stopbits,
                                                        parity=self.parity,
                                                        bytesize=self.bytesize,
                                                        timeout=self.timeout)
                self.modbus_client.connect()
                logger.debug("连接串口成功.")
            except Exception, e:
                logger.error("连接串口失败,错误信息:%r." % e)
                return

        if device_cmd["func_code"] == const.fc_read_coils or device_cmd["func_code"] == const.fc_read_discrete_inputs:
            req_result = self.modbus_client.read_coils(device_cmd["addr"],
                                                       device_cmd["count"],
                                                       unit=int(device_info["device_addr"]))
            if req_result is None:
                logger.error("device_cmd(%r) retun None." % device_cmd)
                device_data = None
            else:
                device_data = {
                    "func_code": device_cmd["func_code"],
                    "addr": device_cmd["addr"],
                    "count": device_cmd["count"],
                    "values": req_result.bits
                }

        elif device_cmd["func_code"] == const.fc_write_coil:
            req_result = self.modbus_client.write_coil(device_cmd["addr"],
                                                       device_cmd["value"],
                                                       unit=int(device_info["device_addr"]))
            res_result = self.modbus_client.read_coils(device_cmd["addr"],
                                                       1,
                                                       unit=int(device_info["device_addr"]))
            if res_result is None:
                logger.error("device_cmd(%r) retun None." % device_cmd)
                device_data = None
            else:
                device_data = {
                    "func_code": device_cmd["func_code"],
                    "addr": device_cmd["addr"],
                    "count": 1,
                    "values": res_result.bits[0:1]
                }
        elif device_cmd["func_code"] == const.fc_write_coils:
            req_result = self.modbus_client.write_coils(device_cmd["addr"],
                                                        device_cmd["values"],
                                                        unit=int(device_info["device_addr"]))
            counter = len(device_cmd["values"])
            res_result = self.modbus_client.read_coils(device_cmd["addr"],
                                                       counter,
                                                       unit=int(device_info["device_addr"]))
            if res_result is None:
                logger.error("device_cmd(%r) retun None." % device_cmd)
                device_data = None
            else:
                device_data = {
                    "func_code": device_cmd["func_code"],
                    "addr": device_cmd["addr"],
                    "count": counter,
                    "values": res_result.bits
                }
        elif device_cmd["func_code"] == const.fc_write_register:
            req_result = self.modbus_client.write_register(device_cmd["addr"],
                                                           device_cmd["value"],
                                                           unit=int(device_info["device_addr"]))
            res_result = self.modbus_client.read_holding_registers(device_cmd["addr"],
                                                                   1,
                                                                   unit=int(device_info["device_addr"]))
            if res_result is None:
                logger.error("device_cmd(%r) retun None." % device_cmd)
                device_data = None
            else:
                device_data = {
                    "func_code": device_cmd["func_code"],
                    "addr": device_cmd["addr"],
                    "count": 1,
                    "values": res_result.registers[0:1]
                }
        elif device_cmd["func_code"] == const.fc_write_registers:
            result = self.modbus_client.write_registers(device_cmd["addr"],
                                                        device_cmd["values"],
                                                        unit=int(device_info["device_addr"]))
            counter = len(device_cmd["values"])
            res_result = self.modbus_client.read_input_registers(device_cmd["addr"],
                                                                 counter,
                                                                 unit=int(device_info["device_addr"]))
            if res_result is None:
                logger.error("device_cmd(%r) retun None." % device_cmd)
                device_data = None
            else:
                device_data = {
                    "func_code": device_cmd["func_code"],
                    "addr": device_cmd["addr"],
                    "count": counter,
                    "values": res_result.registers
                }
        elif device_cmd["func_code"] == const.fc_read_holding_registers:
            res_result = self.modbus_client.read_holding_registers(device_cmd["addr"],
                                                                   device_cmd["count"],
                                                                   unit=int(device_info["device_addr"]))
            if res_result is None:
                logger.error("device_cmd(%r) retun None." % device_cmd)
                device_data = None
            else:
                device_data = {
                    "func_code": device_cmd["func_code"],
                    "addr": device_cmd["addr"],
                    "count": device_cmd["count"],
                    "values": res_result.registers
                }
        elif device_cmd["func_code"] == const.fc_read_input_registers:
            res_result = self.modbus_client.read_input_registers(device_cmd["addr"],
                                                                 device_cmd["count"],
                                                                 unit=int(device_info["device_addr"]))
            if res_result is None:
                logger.error("device_cmd(%r) retun None." % device_cmd)
                device_data = None
            else:
                device_data = {
                    "func_code": device_cmd["func_code"],
                    "addr": device_cmd["addr"],
                    "count": device_cmd["count"],
                    "values": res_result.registers
                }
        else:
            logger.error("不支持的modbus指令:%d" % device_cmd["func_code"])
            device_data = None

        logger.debug("device_data:%r" % device_data)
        if device_data is not None:
            device_data_msg = {
                "device_id": device_info["device_id"],
                "device_addr": device_info["device_addr"],
                "device_port": device_info["device_port"],
                "device_type": device_info["device_type"],
                "protocol": self.protocol.protocol_type,
                "data": {"result": device_data}
            }
            self.mqtt_client.publish_data(device_data_msg)
        else:
            # modbus客户端异常,重置
            self.modbus_client = None


text:
ALTER TABLE organization ADD COLUMN show_history_in_print boolean DEFAULT true NOT NULL;
ALTER TABLE organization ADD COLUMN show_last_modified_in_print boolean DEFAULT true NOT NULL;

# --- !Downs

ALTER TABLE organization DROP COLUMN show_history_in_print;
ALTER TABLE organization DROP COLUMN show_last_modified_in_print;


text:
<?php declare(strict_types=1);

namespace Altair\Cache\Storage;

use Altair\Cache\Contracts\CacheItemStorageInterface;
use Altair\Cache\Exception\InvalidArgumentException;
use Altair\Cache\Support\CacheItemUnserializer;
use Altair\Cache\Traits\RedisNamespaceValidationAwareTrait;
use Exception;
use Predis\Client;
use Predis\Collection\Iterator\Keyspace;
use Predis\Connection\Aggregate\PredisCluster;
use Predis\Connection\Aggregate\RedisCluster;

class PredisCacheItemStorage implements CacheItemStorageInterface
{
    use RedisNamespaceValidationAwareTrait;

    protected $client;
    protected $namespace;

    /**
     * RedisCacheItemPoolStorage constructor.
     *
     * @param Client $redis
     * @param string $namespace
     */
    public function __construct(Client $redis, $namespace = '')
    {
        $info = $redis->info('Server');
        $info = $info['Server'] ?? $info;
        if (!version_compare($info['redis_version'], '2.8', '>=')) {
            throw new InvalidArgumentException(sprintf('%s requires Redis 2.8 or above.', static::class));
        }
        $this->client = $redis;
        $this->useNamespace($namespace);
    }

    /**
     * @inheritDoc
     */
    public function getMaxIdLength(): ?int
    {
        return null;
    }

    /**
     * @inheritDoc
     * @throws \ErrorException
     */
    public function getItems(array $keys = []): array
    {
        $items = [];
        if (!empty($keys)) {
            $values = $this->client->mget($keys);
            foreach ($keys as $index => $key) {
                if ($values[$index]) {
                    $items[$key] = CacheItemUnserializer::unserialize($values[$index]);
                }
            }
        }

        return $items;
    }

    /**
     * @inheritDoc
     */
    public function hasItem(string $key): bool
    {
        return (bool)$this->client->exists($key);
    }

    /**
     * @inheritDoc
     */
    public function clear(): bool
    {
        $success = true;
        $hosts = $this->getHosts($this->client);

        if (null === $hosts) {
            // When using a native Redis cluster, clearing the cache cannot work and always returns false.
            // Clearing the cache should then be done by any other means (e.g. by restarting the cluster).
            //
            // - Thanks Symfony ;)

            return false;
        }

        /** @var Client $host */
        foreach ($hosts as $host) {
            if (!isset($this->namespace[0])) {
                $success = $host->flushdb() && $success;
                continue;
            }

            foreach (new Keyspace($host, $this->namespace . '*', 1000) as $keys) {
                $host->del($keys);
            }
        }

        return $success;
    }

    /**
     * @inheritDoc
     */
    public function deleteItems(array $keys): bool
    {
        if (!empty($keys)) {
            return $this->client->del($keys) === count($keys);
        }

        return true;
    }

    /**
     * @inheritDoc
     */
    public function save(array $values, int $lifespan)
    {
        $serialized = $failed = [];
        foreach ($values as $id => $value) {
            try {
                $serialized[$id] = serialize($value);
            } catch (Exception $e) {
                $failed[] = $id;
            }
        }
        if (empty($serialized)) {
            return $failed;
        }
        if (0 >= $lifespan) {
            $this->client->mset($serialized);

            return $failed;
        }

        $this->client->pipeline(
            static function ($pipe) use ($serialized, $lifespan) {
                /** @var Client $pipe */
                foreach ($serialized as $id => $value) {
                    if (0 >= $lifespan) {
                        $pipe->set($id, $value);
                    } else {
                        $pipe->setex($id, $lifespan, $value);
                    }
                }
            }
        );

        return empty($failed) ? true : $failed;
    }

    /**
     * @param Client $client
     *
     * @return array|null
     */
    protected function getHosts(Client $client): ?array
    {
        $connection = $client->getConnection();

        if ($connection instanceof PredisCluster) {
            $hosts = [];
            foreach ($connection as $c) {
                $hosts[] = new Client($c);
            }
        } elseif ($connection instanceof RedisCluster) {
            return null;
        } else {
            $hosts = [$this->client];
        }

        return $hosts;
    }
}


text:
namespace mars_boost {} namespace boost = mars_boost; namespace mars_boost
{
    namespace range
    {

/// \brief template function copy
///
/// range-based version of the copy std algorithm
///
/// \pre SinglePassRange is a model of the SinglePassRangeConcept
/// \pre OutputIterator is a model of the OutputIteratorConcept
template< class SinglePassRange, class OutputIterator >
inline OutputIterator copy(const SinglePassRange& rng, OutputIterator out)
{
    BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<const SinglePassRange> ));
    return std::copy(mars_boost::begin(rng),mars_boost::end(rng),out);
}

    } // namespace range
    using range::copy;
} // namespace mars_boost {} namespace boost = mars_boost; namespace mars_boost

#endif // include guard


text:
local L = LibStub("AceLocale-3.0"):NewLocale("EPGP", "esMX")
if not L then return end

--@localization(locale="esMX", format="lua_additive_table", same-key-is-true=true)@


text:
package hrv.lib.hrv.calc.parameter;

import hrv.lib.hrv.RRData;
import org.apache.commons.math3.stat.descriptive.moment.StandardDeviation;

public class SDSDCalculator implements HRVDataProcessor {

	@Override
	public HRVParameter process(RRData data) {
		double[] rr = data.getValueAxis();
		var rrDiff = new double[rr.length - 1];

		for (var i = 0; i < rr.length - 1; i++) {
			rrDiff[i] = rr[i] - rr[i + 1];
		}

		var d = new StandardDeviation();
		return new HRVParameter(HRVParameterEnum.SDSD,d.evaluate(rrDiff), "non");
	}

	@Override
	public boolean validData(RRData data) {
		return data.getValueAxis().length > 0;
	}
}


text:
<?php

final class PholioTransactionQuery
  extends PhabricatorApplicationTransactionQuery {

  public function getTemplateApplicationTransaction() {
    return new PholioTransaction();
  }

}


text:
package middlewares

import (
	"io"
	"log"
	"net/http"
	"time"
)

// responseWriter warp http.ResponseWriter.
// There is no way to get http status code and written size by
// using default http.ResponseWriter.
type responseWriter struct {
	http.ResponseWriter
	wroteHeader bool
	status      int
	size        int
}

// WriteHeader warp http.ResponseWriter.WriteHeader
func (rw *responseWriter) WriteHeader(s int) {
	if !rw.wroteHeader {
		rw.wroteHeader = true
		rw.status = s
	}

	rw.ResponseWriter.WriteHeader(s)
}

// Write warp http.ResponseWriter.Write
func (rw *responseWriter) Write(b []byte) (int, error) {
	//	look at http.ResponseWriter.WriteHeader() implementation
	//	if !rw.wroteHeader {
	//		rw.WriteHeader(http.StatusOK)
	//	}
	size, err := rw.ResponseWriter.Write(b)
	rw.size += size
	return size, err
}

// Size of http server written bytes
func (rw *responseWriter) Size() int {
	return rw.size
}

// Status return http server status code
func (rw *responseWriter) Status() int {
	return rw.status
}

// AccessLog write access log to io.Writer
type AccessLog struct {
	log.Logger
}

// NewAccessLog make new AccessLog
func NewAccessLog(out io.Writer) *AccessLog {
	l := log.New(out, "", log.LstdFlags|log.Lmicroseconds)
	return &AccessLog{*l}
}

// ServeHTTP make mung middleware
func (al *AccessLog) ServeHTTP(
	rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	timeStart := time.Now()

	newrw := &responseWriter{rw, false, 0, 0}
	httpMethod := r.Method
	urlPath := r.URL.String()

	next(newrw, r)

	timeEnd := time.Now()
	du := timeEnd.Sub(timeStart)

	al.Printf(
		"%s %s %s %s %d %d",
		r.RemoteAddr, httpMethod, urlPath, du, newrw.Size(), newrw.Status())
}


text:
<?php

use Benrowe\Formatter\Tests\Examples\SampleProvider;

/**
 * Test a concrete version of the AbstractFormatterProvider
 * Ensure that the formatters are available
 */
class AbstractProviderTest extends PHPUnit_Framework_TestCase
{
    private $provider;

    public function setUp()
    {
        $this->provider = new SampleProvider();
    }

    public function testAvailableFormats()
    {
        $this->assertSame(['return', 'rot', 'case'], $this->provider->formats());
        $this->assertSame('foo', $this->provider->asReturn('foo'));
        $this->assertSame('foo', $this->provider->format('foo', 'return'));
    }

    public function testHasFormat()
    {
        $this->assertTrue($this->provider->hasFormat('return'));
        $this->assertFalse($this->provider->hasFormat('doesnotexist'));
    }

    // public function testInvalidFormatName()

    /**
     * @dataProvider invalidFormats
     */
    public function testInvalidFormatName($formatName)
    {
        $this->setExpectedException('InvalidArgumentException');
        $this->provider->hasFormat($formatName);
    }

    public function testInvalidFormat()
    {
        $this->setExpectedException('InvalidArgumentException');
        $this->provider->format('value', 'doesntexist');
    }
    public function testInvalidFormatArray()
    {
        $this->setExpectedException('InvalidArgumentException');
        $this->provider->format('value', ['']);
    }

    public function invalidFormats()
    {
        return [
            'funkyChars' => ['!'],
        ];
    }

    /**
     * @expectedException InvalidArgumentException
     *
     */
    public function testInvalidFormatNameSyntax()
    {
        $this->provider->hasFormat('something.something');

    }
}


text:
describe Twig::Node::Expression::Hash do

  it 'Constructor' do
    elements = [Twig::Node::Expression::Constant.new('foo', 1),
      foo = Twig::Node::Expression::Constant.new('bar', 1)
    ]

    node = Twig::Node::Expression::Hash.new(elements, 1)

    expect(node.nodes[1]).to eq(foo)
  end

  describe ' ' do
    let(:environment) {
      Twig::Environment.new(nil)
    }
    let(:compiler) {
      Twig::Compiler.new(environment)
    }

    it ' ' do
      elements = [
        Twig::Node::Expression::Constant.new('foo', 1),
        Twig::Node::Expression::Constant.new('bar', 1),

        Twig::Node::Expression::Constant.new('bar', 1),
        Twig::Node::Expression::Constant.new('foo', 1)
      ]

      node = Twig::Node::Expression::Hash.new(elements, 1)

      expect(compiler.compile(node).get_source).to eq('{"foo" => "bar", "bar" => "foo"}')
    end
  end
end


text:
---
id: 5a90375238fddaf9a66b5d3b
title: Alinhar um item verticalmente usando align-self
challengeType: 0
videoUrl: 'https://scrimba.com/p/pByETK/cmzd4fz'
forumTopicId: 301123
dashedName: align-an-item-vertically-using-align-self
---

# --description--

Assim como você pode alinhar um item horizontalmente, também existe uma maneira de alinhar um item verticalmente. Para fazer isso, você deve usar a propriedade `align-self` em um grid item. Esta propriedade aceita todos os mesmos valores que `justify-self` do último desafio.

# --instructions--

Alinhe verticalmente o item com a classe `item3` ao final (`end`) da célula.

# --hints--

O elemento de classe `item3` deve ter a propriedade `align-self` com o valor de `end`.

```js
assert(code.match(/.item3\s*?{[\s\S]*align-self\s*?:\s*?end\s*?;[\s\S]*}/gi));
```

# --seed--

## --seed-contents--

```html
<style>
  .item1{background:LightSkyBlue;}
  .item2{background:LightSalmon;}

  .item3 {
    background: PaleTurquoise;
    /* Only change code below this line */

    /* Only change code above this line */
  }

  .item4{background:LightPink;}
  .item5{background:PaleGreen;}

  .container {
    font-size: 40px;
    min-height: 300px;
    width: 100%;
    background: LightGray;
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr 1fr;
    grid-gap: 10px;
  }
</style>

<div class="container">
  <div class="item1">1</div>
  <div class="item2">2</div>
  <div class="item3">3</div>
  <div class="item4">4</div>
  <div class="item5">5</div>
</div>
```

# --solutions--

```html
<style>.item3 {align-self: end;}</style>
```


text:
import { applyMiddleware, compose, createStore } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducer';
import createLogger from 'redux-logger';

export default (initialState = {}) => {
  let finalCreateStore;

  if (process.env.NODE_ENV !== 'production') {
    // configure redux-devtools-extension
    // @see https://github.com/zalmoxisus/redux-devtools-extension
    const logger = createLogger();

    finalCreateStore = compose(
      applyMiddleware(thunk),
      window.devToolsExtension ? window.devToolsExtension() : f => f,
    )(createStore);
  }
  else {
    finalCreateStore = applyMiddleware(thunk)(createStore);
  }

  const store = finalCreateStore(reducer, initialState);

  if (module.hot) {
    module.hot.accept('./reducer', () => {
      store.replaceReducer(require('./reducer').default);
    });
  }

  return store;
};


text:
<?php

namespace App\Phansible\Roles;

use App\Phansible\Model\VagrantBundle;
use App\Phansible\Renderer\VagrantfileRenderer;
use App\Phansible\Role;
use App\Phansible\RoleValuesTransformer;
use PHPUnit\Framework\TestCase;

class VagrantLocalTest extends TestCase
{
    private $role;

    public function setUp(): void
    {
        $this->role = new VagrantLocal();
    }

    public function tearDown(): void
    {
        unset($this->role);
    }

    /**
     * @covers \App\Phansible\Roles\VagrantLocal
     */
    public function testShouldInstanceOf(): void
    {
        $this->assertInstanceOf(Role::class, $this->role);
        $this->assertInstanceOf(RoleValuesTransformer::class, $this->role);
    }

    /**
     * @covers \App\Phansible\Roles\VagrantLocal::getName
     */
    public function testShouldGetName(): void
    {
        $this->assertEquals('Local', $this->role->getName());
    }

    /**
     * @covers \App\Phansible\Roles\VagrantLocal::getSlug
     */
    public function testShouldGetSlug(): void
    {
        $this->assertEquals('vagrant_local', $this->role->getSlug());
    }

    /**
     * @covers \App\Phansible\Roles\VagrantLocal::getRole
     */
    public function testShouldGetRole(): void
    {
        $this->assertEquals('vagrant_local', $this->role->getRole());
    }

    /**
     * @covers \App\Phansible\Roles\VagrantLocal::getInitialValues
     */
    public function testShouldGetInitialValues(): void
    {
        $expected = [];

        $this->assertEquals($expected, $this->role->getInitialValues());
    }

    /**
     * @covers \App\Phansible\Roles\VagrantLocal::transformValues
     * @covers \App\Phansible\Roles\VagrantLocal::getVagrantFile
     * @covers \App\Phansible\Roles\VagrantLocal::getBox
     */
    public function testShouldTransformValues(): void
    {
        $values = [
            'vm' => [
                'base_box'     => 'trusty64',
                'hostname'     => 'default',
                'ip'           => '192.168.33.99',
                'memory'       => '512',
                'sharedfolder' => './',
                'mountPoint'   => '/vagrant',
                'syncType'     => 'nfs',
            ],
        ];

        $bundle = $this->getMockBuilder(VagrantBundle::class)
            ->disableOriginalConstructor()
            ->onlyMethods(['setVagrantFile'])
            ->getMock();

        $bundle->expects($this->once())
            ->method('setVagrantFile')
            ->with(
                $this->isInstanceOf(VagrantfileRenderer::class)
            );

        $this->role->transformValues($values, $bundle);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<chapter xml:id="KSB_Security" xmlns="http://docbook.org/ns/docbook" version="5.0">
    <title>Security</title>

        <title>Overview</title>

        <para>Acegi handles the security layer for KSB. Acegi uses remote method
            invocation to hold the application's security context and to propagate
            this object through to the service layer.</para>

        <title>Security Management</title>
        <para>For client applications to consume secured services hosted from a standalone Rice
            server, the implementer must generate a keystore in KSB. KSB security relies on the
            creation of a keystore using the JVM keytool.</para>

<title>Create Keystore</title>
            <mediaobject>
                <imageobject>
                    <imagedata fileref="../images/KSB_Guide/create_keystore.png"/>
                </imageobject>
            </mediaobject>

        <para>To create a new Client Keystore file, complete all three fields and click the create
            button that is just below the fields:</para>

<title>Create Keystore: File Section</title>
            <mediaobject>
                <imageobject>
                    <imagedata fileref="../images/KSB_Guide/create_keystore_file.png"/>
                </imageobject>
            </mediaobject>

        <para>The <emphasis role="bold">Desired Alias</emphasis> (name for the new keystore you are
            creating) must be unique among your keystores. KSB automatically displays a list of
            existing Keystore entries for your reference below the <emphasis role="italic">Create
                new Client Keystore file</emphasis> table. The data in this list can be sorted in
            ascending or descending order by clicking the column heading for any column except
            <emphasis role="italic">Actions</emphasis>. </para>

<title>Create Keystore: Existing Keystore Section</title>
            <mediaobject>
                <imageobject>
                    <imagedata fileref="../images/KSB_Guide/existing_keystore_entries.png"/>
                </imageobject>
            </mediaobject>

        <para>

                <title>Existing Keystore Entries: Attributes</title>
                <tgroup cols="2">
                    <colspec colname="c1" colnum="1" colwidth="1.0*"/>
                    <colspec colname="c2" colnum="2" colwidth="1.0*"/>

                        <row>
                            <entry>Field</entry>
                            <entry>Description</entry>
                        </row>

                        <row>
                            <entry>Alias</entry>
                            <entry>Keystore name</entry>
                        </row>
                        <row>
                            <entry>Create Date</entry>
                            <entry>Date and time the keystore was created</entry>
                        </row>
                        <row>
                            <entry>Type</entry>
                            <entry>The type of keystore </entry>
                        </row>
                        <row>
                            <entry>Actions</entry>
                            <entry/>
                        </row>

                </tgroup>

        </para>

        <title>Credentials types</title>

        <para>There are several security types you can use to propagate the
            security context object:<itemizedlist>
                <listitem>
                    <para>CAS</para>
                </listitem>

                <listitem>
                    <para>USERNAME_PASSWORD</para>
                </listitem>

                <listitem>
                    <para>JAAS</para>
                </listitem>

                <listitem>
                    <para>X509</para>
                </listitem>
            </itemizedlist></para>

        <title>CredentialsSource</title>

        <para>The CredentialsSource is an interface that helps obtain security
            credentials. It encapsulates the actual source of credentials. The two
            ways to obtain the source are:<itemizedlist>
                <listitem>
                    <para>X509CredentialsSource - X509 Certificate</para>
                </listitem>

                <listitem>
                    <para>UsernamePasswordCredentialsSource - Username and
                        Password</para>
                </listitem>
            </itemizedlist></para>

            <title>KSB security: Server side configuration</title>

            <para>Here is a code snippet that shows the changes needed to
                configure KSB security on the server side:</para>

            <programlisting linenumbering = "numbered"><bean id="ksbConfigurer" class="org.kuali.rice.ksb.messaging.config.KSBConfigurer">
    <!-- Other properties removed -->
    <property name="services">
        <list>
            <bean class="org.kuali.rice.ksb.api.bus.support.SoapServiceDefinition">
                <property name="service">
                    <ref bean="soapService" />
                </property>
                <property name="localServiceName" value="soapLocalName"/>
                <property name="serviceNameSpaceURI" value="soapNameSpace"/>
                <property name="serviceInterface" value="org.kuali.ksb.examples.SOAPEchoService"/>
                <property name="priority" value="3"/>
                <property name="retryAttempts" value="1" />
                <property name="busSecurity" value="false"></property>

                <!-- Valid Values: CAS, KERBEROS -->
                <property name="credentialsType" value="CAS"/>
            </bean>
            <bean class="org.kuali.rice.ksb.api.bus.support.JavaServiceDefinition">
                <property name="service" ref="echoService"></property>
                <property name="localServiceName" value="javaLocalName" />
                <property name="serviceNameSpaceURI" value="javaNameSpace"/>
                <property name="serviceInterface" value="org.kuali.ksb.examples.EchoService"/>
                <property name="priority" value="5" />
                <property name="retryAttempts" value="1" />
                <property name="busSecurity" value="true" />

                <!-- Valid Values: CAS, KERBEROS -->
                <property name="credentialsType" value="CAS"/>
            </bean>
            <!-- Other services removed -->
        </list>
    </property>
</bean></programlisting>

            <title>KSB security: Client side configuration</title>

            <programlisting linenumbering = "numbered"><bean id="customCredentialsSourceFactory" class="edu.myinstituition.myapp.security.credentials.CredentialsSourceFactory" />

<bean id="coreConfigurer" class="org.kuali.rice.core.impl.config.module.CoreConfigurer">
    <!-- Other properties removed -->
    <property name="credentialsSourceFactory" ref="customCredentialsSourceFactory">
</bean>
</programlisting>

        <title>KSB connector and exporter code</title>

            <title>Connectors</title>

            <para>Connectors are used by a client to connect to a service that is
                usually exposed through the KSB registry. The Service Connector
                factory provides a bean that holds a proxy to a remote service with
                some contextual information. The factory determines the type of proxy
                to invoke based on the service definition. The service definition used
                by the server is serialized to the database and de-serialized by the
                client. There are different types of connectors supported by KSB, most
                notable are SOAP and Java over HTTP.</para>

            <title>Exporters</title>

            <para>Services, when exported, can be secured using standard Acegi
                methods. A security manager and an interceptor help organize the set
                of Business Objects that are exported.</para>

        <title>Security and Keystores</title>

            <title>Generating the Keystore</title>

            <para>For client applications to be able to consume secured services
                hosted from a Rice server, the implementer must generate a keystore.
                As an initial setup, KSB security relies on the creation of a keystore
                using the JVM keytool as follows:</para>

            <title>Step 1: Create the Keystore</title>

            <para>The first step is to create the keystore and generate a
                public-private key combination for the client application. When using
                secured services on the KSB, we require the client applications
                transfer their messages digitally signed so that Rice can verify the
                messages authenticity. This is why we must generate these keys.</para>

            <para>Generate your initial Rice keystore as follows:</para>

            <programlisting>keytool -genkey -validity 9999 -alias rice -keyalg RSA -keystore rice.keystore -dname "cn=rice" -keypass r1c3pw -storepass r1c3pw</programlisting>

            <caution>
                <para>keypass and storepass should be the same.</para>

                <para>r1c3pw is the password used for the provided example.</para>
            </caution>

            <title>Step 2: Sign the Key</title>

            <para>This generates the keystore in a file called "rice_keystore" in
                the current directory and generates an RSA key with the alias of
                "rice". Since there is no certificate signing authority to sign our
                key, we must sign it ourselves. To do this, execute the following
                command:</para>

            <programlisting>keytool  -selfcert -validity 9999 -alias rice -keystore rice.keystore -keypass r1c3pw -storepass r1c3pw</programlisting>

            <title>Step 3: Generate the Certificate</title>

            <para>After the application's certificate has been signed, we must
                export it so that it can be imported into the Rice keystore. To export
                a certificate, execute the following command:</para>

            <programlisting>keytool  -export -alias rice -file rice.cert -keystore rice.keystore -storepass r1c3pw</programlisting>

            <title>Step 4: Import Application Certificates</title>

            <para>The client application's certificate can be imported using the
                following command:</para>

            <programlisting>keytool  -import -alias rice -file client.application.cert.file -keystore rice.keystore -storepass r1c3pw</programlisting>

            <para>The keystore file will end up deployed wherever your keystores
                are stored so hang on to both of these files and don't lose them!
                Also, notice that we specified a validity of 9999 days for the
                keystore and cert. This is so you do not have to continually update
                these keystores. This will be determined by your computing standards
                on how you handle key management.</para>

            <title>Configure KSB to use the keystore</title>

            <para>The following params are needed in the xml config to allow the
                ksb to use the keystore:</para>

            <programlisting linenumbering = "numbered"><param name="keystore.file">/usr/local/rice/rice.keystore</param>
<param name="keystore.alias">rice</param>
<param name="keystore.password"> password </param>
</programlisting>

            <para><itemizedlist>
                <listitem>
                    <para>keystore.file - is the location of the keystore</para>
                </listitem>

                <listitem>
                    <para>keystore.alias - is the alias used in creating the
                        keystore above</para>
                </listitem>

                <listitem>
                    <para>keystore.password - this is the password of the alias AND
                        the keystore. This assumes that the keystore is up in such a way
                        that these are the same.</para>
                </listitem>
            </itemizedlist></para>

        <title>BasicAuthenticationService</title>
        <para>The <emphasis role="bold">BasicAuthenticationService</emphasis> allows services published on the
            KSB to be accessed securely with basic authentication.  As an example, here is how the
            <emphasis role="bold">Workflow Document Actions Service</emphasis> could be exposed as a service
            with basic authentication.</para>

        <para><itemizedlist>
            <listitem>
                <para>Add the following bean to a spring bean file that is loaded as a part of the KEW module.
                    <programlisting linenumbering = "numbered"><bean id="rice.kew.workflowDocumentActionServiceBasicAuthentication.exporter"
              parent="kewServiceExporter" lazy-init="false">
    <property name="serviceDefinition">
        <bean parent="kewService">
            <property name="service">
                <ref bean="rice.kew.workflowDocumentActionsService" />
            </property>
            <property name="localServiceName"
                 value="workflowDocumentActionsService-basicAuthentication" />
            <property name="busSecurity"
                 value="${rice.kew.workflowDocumentActionsService.secure}" />
            <property name="basicAuthentication" value="true" />
        </bean>
    </property>
</bean></programlisting></para>
            </listitem>

            <listitem>
                <para>Add the following bean to a spring bean file that is loaded as a part of the KSB module.
                    <programlisting linenumbering = "numbered"><bean class="org.kuali.rice.ksb.service.BasicAuthenticationCredentials">
    <property name="serviceNameSpaceURI"
          value="http://rice.kuali.org/kew/v2_0" />
    <property name="localServiceName"
          value="workflowDocumentActionsService-basicAuthentication" />
    <property name="username"
          value="${WorkflowDocumentActionsService.username}" />
    <property name="password"
          value="${WorkflowDocumentActionsService.password}" />
    <property name="authenticationService" ref="basicAuthenticationService" />
</bean></programlisting></para>
            </listitem>

            <listitem>
                <para>Add the following config parameters to a secure file that is loaded when the application is started.

                    <programlisting linenumbering = "numbered"><param name="WorkflowDocumentActionsService.username">username</param>
<param name="WorkflowDocumentActionsService.password">pw</param></programlisting></para>
            </listitem>

            <listitem>
                <para>To verify the new service can be called, it can be tested using a tool such as soapUI.
                    Here is an example call which will invoke the method <emphasis role="bold">logAnnotation</emphasis> on
                    <emphasis role="bold">WorkflowDocumentActionsServiceImpl</emphasis>.
                    <programlisting linenumbering = "numbered"><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                xmlns:v2="http://rice.kuali.org/kew/v2_0">
  <soapenv:Header>
    <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
            soapenv:mustUnderstand="1">
      <wsse:UsernameToken xmlns:wsu=
          "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
          wsu:Id="UsernameToken-1815911473">
        <wsse:Username>username</wsse:Username>
        <wsse:Password Type=
          "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">pw</wsse:Password>
      </wsse:UsernameToken>
    </wsse:Security>
  </soapenv:Header>
  <soapenv:Body>
    <v2:logAnnotation>
      <v2:documentId>123456</v2:documentId>
      <v2:principalId>admin</v2:principalId>
      <v2:annotation>Add this annotation please.</v2:annotation>
    </v2:logAnnotation>
  <soapenv:Body>
</soapenv:Envelope></programlisting></para>
            </listitem>
        </itemizedlist>
        </para>

    </chapter>


text:
Segera Hadir

Konferensi Perangkat Lunak Merdeka 2016

Jakarta, XX Oktober 2016

Ikuti kami:

Twitter: https://twitter.com/KopralMerdeka

Facebook: https://www.facebook.com/Kopral-Merdeka-726624010806396


text:
package v1alpha1

import (
	"fmt"

	"github.com/ghodss/yaml"
	"github.com/pkg/errors"

	apis "github.com/openebs/maya/pkg/apis/openebs.io/upgrade/v1alpha1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

//UpgradeResult holds the apis upgraderesult object
type UpgradeResult struct {
	// upgrade result object
	object *apis.UpgradeResult
}

// UpgradeResultList is the list of
// upgradeResults
type UpgradeResultList struct {
	// list of upgrade results
	items []*UpgradeResult
}

// Builder enables building an instance of
// upgradeResult
type Builder struct {
	*UpgradeResult
	checks map[*Predicate]string
	errors []error
}

// Predicate abstracts conditional logic w.r.t the upgradeResult instance
//
// NOTE:
// Predicate is a functional approach versus traditional approach to mix
// conditions such as *if-else* within blocks of business logic
//
// NOTE:
// Predicate approach enables clear separation of conditionals from
// imperatives i.e. actions that form the business logic
type Predicate func(*UpgradeResult) bool

// NewBuilder returns a new instance of Builder
func NewBuilder() *Builder {
	return &Builder{
		UpgradeResult: &UpgradeResult{
			object: &apis.UpgradeResult{},
		},
		checks: make(map[*Predicate]string),
	}
}

// WithTypeMeta adds typemeta in upgrade result instance.
func (b *Builder) WithTypeMeta(typeMeta metav1.TypeMeta) *Builder {
	b.object.TypeMeta = typeMeta
	return b
}

// WithObjectMeta adds objectMeta in upgrade result instance.
func (b *Builder) WithObjectMeta(objectMeta metav1.ObjectMeta) *Builder {
	b.object.ObjectMeta = objectMeta
	return b
}

// WithTasks adds tasks details in upgrade result instance.
func (b *Builder) WithTasks(tasks ...apis.UpgradeResultTask) *Builder {
	b.object.Tasks = append(b.object.Tasks, tasks...)
	return b
}

// WithResultConfig adds resource details and runtime
// config in upgrade result instance.
func (b *Builder) WithResultConfig(resource apis.ResourceDetails,
	data ...apis.DataItem) *Builder {
	b.object.Config.ResourceDetails = resource
	b.object.Config.Data = append(b.object.Config.Data, data...)
	return b
}

// BuilderForYAMLObject returns a new instance
// of Builder for a given template object
func BuilderForYAMLObject(object []byte) *Builder {
	b := &Builder{
		UpgradeResult: &UpgradeResult{
			object: &apis.UpgradeResult{},
		},
		checks: make(map[*Predicate]string),
	}
	err := yaml.Unmarshal(object, b.object)
	if err != nil {
		b.errors = append(b.errors, err)
		return b
	}
	return b
}

// Build returns the final instance of upgradeResult
func (b *Builder) Build() (*apis.UpgradeResult, error) {
	if len(b.errors) != 0 {
		return nil, errors.Errorf("%v", b.errors)
	}
	err := b.validate()
	if err != nil {
		return nil, err
	}
	return b.UpgradeResult.object, nil
}

// validate will run checks against upgrade
// result instance
func (b *Builder) validate() error {
	for cond := range b.checks {
		pass := (*cond)(b.UpgradeResult)
		if !pass {
			b.errors = append(b.errors,
				errors.Errorf("validation failed: %s", b.checks[cond]))
		}
	}
	if len(b.errors) == 0 {
		return nil
	}
	return errors.Errorf("%v", b.errors)
}

// AddCheckf adds the predicate as a condition to be validated against the
// upgrade result instance and format the message string according to format specifier.
// If only predicate and message string is provided, it will treat it as the
// value for the corresponding predicate.
func (b *Builder) AddCheckf(p Predicate, predicateMsg string, args ...interface{}) *Builder {
	b.checks[&p] = fmt.Sprintf(predicateMsg, args...)
	return b
}

// AddCheck adds the predicate as a condition to be validated against the
// upgrade result instance
func (b *Builder) AddCheck(p Predicate) *Builder {
	return b.AddCheckf(p, "")
}

// AddChecks adds the provided predicates as conditions to be validated against
// the upgrade result instance
func (b *Builder) AddChecks(predicates ...Predicate) *Builder {
	for _, check := range predicates {
		b.AddCheck(check)
	}
	return b
}

// ListBuilder enables building
// an instance of upgradeResultList
type ListBuilder struct {
	list *UpgradeResultList
}

// NewListBuilder returns a new instance
// of ListBuilder
func NewListBuilder() *ListBuilder {
	return &ListBuilder{list: &UpgradeResultList{}}
}

// WithAPIList builds the list of ur
// instances based on the provided
// ur api instances
func (b *ListBuilder) WithAPIList(list *apis.UpgradeResultList) *ListBuilder {
	if list == nil {
		return b
	}
	for i := range list.Items {
		b.list.items = append(b.list.items, &UpgradeResult{object: &list.Items[i]})
	}
	return b
}

// List returns the list of ur
// instances that was built by this
// Builder
func (b *ListBuilder) List() *UpgradeResultList {
	return b.list
}


text:
<!DOCTYPE html>
<html lang="en">

{% include head.html %}

<body>
{% include pageheader.html %}
    <main>
    {{content}}
    </main>
    <script src={{url}}/js/main.js></script>
</body>

</html>


text:
// CLASS HEADER
#include <dali/internal/network/common/network-performance-client.h>

// EXTERNAL INCLUDES
#include <stdio.h>
#include <iostream>
#include <string>

// INTERNAL INCLUDES
#include <dali/internal/network/common/automation.h>
#include <dali/internal/network/common/network-performance-protocol.h>
#include <dali/internal/network/common/socket-interface.h>

namespace Dali
{
namespace Internal
{
namespace Adaptor
{
namespace
{
const float MICROSECONDS_TO_SECOND = 1e-6;
const char  UNKNOWN_CMD[]          = "Command or parameter invalid, type help for list of commands\n";

/**
 * helper class to store data along with the automation callback.
 */
class AutomationCallback : public CallbackBase
{
public:
  /**
   * instead of using templates, or having different callback classes for each callback
   * we use a command id that decides which static function to call on the Automation class.
   */
  enum CommandId
  {
    UNKNOWN_COMMAND,
    SET_PROPERTY,
    CUSTOM_COMMAND,
    DUMP_SCENE
  };

  AutomationCallback(unsigned int clientId, ClientSendDataInterface& sendDataInterface)
  : CallbackBase(reinterpret_cast<void*>(this),
                 NULL, // we get the dispatcher to call function directly
                 reinterpret_cast<CallbackBase::Dispatcher>(&AutomationCallback::Dispatcher)),
    mSendDataInterface(sendDataInterface),
    mCommandId(UNKNOWN_COMMAND),
    mClientId(clientId)
  {
  }

  void AssignSetPropertyCommand(std::string setPropertyCommand)
  {
    mCommandId     = SET_PROPERTY;
    mCommandString = setPropertyCommand;
  }

  void AssignDumpSceneCommand()
  {
    mCommandId = DUMP_SCENE;
  }

  void AssignCustomCommand(std::string&& customCommand)
  {
    mCommandId     = CUSTOM_COMMAND;
    mCommandString = std::move(customCommand);
  }

  void RunCallback()
  {
    switch(mCommandId)
    {
      case SET_PROPERTY:
      {
        Automation::SetProperty(mCommandString);
        break;
      }
      case DUMP_SCENE:
      {
        Automation::DumpScene(mClientId, &mSendDataInterface);
        break;
      }
      case CUSTOM_COMMAND:
      {
        Automation::SetCustomCommand(mCommandString);
        break;
      }
      default:
      {
        DALI_ASSERT_DEBUG(0 && "Unknown command");
        break;
      }
    }
  }
  static void Dispatcher(CallbackBase& base)
  {
    AutomationCallback& automationCallback(static_cast<AutomationCallback&>(base));
    automationCallback.RunCallback();
  }

private:
  std::string              mCommandString;     ///< command string for property or custom command
  ClientSendDataInterface& mSendDataInterface; ///< Abstract client send data interface
  CommandId                mCommandId;         ///< command id
  const unsigned int       mClientId;          ///< client id
};

/**
 * @brief Helper to ensure the AutomationCallback method we want is called in the main thread
 */
template<typename T>
void TriggerOnMainThread(unsigned int clientId, ClientSendDataInterface& sendDataInterface, T&& lambda)
{
  // this needs to be run on the main thread, use the trigger event....
  AutomationCallback* callback = new AutomationCallback(clientId, sendDataInterface);
  lambda(callback);

  // create a trigger event that automatically deletes itself after the callback has run in the main thread
  TriggerEventInterface* interface = TriggerEventFactory::CreateTriggerEvent(callback, TriggerEventInterface::DELETE_AFTER_TRIGGER);

  // asynchronous call, the call back will be run sometime later on the main thread
  interface->Trigger();
}

} // unnamed namespace

NetworkPerformanceClient::NetworkPerformanceClient(pthread_t*               thread,
                                                   SocketInterface*         socket,
                                                   unsigned int             clientId,
                                                   ClientSendDataInterface& sendDataInterface,
                                                   SocketFactoryInterface&  socketFactory)
: mThread(thread),
  mSocket(socket),
  mMarkerBitmask(PerformanceMarker::FILTERING_DISABLED),
  mSendDataInterface(sendDataInterface),
  mSocketFactoryInterface(socketFactory),
  mClientId(clientId),
  mConsoleClient(false)
{
}

NetworkPerformanceClient::~NetworkPerformanceClient()
{
  if(mSocket->SocketIsOpen())
  {
    mSocket->CloseSocket();
  }
  mSocketFactoryInterface.DestroySocket(mSocket);
}

unsigned int NetworkPerformanceClient::GetId() const
{
  return mClientId;
}

SocketInterface& NetworkPerformanceClient::GetSocket()
{
  return *mSocket;
}

bool NetworkPerformanceClient::WriteSocket(const void* buffer, unsigned int bufferSizeInBytes)
{
  return mSocket->Write(buffer, bufferSizeInBytes);
}

bool NetworkPerformanceClient::TransmitMarker(const PerformanceMarker& marker, const char* const description)
{
  if(!marker.IsFilterEnabled(mMarkerBitmask))
  {
    return true;
  }
  if(mConsoleClient)
  {
    // write out the time stamp
    char   *buffer;
    double usec = marker.GetTimeStamp().microseconds;
    int    size = asprintf(&buffer, "%.6f (seconds), %s\n", usec * MICROSECONDS_TO_SECOND, description);
    auto retVal = mSocket->Write(buffer, size);
    free(buffer);
    return retVal;
  }

  // todo serialize the data
  return false;
}

void NetworkPerformanceClient::ExitSelect()
{
  mSocket->ExitSelect();
}

pthread_t* NetworkPerformanceClient::GetThread()
{
  return mThread;
}

void NetworkPerformanceClient::ProcessCommand(char* buffer, unsigned int bufferSizeInBytes)
{
  // if connected via console, then strip off the carriage return, and switch to console mode
  if(buffer[bufferSizeInBytes - 1] == '\n')
  {
    buffer[bufferSizeInBytes - 1] = 0;
    mConsoleClient                = true;
  }
  unsigned int                   param(0);
  std::string                    stringParam;
  PerformanceProtocol::CommandId commandId(PerformanceProtocol::UNKNOWN_COMMAND);

  bool ok = PerformanceProtocol::GetCommandId(buffer, bufferSizeInBytes, commandId, param, stringParam);
  if(!ok)
  {
    WriteSocket(UNKNOWN_CMD, sizeof(UNKNOWN_CMD));
    return;
  }
  std::string response;

  switch(commandId)
  {
    case PerformanceProtocol::HELP_MESSAGE:
    {
      response = PerformanceProtocol::GetHelpMessage();
      break;
    }

    case PerformanceProtocol::ENABLE_TIME_MARKER_BIT_MASK:
    {
      mMarkerBitmask = static_cast<PerformanceMarker::MarkerFilter>(param);
      response       = "enable time marker ";
      break;
    }

    case PerformanceProtocol::DUMP_SCENE_GRAPH:
    {
      TriggerOnMainThread(mClientId, mSendDataInterface, [&](AutomationCallback* callback){callback->AssignDumpSceneCommand();});
      break;
    }

    case PerformanceProtocol::SET_PROPERTIES:
    {
      TriggerOnMainThread(mClientId, mSendDataInterface, [&](AutomationCallback* callback){callback->AssignSetPropertyCommand(stringParam);});
      response = "Completed";
      break;
    }

    case PerformanceProtocol::CUSTOM_COMMAND:
    {
      TriggerOnMainThread(mClientId, mSendDataInterface, [&](AutomationCallback* callback){callback->AssignCustomCommand(std::move(stringParam));});
      response = "Completed";
      break;
    }

    case PerformanceProtocol::LIST_METRICS_AVAILABLE:
    case PerformanceProtocol::ENABLE_METRIC:
    case PerformanceProtocol::DISABLE_METRIC:
    {
      response = "Metrics currently not supported";
      break;
    }
    default:
    {
      response = UNKNOWN_CMD;
      break;
    }
  }
  if(!response.empty())
  {
    // add a carriage return for console clients
    if(mConsoleClient)
    {
      response += "\n";
    }
    WriteSocket(response.c_str(), response.length());
  }
}

} // namespace Adaptor

} // namespace Internal

} // namespace Dali


text:
<?php

namespace Pms\CoreBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Pms\UserBundle\Entity\User;

/**
 * Receive
 *
 * @ORM\Table(name="receives")
 * @ORM\Entity(repositoryClass="Pms\CoreBundle\Entity\Repository\ReceiveRepository")
 */
class Receive
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var User
     *
     * @ORM\ManyToOne(targetEntity="Pms\UserBundle\Entity\User")
     * @ORM\JoinColumn(name="received_by", nullable=true)
     */
    private $receivedBy;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="received_date", type="datetime")
     */
    private $receivedDate;

    /**
     * @var Invoice
     *
     * @ORM\ManyToOne(targetEntity="Pms\CoreBundle\Entity\Invoice", inversedBy="receive")
     * @ORM\JoinColumn(name="invoices")
     */
    private $invoice;

    /**
     * @var Invoice
     *
     * @ORM\ManyToOne(targetEntity="Pms\CoreBundle\Entity\Invoice")
     * @ORM\JoinColumn(name="calan")
     */
    private $calan;

    /**
     * @var string
     *
     * @ORM\Column(name="grn", type="string", length=255, nullable=true)
     */
    private $grn;

    /**
     * @var ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="Pms\CoreBundle\Entity\ReceivedItem", mappedBy="receive", cascade={"persist", "remove"})
     */
    private $receiveItems;

    /**
     * @var Vendor
     *
     * @ORM\ManyToOne(targetEntity="Pms\CoreBundle\Entity\Vendor", inversedBy="receive")
     * @ORM\JoinColumn(name="vendors", nullable=true)
     */
    private $vendor;

    /**
     * @var User
     *
     * @ORM\ManyToOne(targetEntity="Pms\UserBundle\Entity\User")
     * @ORM\JoinColumn(name="buyers", nullable=true)
     */
    private $buyer;

    /**
     * @var integer
     *
     * @ORM\Column(name="status", type="integer")
     */
    private $status;

    /**
     * @var User
     *
     * @ORM\ManyToOne(targetEntity="Pms\UserBundle\Entity\User")
     * @ORM\JoinColumn(name="closed_by", nullable=true)
     */
    private $closedBy;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="closed_date", type="datetime", nullable=true)
     */
    private $closedDate;

    public function __construct()
    {
        $this->receiveItems = new ArrayCollection();
    }

    /**
     * Set closedBy
     *
     * @param User $closedBy
     * @return Receive
     */
    public function setClosedBy($closedBy)
    {
        $this->closedBy = $closedBy;

        return $this;
    }

    /**
     * Get closedBy
     *
     * @return User
     */
    public function getClosedBy()
    {
        return $this->closedBy;
    }

    /**
     * Set closedDate
     *
     * @param \DateTime $closedDate
     * @return Receive
     */
    public function setClosedDate($closedDate)
    {
        $this->closedDate = $closedDate;

        return $this;
    }

    /**
     * Get closedDate
     *
     * @return \DateTime
     */
    public function getClosedDate()
    {
        return $this->closedDate;
    }

    /**
     * Set status
     *
     * @param integer $status
     * @return Receive
     */
    public function setStatus($status)
    {
        $this->status = $status;

        return $this;
    }

    /**
     * Get status
     *
     * @return integer
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * Set buyer
     *
     * @param User $buyer
     * @return Receive
     */
    public function setBuyer($buyer)
    {
        $this->buyer = $buyer;

        return $this;
    }

    /**
     * Get buyer
     *
     * @return User
     */
    public function getBuyer()
    {
        return $this->buyer;
    }

    /**
     * Set vendor
     *
     * @param integer $vendor
     * @return Receive
     */
    public function setVendor($vendor)
    {
        $this->vendor = $vendor;

        return $this;
    }

    /**
     * Get vendor
     *
     * @return integer
     */
    public function getVendor()
    {
        return $this->vendor;
    }

    public function addReceiveItem(ReceivedItem $item)
    {
        $item->setReceive($this);

        if (!$this->getReceiveItems()->contains($item)) {
            $this->receiveItems->add($item);
        }

        return $this;
    }

    public function removeReceiveItem(ReceivedItem $item)
    {
        if ($this->getReceiveItems()->contains($item)) {
            $this->getReceiveItems()->removeElement($item);
        }
    }

    public function getReceiveItems()
    {
        return $this->receiveItems;
    }

    /**
     * Set invoice
     *
     * @param Invoice $invoice
     * @return Receive
     */
    public function setInvoice($invoice)
    {
        $this->invoice = $invoice;

        return $this;
    }

    /**
     * Get invoice
     *
     * @return Invoice
     */
    public function getInvoice()
    {
        return $this->invoice;
    }

    /**
     * Set calan
     *
     * @param Invoice $calan
     * @return Receive
     */
    public function setCalan($calan)
    {
        $this->calan = $calan;

        return $this;
    }

    /**
     * Get calan
     *
     * @return Invoice
     */
    public function getCalan()
    {
        return $this->calan;
    }

    /**
     * Set grn
     *
     * @param string $grn
     * @return Receive
     */
    public function setGrn($grn)
    {
        $this->grn = $grn;

        return $this;
    }

    /**
     * Get grn
     *
     * @return string
     */
    public function getGrn()
    {
        return $this->grn;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set receivedBy
     *
     * @param User $receivedBy
     * @return Receive
     */
    public function setReceivedBy($receivedBy)
    {
        $this->receivedBy = $receivedBy;

        return $this;
    }

    /**
     * Get receivedBy
     *
     * @return User
     */
    public function getReceivedBy()
    {
        return $this->receivedBy;
    }

    /**
     * Set receivedDate
     *
     * @param \DateTime $receivedDate
     * @return Receive
     */
    public function setReceivedDate($receivedDate)
    {
        $this->receivedDate = $receivedDate;

        return $this;
    }

    /**
     * Get receivedDate
     *
     * @return \DateTime
     */
    public function getReceivedDate()
    {
        return $this->receivedDate;
    }
}


text:
node-lp_solve
============

A NodeJS module for createing and solving simple Linear Programs using lp_solve.

Example:

```javascript

// solve http://people.brunel.ac.uk/~mastjjb/jeb/or/morelp.html

var lpsolve = require('lp_solve');
var Row = lpsolve.Row;

var lp = new lpsolve.LinearProgram();

var x = lp.addColumn('x'); // lp.addColumn('x', true) for integer variable
var y = lp.addColumn('y'); // lp.addColumn('y', false, true) for binary variable

var objective = new Row().Add(x, 1).Add(y, 1);

lp.setObjective(objective);

var machineatime = new Row().Add(x, 50).Add(y, 24);
lp.addConstraint(machineatime, 'LE', 2400, 'machine a time')

var machinebtime = new Row().Add(x, 30).Add(y, 33);
lp.addConstraint(machinebtime, 'LE', 2100, 'machine b time')

lp.addConstraint(new Row().Add(x, 1), 'GE', 75 - 30, 'meet demand of x')
lp.addConstraint(new Row().Add(y, 1), 'GE', 95 - 90, 'meet demand of y')

console.log(lp.dumpProgram());
console.log(lp.solve());
console.log('objective =', lp.getObjectiveValue())
console.log('x =', lp.get(x));
console.log('y =', lp.get(y));
console.log('machineatime =', lp.calculate(machineatime));
console.log('machinebtime =', lp.calculate(machinebtime));

```

Output

```
minimize: +1 x +1 y
subject to
machine a time:  +50 x +24 y <= 2400
machine b time:  +30 x +33 y <= 2100
meet demand of x:  +1 x >= 45
meet demand of y:  +1 y >= 5

Model name:  '' - run #1
Objective:   Minimize(R0)

SUBMITTED
Model size:        4 constraints,       2 variables,            6 non-zeros.
Sets:                                   0 GUB,                  0 SOS.

Using DUAL simplex for phase 1 and PRIMAL simplex for phase 2.
The primal and dual simplex pricing strategy set to 'Devex'.

Optimal solution                  50 after          2 iter.

Excellent numeric accuracy ||*|| = 0

 MEMO: lp_solve version 5.5.2.0 for 64 bit OS, with 64 bit REAL variables.
      In the total iteration count 2, 0 (0.0%) were bound flips.
      There were 0 refactorizations, 0 triggered by time and 0 by density.
       ... on average 2.0 major pivots per refactorization.
      The largest [LUSOL v2.2.1.0] fact(B) had 5 NZ entries, 1.0x largest basis.
      The constraint matrix inf-norm is 50, with a dynamic range of 50.
      Time to load data was 0.001 seconds, presolve used 0.004 seconds,
       ... 0.003 seconds in simplex solver, in total 0.008 seconds.

{ code: 0, description: 'OPTIMAL' }
objective = 50
x = 45
y = 5
machineatime = 2370
machinebtime = 1515
```

Access to the full lp_solve api is available through lp.lprec - some functions have not been checked and may not work as expected.

e.g.:

```
var lpsolve = require('lp_solve');

var lp = new lpsolve.LinearProgram();

lp.lprec.set_presolve(/* PRESOLVE_NONE */ 0, 0);

```


text:
(function () {
  'use strict';
  angular.module('zxcvbn', [])
    .directive('zxcvbn', function () {
      return {
        scope: {
          password: '=',
          extras: '=?',
          data: '=?'
        },
        restrict: 'E',
        template: '{{ display.crack_times_display }}',
        link: function (scope, element, attrs) {
          scope.$watch('password', function (newVal) {
            if (angular.isString(newVal)) {

              if (scope.extras)
                scope.timeToCrack = zxcvbn(newVal, scope.extras);
              else
                scope.timeToCrack = zxcvbn(newVal);

              if (('data' in attrs) && scope.timeToCrack)
                scope.data = angular.copy(scope.timeToCrack);

              scope.display = angular.copy(scope.timeToCrack);
            }
          });
        }
      };
    });

})();


text:
/**
 * XOS integration application CLI commands.
 */
package org.onosproject.xosintegration.cli;