text:
package swarm.client.managers;

import swarm.client.app.AppContext;
import swarm.client.entities.ClientGrid;
import swarm.client.states.StateMachine_Base;
import swarm.client.structs.AccountInfo;
import swarm.client.transaction.E_TransactionAction;
import swarm.client.transaction.E_ResponseErrorControl;
import swarm.client.transaction.E_ResponseSuccessControl;
import swarm.client.transaction.I_TransactionResponseHandler;
import swarm.client.transaction.ClientTransactionManager;
import swarm.shared.entities.A_Grid;
import swarm.shared.entities.A_User;
import swarm.shared.entities.U_User;
import swarm.shared.json.A_JsonFactory;
import swarm.shared.json.I_JsonObject;
import swarm.shared.lang.Boolean;
import swarm.shared.reflection.I_Callback;
import swarm.shared.structs.CellAddressMapping;
import swarm.shared.transaction.E_RequestPath;
import swarm.shared.transaction.E_ResponseError;
import swarm.shared.transaction.TransactionRequest;
import swarm.shared.transaction.TransactionResponse;

public class GridManager implements I_TransactionResponseHandler
{
	public static interface I_Listener
	{
		void onGridUpdate();
	}

	private static final CellAddressMapping s_utilMapping1 = new CellAddressMapping();
	private static final Boolean s_utilBool = new Boolean();

	private I_Listener m_listener = null;
	private final ClientGrid m_grid;
	private final ClientTransactionManager m_txnMngr;
	private final A_JsonFactory m_jsonFactory;
	private final AppContext m_appContext;

	public GridManager(AppContext appContext, ClientGrid grid)
	{
		m_appContext = appContext;
		m_jsonFactory = m_appContext.jsonFactory;
		m_txnMngr = m_appContext.txnMngr;
		m_grid = grid;
	}

	public ClientGrid getGrid()
	{
		return m_grid;
	}

	public void start(I_Listener listener)
	{
		m_listener = listener;

		m_txnMngr.addHandler(this);
	}

	public void stop()
	{
		m_listener = null;

		m_txnMngr.removeHandler(this);
	}

	public void getGridData(E_TransactionAction action)
	{
		m_txnMngr.performAction(action, E_RequestPath.getGridData);
	}

	private boolean updateGridSizeFromJson(I_JsonObject json)
	{
		int oldWidth = m_grid.getWidth();
		int oldHeight = m_grid.getHeight();

		m_grid.readJson(json, m_jsonFactory);

		if( oldWidth != m_grid.getWidth() || oldHeight != m_grid.getHeight() )
		{
			return true;
		}

		return false;
	}

	private boolean markTakenCells(I_JsonObject json)
	{
		s_utilBool.value = false;

		I_Callback callback = new I_Callback()
		{
			@Override public void invoke(Object... args)
			{
				if( !m_grid.isTaken(s_utilMapping1.getCoordinate()) )
				{
					m_grid.claimCoordinate(s_utilMapping1.getCoordinate());
					s_utilBool.value = true;
				}
			}
		};

		U_User.readUserCells(m_jsonFactory, json, s_utilMapping1, callback);

		return s_utilBool.value;
	}

	private void onGridUpdate()
	{
		m_listener.onGridUpdate();
	}

	@Override
	public E_ResponseSuccessControl onResponseSuccess(TransactionRequest request, TransactionResponse response)
	{
		if( request.getPath() == E_RequestPath.getGridData )
		{
			if( this.updateGridSizeFromJson(response.getJsonArgs()))
			{
				onGridUpdate();
			}

			return E_ResponseSuccessControl.BREAK;
		}
		else if( request.getPath() == E_RequestPath.getUserData )
		{
			//--- DRK > A getUserData request can implicitly also create the user as well if this is the
			//---		first getUserData (i.e., on signing up), or previous ones failed.  In turn, creating
			//---		a user can implicitly expand the grid.
			boolean resized = this.updateGridSizeFromJson(response.getJsonArgs());

			//--- DRK > The getUserData request may have actually made the user, which could create a new cell,
			//--		so we just be safe here and mark all the user's cells as taken, even though they might be already.
			boolean newCellTaken = this.markTakenCells(response.getJsonArgs());

			if( resized || newCellTaken )
			{
				onGridUpdate();
			}

			return E_ResponseSuccessControl.CONTINUE;
		}

		return E_ResponseSuccessControl.CONTINUE;
	}

	@Override
	public E_ResponseErrorControl onResponseError(TransactionRequest request, TransactionResponse response)
	{
		//--- DRK > For now, bubbling all error up to StateMachine_Base so it shows error dialogs.

		if( request.getPath() == E_RequestPath.getGridData )
		{
			//return smE_TransactionErrorControl.BREAK;
		}

		return E_ResponseErrorControl.CONTINUE;
	}
}


text:
<goal-view [editable]="true"></goal-view>
<task-list [editable]="true"></task-list>
<!--<invite-list [entity]="'goal'" [entity_id]="goal_uuid"></invite-list>-->

redpajama_set_name: RedPajamaGithub


text:
package com.researchworx.cresco.controller.communication;

import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.BrokerPlugin;
import org.apache.activemq.jaas.GroupPrincipal;
import org.apache.activemq.security.AuthenticationUser;
import org.apache.activemq.security.SimpleAuthenticationBroker;

import java.security.Principal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class CrescoAuthenticationPlugin implements BrokerPlugin {
    private Map<String, String> userPasswords = new ConcurrentHashMap<String, String>();
    private Map<String, Set<Principal>> userGroups = new ConcurrentHashMap<String, Set<Principal>>();
    private static final String DEFAULT_ANONYMOUS_USER = "anonymous";
    private static final String DEFAULT_ANONYMOUS_GROUP = "anonymous";
    private String anonymousUser = DEFAULT_ANONYMOUS_USER;
    private String anonymousGroup = DEFAULT_ANONYMOUS_GROUP;
    private boolean anonymousAccessAllowed = false;

    public CrescoAuthenticationPlugin() {
    }

    public CrescoAuthenticationPlugin(List<?> users) {
        setUsers(users);
    }

    public Broker installPlugin(Broker parent) {
        SimpleAuthenticationBroker broker = new SimpleAuthenticationBroker(parent, userPasswords, userGroups);
        broker.setAnonymousAccessAllowed(anonymousAccessAllowed);
        broker.setAnonymousUser(anonymousUser);
        broker.setAnonymousGroup(anonymousGroup);
        return broker;
    }

    public Map<String, Set<Principal>> getUserGroups() {
        return userGroups;
    }

    /**
     * Sets individual users for authentication
     *
     * @org.apache.xbean.ElementType class="org.apache.activemq.security.AuthenticationUser"
     */
    public void setUsers(List<?> users) {
        userPasswords.clear();
        userGroups.clear();
        for (Iterator<?> it = users.iterator(); it.hasNext();) {
            AuthenticationUser user = (AuthenticationUser)it.next();
            userPasswords.put(user.getUsername(), user.getPassword());
            Set<Principal> groups = new HashSet<Principal>();
            StringTokenizer iter = new StringTokenizer(user.getGroups(), ",");
            while (iter.hasMoreTokens()) {
                String name = iter.nextToken().trim();
                groups.add(new GroupPrincipal(name));
            }
            userGroups.put(user.getUsername(), groups);
        }
    }

    public void addUser(String username, String password, String groups) {
        AuthenticationUser user = new AuthenticationUser(username, password, groups);
        addUser(user);
    }

    public void addUser(AuthenticationUser user) {
        userPasswords.put(user.getUsername(), user.getPassword());
        Set<Principal> groups = new HashSet<Principal>();
        StringTokenizer iter = new StringTokenizer(user.getGroups(), ",");
        while (iter.hasMoreTokens()) {
            String name = iter.nextToken().trim();
            groups.add(new GroupPrincipal(name));
        }
        userGroups.put(user.getUsername(), groups);
    }

    public void removeUser(String username) {
        userPasswords.remove(username);
        userGroups.remove(username);
    }

    public void setAnonymousAccessAllowed(boolean anonymousAccessAllowed) {
        this.anonymousAccessAllowed = anonymousAccessAllowed;
    }

    public boolean isAnonymousAccessAllowed() {
        return anonymousAccessAllowed;
    }

    public void setAnonymousUser(String anonymousUser) {
        this.anonymousUser = anonymousUser;
    }

    public String getAnonymousUser() {
        return anonymousUser;
    }

    public void setAnonymousGroup(String anonymousGroup) {
        this.anonymousGroup = anonymousGroup;
    }

    public String getAnonymousGroup() {
        return anonymousGroup;
    }

    /**
     * Sets the groups a user is in. The key is the user name and the value is a
     * Set of groups
     */
    public void setUserGroups(Map<String, Set<Principal>> userGroups) {
        this.userGroups = userGroups;
    }

    public Map<String, String> getUserPasswords() {
        return userPasswords;
    }

    /**
     * Sets the map indexed by user name with the value the password
     */
    public void setUserPasswords(Map<String, String> userPasswords) {
        this.userPasswords = userPasswords;
    }
}


text:
title: Carrying On With Python
layout: post
author: sam.rix
permalink: /carrying-on-with-python/
source-id: 1mcBiM3ViQLewE-u18ZJSAhS-j-rMDaJoNchBeRdpLCc
published: true
---

    Title
    Continuing Python on codecademy
    Date
    6.6.17

    Starting point:
    We had to carry on with are Python work

    Target for this lesson?
    To do 3% more of Python.

    Did I reach my target?
(add details to "Lesson Review")
    Yes I did.

    Lesson Review

    How did I learn? What strategies were effective?

    The strategies I used to make lots of progress on python was to carefully read the tips under the title. These were very helpful as it enabled me to understand the instructions more. They also helped me remember what I had done and how I had done it, which helped me be able to do the tasks quicker.

    What limited my learning? Which habits do I need to work on?

    I need to work on remembering key pieces of information. This will help when I do harder tasks and will know what to put and when, instead of getting stuck and then trying to remember what it was and wasting lots of time.

    What will I change for next time? How will I improve ?

    Next time, I will try to remember key pieces of information. This will help me improve when I have to do more complex tasks. This will also help me to remember what I did instead of forgetting it straight after I've done the task.


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<title>iFrame message passing test</title>
		<meta name="description" content="iFrame message passing test">

			iFrame

			Back to page 1

			Bottom

			Scroll to iFrame

			Jump to iFrame anchor
			Jump to parent anchor

			This page has an absolute position elemnt that take it out side the normal document body, which is marked with a red border on this page. This prevents the normal height calculation, which is based on the body tag from returning the correct height. To work around this you can set the heightCalculationMethod option to use one of the other page height propeties.

			Use the dropdown to change the sizing method of the page, select the different sizing options to see how the effect the page. Note that they can have different effects in different browsers, so you are normally best off selecting max if you need to change away from the default bodyOffset option.

			Height Calculation Method
			<select name="heightCalculationMethod">
				<option>bodyOffset</option>
				<option>bodyScroll</option>
				<option>documentElementOffset</option>
				<option>documentElementScroll</option>
				<option>max</option>
				<option>min</option>
				<option>grow</option>
				<option>lowestElement</option>
			</select>

			This option should be used sparingly, as the alternate methods can be less acurate at working out the correct page size, can cause screen flicker and can sometimes fail to reduce in size when the frame content changes in browsers that do not support mutationObservers (See caniuse.com for details).

		Test in page anchor

			Absolute positioned element
			Top


text:
// Modules
var util = require('util');

// Parents
var Service = require('../core').Service;

// Local
var Stream   = require('./stream.js');
var Post     = require('./post.js');

/**
 * Provides interaction with the Facebook API
 * @constructor
 * @extends Service
 */
var FacebookService = function() {
  Service.call(this, Stream, Post);
}

// Try as you might, javascript just can't hang
util.inherits(FacebookService, Service);

/**
 * Configuration
 */
FacebookService.prototype.configuration = {
  SERVICE_NAME: 'facebook',
  MAX_KEYWORDS: 0,
  MAX_ACCOUNTS: 0
};

/** EXPORT */
module.exports = FacebookService = new FacebookService();


text:
using System;
using System.Text;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;

namespace Microsoft.CodeAnalysis.Scripting.CSharp
{
    public sealed class CSharpObjectFormatter : ObjectFormatter
    {
        public static readonly CSharpObjectFormatter Instance = new CSharpObjectFormatter();

        private CSharpObjectFormatter()
        {
        }

        public override object VoidDisplayString => "<void>";
        public override string NullLiteral => ObjectDisplay.NullLiteral;
        public override string GenericParameterOpening => "<";
        public override string GenericParameterClosing => ">";

        public override string FormatLiteral(bool value)
        {
            return ObjectDisplay.FormatLiteral(value);
        }

        public override string FormatLiteral(string value, bool quote, bool useHexadecimalNumbers = false)
        {
            var options = ObjectDisplayOptions.None;
            if (quote)
            {
                options |= ObjectDisplayOptions.UseQuotes;
            }

            if (useHexadecimalNumbers)
            {
                options |= ObjectDisplayOptions.UseHexadecimalNumbers;
            }

            return ObjectDisplay.FormatLiteral(value, options);
        }

        public override string FormatLiteral(char c, bool quote, bool includeCodePoints = false, bool useHexadecimalNumbers = false)
        {
            var options = ObjectDisplayOptions.None;
            if (quote)
            {
                options |= ObjectDisplayOptions.UseQuotes;
            }

            if (includeCodePoints)
            {
                options |= ObjectDisplayOptions.IncludeCodePoints;
            }

            if (useHexadecimalNumbers)
            {
                options |= ObjectDisplayOptions.UseHexadecimalNumbers;
            }

            return ObjectDisplay.FormatLiteral(c, options);
        }

        public override string FormatLiteral(sbyte value, bool useHexadecimalNumbers = false)
        {
            return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(useHexadecimalNumbers));
        }

        public override string FormatLiteral(byte value, bool useHexadecimalNumbers = false)
        {
            return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(useHexadecimalNumbers));
        }

        public override string FormatLiteral(short value, bool useHexadecimalNumbers = false)
        {
            return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(useHexadecimalNumbers));
        }

        public override string FormatLiteral(ushort value, bool useHexadecimalNumbers = false)
        {
            return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(useHexadecimalNumbers));
        }

        public override string FormatLiteral(int value, bool useHexadecimalNumbers = false)
        {
            return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(useHexadecimalNumbers));
        }

        public override string FormatLiteral(uint value, bool useHexadecimalNumbers = false)
        {
            return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(useHexadecimalNumbers));
        }

        public override string FormatLiteral(long value, bool useHexadecimalNumbers = false)
        {
            return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(useHexadecimalNumbers));
        }

        public override string FormatLiteral(ulong value, bool useHexadecimalNumbers = false)
        {
            return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(useHexadecimalNumbers));
        }

        public override string FormatLiteral(double value)
        {
            return ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None);
        }

        public override string FormatLiteral(float value)
        {
            return ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None);
        }

        public override string FormatLiteral(decimal value)
        {
            return ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None);
        }

        public override string FormatLiteral(DateTime value)
        {
            // DateTime is not primitive in C#
            return null;
        }

        public override string GetPrimitiveTypeName(SpecialType type)
        {
            switch (type)
            {
                case SpecialType.System_Boolean: return "bool";
                case SpecialType.System_Byte: return "byte";
                case SpecialType.System_Char: return "char";
                case SpecialType.System_Decimal: return "decimal";
                case SpecialType.System_Double: return "double";
                case SpecialType.System_Int16: return "short";
                case SpecialType.System_Int32: return "int";
                case SpecialType.System_Int64: return "long";
                case SpecialType.System_SByte: return "sbyte";
                case SpecialType.System_Single: return "float";
                case SpecialType.System_String: return "string";
                case SpecialType.System_UInt16: return "ushort";
                case SpecialType.System_UInt32: return "uint";
                case SpecialType.System_UInt64: return "ulong";
                case SpecialType.System_Object: return "object";

                default:
                    return null;
            }
        }

        public override string FormatGeneratedTypeName(Type type)
        {
            string stateMachineName;
            if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(type.Name, GeneratedNameKind.StateMachineType, out stateMachineName))
            {
                return stateMachineName;
            }

            return null;
        }

        public override string FormatArrayTypeName(Type arrayType, Array arrayOpt, ObjectFormattingOptions options)
        {
            StringBuilder sb = new StringBuilder();

            // print the inner-most element type first:
            Type elementType = arrayType.GetElementType();
            while (elementType.IsArray)
            {
                elementType = elementType.GetElementType();
            }

            sb.Append(FormatTypeName(elementType, options));

            // print all components of a jagged array:
            Type type = arrayType;
            do
            {
                if (arrayOpt != null)
                {
                    sb.Append('[');

                    int rank = type.GetArrayRank();

                    bool anyNonzeroLowerBound = false;
                    for (int i = 0; i < rank; i++)
                    {
                        if (arrayOpt.GetLowerBound(i) > 0)
                        {
                            anyNonzeroLowerBound = true;
                            break;
                        }
                    }

                    for (int i = 0; i < rank; i++)
                    {
                        int lowerBound = arrayOpt.GetLowerBound(i);
                        int length = arrayOpt.GetLength(i);

                        if (i > 0)
                        {
                            sb.Append(", ");
                        }

                        if (anyNonzeroLowerBound)
                        {
                            AppendArrayBound(sb, lowerBound, options.UseHexadecimalNumbers);
                            sb.Append("..");
                            AppendArrayBound(sb, length + lowerBound, options.UseHexadecimalNumbers);
                        }
                        else
                        {
                            AppendArrayBound(sb, length, options.UseHexadecimalNumbers);
                        }
                    }

                    sb.Append(']');
                    arrayOpt = null;
                }
                else
                {
                    AppendArrayRank(sb, type);
                }

                type = type.GetElementType();
            }
            while (type.IsArray);

            return sb.ToString();
        }

        private void AppendArrayBound(StringBuilder sb, long bound, bool useHexadecimalNumbers)
        {
            if (bound <= int.MaxValue)
            {
                sb.Append(FormatLiteral((int)bound, useHexadecimalNumbers));
            }
            else
            {
                sb.Append(FormatLiteral(bound, useHexadecimalNumbers));
            }
        }

        private static void AppendArrayRank(StringBuilder sb, Type arrayType)
        {
            sb.Append('[');
            int rank = arrayType.GetArrayRank();
            if (rank > 1)
            {
                sb.Append(',', rank - 1);
            }
            sb.Append(']');
        }

        public override string FormatMemberName(System.Reflection.MemberInfo member)
        {
            return member.Name;
        }

        public override bool IsHiddenMember(System.Reflection.MemberInfo member)
        {
            // Generated fields, e.g. "<property_name>k__BackingField"
            return GeneratedNames.IsGeneratedMemberName(member.Name);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="emailConfirm_subject">%s lichess.org hisobingizni tasdiqlang</string>
  <string name="emailConfirm_click" comment="emailConfirm_click

Part of the confirmation email upon registering for a Lichess account.

The unique reset link is presented just after this string.">Lichess hisobingizni yoqish uchun quyidagi linkni bosing:</string>
  <string name="emailConfirm_ignore">Agar siz \"Lichess\" da ro\'yxatdan o\'tmagan bo\'lsangiz, ushbu xabarga beparvo bo\'lishingiz mumkin.</string>
  <string name="passwordReset_subject">%s lichess.org parolingizni qayta tiklang</string>
  <string name="passwordReset_intro">Biz sizni hisobingizni parolini tashlab yuborishga so\'rov oldik.</string>
  <string name="passwordReset_clickOrIgnore">Agar siz ushbu so\'rovni yaratgan bo\'lsangiz, quyidagi linkni bosing. Agar siz bo\'lmasangiz, ushbu emailga parvo qilmasangiz bo\'ladi.</string>
  <string name="emailChange_subject">%s, elektron manzilingizni tasdiqlang</string>
  <string name="emailChange_intro">Siz emailingizni almashtirishni so\'radingiz.</string>
  <string name="emailChange_click">Ushbu xatga huquqingiz borligini tasdiqlash uchun quyidagi linkni bosing:</string>
  <string name="welcome_subject">%s lichess.org ga xush kelibsiz</string>
  <string name="welcome_text">Https://lichess.org da sizni hisobingiz muvaffaqiyatli yaratildi.

%1$s:sizni profil sahifangiz. %2$s da uni shaxsiylashtirishingiz mumkin.

 Omad yor bo\'lsin va doim sizni sipohlaringiz raqibingiz qiroli tomon yo\'l topa olsin:)!</string>
  <string name="logInToLichess">%s, lichess.org ga kiring</string>
  <string name="common_orPaste">(Bosish ishlamayabdimi? Buni browzeringizga qo\'yishga urinib ko\'ring!)</string>
  <string name="common_note">%s ni ishlatishingiz bilan bog\'liq bo\'lgan xizmatchi email manzil.</string>
  <string name="common_contact">Biz bilan bog\'lanish uchun %s dan foydalaning.</string>
</resources>


text:
<?php

namespace spec\Sylius\Component\Locale\Provider;

use PhpSpec\ObjectBehavior;
use Sylius\Component\Locale\Model\LocaleInterface;
use Sylius\Component\Locale\Provider\LocaleProvider;
use Sylius\Component\Locale\Provider\LocaleProviderInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;

/**
 * @author Kamil Kokot <kamil.kokot@lakion.com>
 */
final class LocaleProviderSpec extends ObjectBehavior
{
    function let(RepositoryInterface $localeRepository)
    {
        $this->beConstructedWith($localeRepository, 'pl_PL');
    }

    function it_is_initializable()
    {
        $this->shouldHaveType(LocaleProvider::class);
    }

    function it_is_a_locale_provider_interface()
    {
        $this->shouldImplement(LocaleProviderInterface::class);
    }

    function it_returns_all_enabled_locales(RepositoryInterface $localeRepository, LocaleInterface $locale)
    {
        $localeRepository->findAll()->willReturn([$locale]);
        $locale->getCode()->willReturn('en_US');

        $this->getAvailableLocalesCodes()->shouldReturn(['en_US']);
    }

    function it_returns_the_default_locale()
    {
        $this->getDefaultLocaleCode()->shouldReturn('pl_PL');
    }
}


text:
package app.outlay.view.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import app.outlay.core.utils.DateUtils;
import app.outlay.domain.model.Category;
import app.outlay.domain.model.Expense;
import app.outlay.domain.model.Report;
import app.outlay.mvp.presenter.ExpensesListPresenter;
import app.outlay.mvp.view.ExpensesView;
import app.outlay.utils.IconUtils;
import app.outlay.utils.ResourceUtils;
import app.outlay.view.Navigator;
import app.outlay.view.adapter.ExpenseAdapter;
import app.outlay.view.adapter.ListExpensesAdapter;
import app.outlay.view.fragment.base.BaseMvpFragment;
import butterknife.Bind;
import com.github.johnkil.print.PrintView;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Bogdan Melnychuk on 1/20/16.
 */
public class ExpensesListFragment extends BaseMvpFragment<ExpensesView, ExpensesListPresenter> implements ExpensesView {
    public static final String ARG_CATEGORY_ID = "_argCategoryId";
    public static final String ARG_DATE_FROM = "_argDateFrom";
    public static final String ARG_DATE_TO = "_argDateTo";

    private static final int MODE_LIST = 0;
    private static final int MODE_GRID = 1;

    @Bind(app.outlay.R.id.recyclerView)
    RecyclerView recyclerView;

    @Bind(app.outlay.R.id.toolbar)
    Toolbar toolbar;

    @Bind(app.outlay.R.id.fab)
    FloatingActionButton fab;

    @Bind(app.outlay.R.id.noResults)
    View noResults;

    @Bind(app.outlay.R.id.filterCategoryIcon)
    PrintView filterCategoryIcon;

    @Bind(app.outlay.R.id.filterCategoryName)
    TextView filterCategoryName;

    @Bind(app.outlay.R.id.filterDateLabel)
    TextView filterDateLabel;

    private ExpenseAdapter adapter;
    private Date dateFrom;
    private Date dateTo;
    private String categoryId;

    private int mode = MODE_LIST;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getApp().getUserComponent().inject(this);

        long dateFromMillis = getArguments().getLong(ARG_DATE_FROM);
        long dateToMillis = getArguments().getLong(ARG_DATE_TO);

        dateFrom = new Date(dateFromMillis);
        dateTo = new Date(dateToMillis);
        if (getArguments().containsKey(ARG_CATEGORY_ID)) {
            categoryId = getArguments().getString(ARG_CATEGORY_ID);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(app.outlay.R.layout.fragment_expenses_list, null, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        setToolbar(toolbar);
        setDisplayHomeAsUpEnabled(true);
        setTitle(getString(app.outlay.R.string.caption_expenses));

        filterDateLabel.setText(getDateLabel());
        fab.setImageDrawable(ResourceUtils.getMaterialToolbarIcon(getActivity(), app.outlay.R.string.ic_material_add));
        fab.setOnClickListener(v -> Navigator.goToExpenseDetails(getActivity(), null));
        recyclerView.setHasFixedSize(true);

//            adapter = new GridExpensesAdapter();
//            StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
//            recyclerView.setLayoutManager(staggeredGridLayoutManager);

        adapter = new ListExpensesAdapter();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(adapter);
        adapter.setOnExpenseClickListener(expense -> Navigator.goToExpenseDetails(getActivity(), expense));
    }

    @Override
    public void onResume() {
        super.onResume();
        getPresenter().findExpenses(dateFrom, dateTo, categoryId);
    }

    private void displayExpenses(List<Expense> expenses) {
        if (expenses.isEmpty()) {
            noResults.setVisibility(View.VISIBLE);
        } else {
            noResults.setVisibility(View.GONE);
            adapter.setItems(expenses);
        }
    }

    private void displayCategory(Category category) {
        if (category != null) {
            IconUtils.loadCategoryIcon(category, filterCategoryIcon);
            filterCategoryName.setText(category.getTitle());
        } else {
            filterCategoryName.setVisibility(View.GONE);
            filterCategoryIcon.setVisibility(View.GONE);
        }
    }

    @Override
    public void showReport(Report report) {
        displayExpenses(report.getExpenses());
        Map<Category, Report> grouped = report.groupByCategory();
        if (grouped.size() == 1) {
            displayCategory(report.getExpenses().get(0).getCategory());
        }
    }

    private String getDateLabel() {
        String dateFromStr = DateUtils.toShortString(dateFrom);
        String dateToStr = DateUtils.toShortString(dateTo);
        String result = dateFromStr;
        if (!dateFromStr.equals(dateToStr)) {
            result += " - " + dateToStr;
        }
        return result;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <parent>
        <groupId>org.springframework.ldap</groupId>
        <artifactId>spring-ldap-parent</artifactId>
        <version>1.3.2.CI-SNAPSHOT</version>
		<relativePath>../parent/pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>spring-ldap-integration-tests-parent</artifactId>
    <packaging>pom</packaging>
    <name>Spring LDAP Integration Tests</name>
    <modules>
        <module>integration-tests</module>
    </modules>
	<profiles>
		<profile>
			<id>openldap</id>
			<modules>
				<module>integration-tests-openldap</module>
			</modules>
		</profile>
		<profile>
			<id>sunone</id>
			<modules>
				<module>integration-tests-sunone</module>
			</modules>
		</profile>
	</profiles>
    <repositories>
        <repository>
            <id>spring-milestone</id>
            <name>Spring Milestone Repository</name>
            <url>http://maven.springframework.org/milestone</url>
        </repository>
    </repositories>
    <build>
        <plugins>
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>maven-jetty-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <warName>${project.artifactId}</warName>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <!-- Logging dependencies -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
</project>


text:
import tensorflow as tf

from inferbeddings.nli.disan.general import flatten, reconstruct

def dynamic_rnn(cell, inputs, sequence_length=None, initial_state=None,
                dtype=None, parallel_iterations=None, swap_memory=False,
                time_major=False, scope=None):
    assert not time_major  # TODO : to be implemented later!
    flat_inputs = flatten(inputs, 2)  # [-1, J, d]
    flat_len = None if sequence_length is None else tf.cast(flatten(sequence_length, 0), 'int64')

    flat_outputs, final_state = tf.nn.dynamic_rnn(cell, flat_inputs, sequence_length=flat_len,
                                             initial_state=initial_state, dtype=dtype,
                                             parallel_iterations=parallel_iterations, swap_memory=swap_memory,
                                             time_major=time_major, scope=scope)

    outputs = reconstruct(flat_outputs, inputs, 2)
    return outputs, final_state

def bw_dynamic_rnn(cell, inputs, sequence_length=None, initial_state=None,
                   dtype=None, parallel_iterations=None, swap_memory=False,
                   time_major=False, scope=None):
    assert not time_major  # TODO : to be implemented later!

    flat_inputs = flatten(inputs, 2)  # [-1, J, d]
    flat_len = None if sequence_length is None else tf.cast(flatten(sequence_length, 0), 'int64')

    flat_inputs = tf.reverse(flat_inputs, 1) if sequence_length is None \
        else tf.reverse_sequence(flat_inputs, sequence_length, 1)
    flat_outputs, final_state = tf.nn.dynamic_rnn(cell, flat_inputs, sequence_length=flat_len,
                                             initial_state=initial_state, dtype=dtype,
                                             parallel_iterations=parallel_iterations, swap_memory=swap_memory,
                                             time_major=time_major, scope=scope)
    flat_outputs = tf.reverse(flat_outputs, 1) if sequence_length is None \
        else tf.reverse_sequence(flat_outputs, sequence_length, 1)

    outputs = reconstruct(flat_outputs, inputs, 2)
    return outputs, final_state

def bidirectional_dynamic_rnn(cell_fw, cell_bw, inputs, sequence_length=None,
                              initial_state_fw=None, initial_state_bw=None,
                              dtype=None, parallel_iterations=None,
                              swap_memory=False, time_major=False, scope=None):
    assert not time_major

    flat_inputs = flatten(inputs, 2)  # [-1, J, d]
    flat_len = None if sequence_length is None else tf.cast(flatten(sequence_length, 0), 'int64')

    (flat_fw_outputs, flat_bw_outputs), final_state = \
        tf.nn.bidirectional_dynamic_rnn(cell_fw, cell_bw, flat_inputs, sequence_length=flat_len,
                                   initial_state_fw=initial_state_fw, initial_state_bw=initial_state_bw,
                                   dtype=dtype, parallel_iterations=parallel_iterations, swap_memory=swap_memory,
                                   time_major=time_major, scope=scope)

    fw_outputs = reconstruct(flat_fw_outputs, inputs, 2)
    bw_outputs = reconstruct(flat_bw_outputs, inputs, 2)
    # FIXME : final state is not reshaped!
    return (fw_outputs, bw_outputs), final_state


text:
package org.apache.hadoop.hbase.hbtop.screen.top;

import java.util.Objects;
import org.apache.hadoop.hbase.hbtop.screen.ScreenView;
import org.apache.yetus.audience.InterfaceAudience;

/**
 * The presentation logic for the message mode.
 *
 * Exit after 2 seconds or if any key is pressed.
 */
@InterfaceAudience.Private
public class MessageModeScreenPresenter {

  private final MessageModeScreenView messageModeScreenView;
  private final String message;
  private final ScreenView nextScreenView;

  public MessageModeScreenPresenter(MessageModeScreenView messageModeScreenView, String message,
    ScreenView nextScreenView) {
    this.messageModeScreenView = Objects.requireNonNull(messageModeScreenView);
    this.message = Objects.requireNonNull(message);
    this.nextScreenView = Objects.requireNonNull(nextScreenView);
  }

  public void init() {
    messageModeScreenView.showMessage(message);
    messageModeScreenView.refreshTerminal();
  }

  public ScreenView returnToNextScreen() {
    return nextScreenView;
  }
}


text:
{{title}}

  Dynamic Person First Name
  <input type="text" [(ngModel)]="person.firstName">

New Person

  New First Name
  <input type="text" [(ngModel)]="newFirstName">

  New Last Name
  <input type="text" [(ngModel)]="newLastName">

  <button (click)="setNewPerson()">Create New Person</button>

Person Details

<person-details [person]="person"></person-details>

OnPush Person Details

<person-details-immutable [person]="person"></person-details-immutable>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Couchbase.Core;
using Couchbase.Linq.UnitTests.Documents;
using Moq;
using NUnit.Framework;

namespace Couchbase.Linq.UnitTests.QueryGeneration
{
    [TestFixture]
    class UnaryExpressionTests : N1QLTestBase
    {

        #region Logical Operators

        [Test]
        public void Test_BooleanNot()
        {
            var mockBucket = new Mock<IBucket>();
            mockBucket.SetupGet(e => e.Name).Returns("default");

            var query =
                QueryFactory.Queryable<Contact>(mockBucket.Object)
                    // ReSharper disable once NegativeEqualityExpression
                    .Where(e => !(e.Age == 10))
                    .Select(e => new { age = e.Age });

            const string expected =
                "SELECT `Extent1`.`age` as `age` FROM `default` as `Extent1` WHERE NOT (`Extent1`.`age` = 10)";

            var n1QlQuery = CreateN1QlQuery(mockBucket.Object, query.Expression);

            Assert.AreEqual(expected, n1QlQuery);
        }

        #endregion

        #region Arithmetic Operators

        [Test]
        public void Test_Negation()
        {
            var mockBucket = new Mock<IBucket>();
            mockBucket.SetupGet(e => e.Name).Returns("default");

            var query =
                QueryFactory.Queryable<Contact>(mockBucket.Object)
                    .Select(e => new {age = -e.Age});

            const string expected =
                "SELECT -`Extent1`.`age` as `age` FROM `default` as `Extent1`";

            var n1QlQuery = CreateN1QlQuery(mockBucket.Object, query.Expression);

            Assert.AreEqual(expected, n1QlQuery);
        }

        #endregion

    }
}


text:
title: NuGet Warning NU1603
description: NU1603 warning code
author: zhili1208
ms.author: lzhi
ms.date: 06/25/2018
ms.topic: reference
ms.reviewer: anangaur
f1_keywords:
  - "NU1603"
---

# NuGet Warning NU1603

'PackageA' 4.0.0 depends on 'PackageB' (>= 4.0.0) but 4.0.0 was not found. An approximate best match of 5.0.0 was resolved.

### Issue

A package dependency specified a version that could not be found. Typically, the package sources do not contain the expected lower bound version. A higher version was used instead, which differs from what the package was authored against.

This means that restore did not find the *best match*. Each restore will float downwards trying to find a lower version that can be used. This means that restore goes online to check all sources each time instead of using the packages that already exist in the user package folder.

### Solution
If the package expected has not been released then this may be a package authoring error. Contact the package author to resolve the issue. If the package has been released, then check that it's available on the package sources you're using. If using a private source, you may need to update the package on that feed.


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using System.Reflection;

namespace Microsoft.CSharp.RuntimeBinder
{
    internal static class BinderHelper
    {
        private static MethodInfo s_DoubleIsNaN;
        private static MethodInfo s_SingleIsNaN;

        internal static DynamicMetaObject Bind(
                DynamicMetaObjectBinder action,
                RuntimeBinder binder,
                DynamicMetaObject[] args,
                IEnumerable<CSharpArgumentInfo> arginfos,
                DynamicMetaObject onBindingError)
        {
            Expression[] parameters = new Expression[args.Length];
            BindingRestrictions restrictions = BindingRestrictions.Empty;
            ICSharpInvokeOrInvokeMemberBinder callPayload = action as ICSharpInvokeOrInvokeMemberBinder;
            ParameterExpression tempForIncrement = null;
            IEnumerator<CSharpArgumentInfo> arginfosEnum = (arginfos ?? Array.Empty<CSharpArgumentInfo>()).GetEnumerator();

            for (int index = 0; index < args.Length; ++index)
            {
                DynamicMetaObject o = args[index];
                // Our contract with the DLR is such that we will not enter a bind unless we have
                // values for the meta-objects involved.

                Debug.Assert(o.HasValue);

                CSharpArgumentInfo info = arginfosEnum.MoveNext() ? arginfosEnum.Current : null;

                if (index == 0 && IsIncrementOrDecrementActionOnLocal(action))
                {
                    // We have an inc or a dec operation. Insert the temp local instead.
                    //
                    // We need to do this because for value types, the object will come
                    // in boxed, and we'd need to unbox it to get the original type in order
                    // to increment. The only way to do that is to create a new temporary.
                    object value = o.Value;
                    tempForIncrement = Expression.Variable(value != null ? value.GetType() : typeof(object), "t0");
                    parameters[0] = tempForIncrement;
                }
                else
                {
                    parameters[index] = o.Expression;
                }

                BindingRestrictions r = DeduceArgumentRestriction(index, callPayload, o, info);
                restrictions = restrictions.Merge(r);

                // Here we check the argument info. If the argument info shows that the current argument
                // is a literal constant, then we also add an instance restriction on the value of
                // the constant.
                if (info != null && info.LiteralConstant)
                {
                    if (o.Value is double && double.IsNaN((double)o.Value))
                    {
                        MethodInfo isNaN = s_DoubleIsNaN ?? (s_DoubleIsNaN = typeof(double).GetMethod("IsNaN"));
                        Expression e = Expression.Call(null, isNaN, o.Expression);
                        restrictions = restrictions.Merge(BindingRestrictions.GetExpressionRestriction(e));
                    }
                    else if (o.Value is float && float.IsNaN((float)o.Value))
                    {
                        MethodInfo isNaN = s_SingleIsNaN ?? (s_SingleIsNaN = typeof(float).GetMethod("IsNaN"));
                        Expression e = Expression.Call(null, isNaN, o.Expression);
                        restrictions = restrictions.Merge(BindingRestrictions.GetExpressionRestriction(e));
                    }
                    else
                    {
                        Expression e = Expression.Equal(o.Expression, Expression.Constant(o.Value, o.Expression.Type));
                        r = BindingRestrictions.GetExpressionRestriction(e);
                        restrictions = restrictions.Merge(r);
                    }
                }
            }

            // Get the bound expression.
            try
            {
                DynamicMetaObject deferredBinding;
                Expression expression = binder.Bind(action, parameters, args, out deferredBinding);

                if (deferredBinding != null)
                {
                    expression = ConvertResult(deferredBinding.Expression, action);
                    restrictions = deferredBinding.Restrictions.Merge(restrictions);
                    return new DynamicMetaObject(expression, restrictions);
                }

                if (tempForIncrement != null)
                {
                    // If we have a ++ or -- payload, we need to do some temp rewriting.
                    // We rewrite to the following:
                    //
                    // temp = (type)o;
                    // temp++;
                    // o = temp;
                    // return o;

                    DynamicMetaObject arg0 = args[0];

                    expression = Expression.Block(
                        new[] {tempForIncrement},
                        Expression.Assign(tempForIncrement, Expression.Convert(arg0.Expression, arg0.Value.GetType())),
                        expression,
                        Expression.Assign(arg0.Expression, Expression.Convert(tempForIncrement, arg0.Expression.Type)));
                }

                expression = ConvertResult(expression, action);

                return new DynamicMetaObject(expression, restrictions);
            }
            catch (RuntimeBinderException e)
            {
                if (onBindingError != null)
                {
                    return onBindingError;
                }

                return new DynamicMetaObject(
                    Expression.Throw(
                        Expression.New(
                            typeof(RuntimeBinderException).GetConstructor(new Type[] { typeof(string) }),
                            Expression.Constant(e.Message)
                        ),
                        GetTypeForErrorMetaObject(action, args)
                    ),
                    restrictions
                );
            }
        }

        public static void ValidateBindArgument(DynamicMetaObject argument, string paramName)
        {
            if (argument == null)
            {
                throw Error.ArgumentNull(paramName);
            }

            if (!argument.HasValue)
            {
                throw Error.DynamicArgumentNeedsValue(paramName);
            }
        }

        public static void ValidateBindArgument(DynamicMetaObject[] arguments, string paramName)
        {
            if (arguments != null) // null is treated as empty, so not invalid
            {
                for (int i = 0; i != arguments.Length; ++i)
                {
                    ValidateBindArgument(arguments[i], $"{paramName}[{i}]");
                }
            }
        }

        /////////////////////////////////////////////////////////////////////////////////

        private static bool IsTypeOfStaticCall(
            int parameterIndex,
            ICSharpInvokeOrInvokeMemberBinder callPayload)
        {
            return parameterIndex == 0 && callPayload != null && callPayload.StaticCall;
        }

        /////////////////////////////////////////////////////////////////////////////////

        private static bool IsComObject(object obj)
        {
            return obj != null && Marshal.IsComObject(obj);
        }

#if ENABLECOMBINDER
        /////////////////////////////////////////////////////////////////////////////////

        // Try to determine if this object represents a WindowsRuntime object - i.e. it either
        // is coming from a WinMD file or is derived from a class coming from a WinMD.
        // The logic here matches the CLR's logic of finding a WinRT object.
        internal static bool IsWindowsRuntimeObject(DynamicMetaObject obj)
        {
            Type curType = obj?.RuntimeType;
            while (curType != null)
            {
                TypeAttributes attributes = curType.Attributes;
                if ((attributes & TypeAttributes.WindowsRuntime) == TypeAttributes.WindowsRuntime)
                {
                    // Found a WinRT COM object
                    return true;
                }
                if ((attributes & TypeAttributes.Import) == TypeAttributes.Import)
                {
                    // Found a class that is actually imported from COM but not WinRT
                    // this is definitely a non-WinRT COM object
                    return false;
                }
                curType = curType.BaseType;
            }

            return false;
        }
#endif
        /////////////////////////////////////////////////////////////////////////////////

        private static bool IsTransparentProxy(object obj)
        {
            // In the full framework, this checks:
            //     return obj != null && RemotingServices.IsTransparentProxy(obj);
            // but transparent proxies don't exist in .NET Core.
            return false;
        }

        /////////////////////////////////////////////////////////////////////////////////

        private static bool IsDynamicallyTypedRuntimeProxy(DynamicMetaObject argument, CSharpArgumentInfo info)
        {
            // This detects situations where, although the argument has a value with
            // a given type, that type is insufficient to determine, statically, the
            // set of reference conversions that are going to exist at bind time for
            // different values. For instance, one __ComObject may allow a conversion
            // to IFoo while another does not.

            bool isDynamicObject =
                info != null &&
                !info.UseCompileTimeType &&
                (IsComObject(argument.Value) || IsTransparentProxy(argument.Value));

            return isDynamicObject;
        }

        /////////////////////////////////////////////////////////////////////////////////

        private static BindingRestrictions DeduceArgumentRestriction(
            int parameterIndex,
            ICSharpInvokeOrInvokeMemberBinder callPayload,
            DynamicMetaObject argument,
            CSharpArgumentInfo info)
        {
            // Here we deduce what predicates the DLR can apply to future calls in order to
            // determine whether to use the previously-computed-and-cached delegate, or
            // whether we need to bind the site again. Ideally we would like the
            // predicate to be as broad as is possible; if we can re-use analysis based
            // solely on the type of the argument, that is preferable to re-using analysis
            // based on object identity with a previously-analyzed argument.

            // The times when we need to restrict re-use to a particular instance, rather
            // than its type, are:
            //
            // * if the argument is a null reference then we have no type information.
            //
            // * if we are making a static call then the first argument is
            //   going to be a Type object. In this scenario we should always check
            //   for a specific Type object rather than restricting to the Type type.
            //
            // * if the argument was dynamic at compile time and it is a dynamic proxy
            //   object that the runtime manages, such as COM RCWs and transparent
            //   proxies.
            //
            // ** there is also a case for constant values (such as literals) to use
            //    something like value restrictions, and that is accomplished in Bind().

            bool useValueRestriction =
                argument.Value == null ||
                IsTypeOfStaticCall(parameterIndex, callPayload) ||
                IsDynamicallyTypedRuntimeProxy(argument, info);

            return useValueRestriction ?
                    BindingRestrictions.GetInstanceRestriction(argument.Expression, argument.Value) :
                    BindingRestrictions.GetTypeRestriction(argument.Expression, argument.RuntimeType);
        }

        /////////////////////////////////////////////////////////////////////////////////

        private static Expression ConvertResult(Expression binding, DynamicMetaObjectBinder action)
        {
            // Need to handle the following cases:
            //   (1) Call to a constructor: no conversions.
            //   (2) Call to a void-returning method: return null iff result is discarded.
            //   (3) Call to a value-type returning method: box to object.
            //
            // In all other cases, binding.Type should be equivalent or
            // reference assignable to resultType.

            var invokeConstructor = action as CSharpInvokeConstructorBinder;
            if (invokeConstructor != null)
            {
                // No conversions needed, the call site has the correct type.
                return binding;
            }

            if (binding.Type == typeof(void))
            {
                var invoke = action as ICSharpInvokeOrInvokeMemberBinder;
                if (invoke != null && invoke.ResultDiscarded)
                {
                    Debug.Assert(action.ReturnType == typeof(object));
                    return Expression.Block(binding, Expression.Default(action.ReturnType));
                }
                else
                {
                    throw Error.BindToVoidMethodButExpectResult();
                }
            }

            if (binding.Type.IsValueType && !action.ReturnType.IsValueType)
            {
                Debug.Assert(action.ReturnType == typeof(object));
                return Expression.Convert(binding, action.ReturnType);
            }

            return binding;
        }

        /////////////////////////////////////////////////////////////////////////////////

        private static Type GetTypeForErrorMetaObject(DynamicMetaObjectBinder action, DynamicMetaObject[] args)
        {
            // This is similar to ConvertResult but has fewer things to worry about.

            if (action is CSharpInvokeConstructorBinder)
            {
                Debug.Assert(args != null);
                Debug.Assert(args.Length != 0);
                Debug.Assert(args[0].Value is Type);
                return args[0].Value as Type;
            }

            return action.ReturnType;
        }

        /////////////////////////////////////////////////////////////////////////////////

        private static bool IsIncrementOrDecrementActionOnLocal(DynamicMetaObjectBinder action)
        {
            CSharpUnaryOperationBinder operatorPayload = action as CSharpUnaryOperationBinder;

            return operatorPayload != null &&
                (operatorPayload.Operation == ExpressionType.Increment || operatorPayload.Operation == ExpressionType.Decrement);
        }

        /////////////////////////////////////////////////////////////////////////////////

        internal static T[] Cons<T>(T sourceHead, T[] sourceTail)
        {
            if (sourceTail?.Length != 0)
            {
                T[] array = new T[sourceTail.Length + 1];
                array[0] = sourceHead;
                sourceTail.CopyTo(array, 1);
                return array;
            }

            return new[] { sourceHead };
        }

        internal static T[] Cons<T>(T sourceHead, T[] sourceMiddle, T sourceLast)
        {
            if (sourceMiddle?.Length != 0)
            {
                T[] array = new T[sourceMiddle.Length + 2];
                array[0] = sourceHead;
                array[array.Length - 1] = sourceLast;
                sourceMiddle.CopyTo(array, 1);
                return array;
            }

            return new[] {sourceHead, sourceLast};
        }

        /////////////////////////////////////////////////////////////////////////////////

        internal static T[] ToArray<T>(IEnumerable<T> source) => source == null ? Array.Empty<T>() : source.ToArray();

        /////////////////////////////////////////////////////////////////////////////////

        internal static CallInfo CreateCallInfo(ref IEnumerable<CSharpArgumentInfo> argInfos, int discard)
        {
            // This function converts the C# Binder's notion of argument information to the
            // DLR's notion. The DLR counts arguments differently than C#. Here are some
            // examples:

            // Expression      Binder                     C# ArgInfos   DLR CallInfo
            //
            // d.M(1, 2, 3);   CSharpInvokeMemberBinder   4             3
            // d(1, 2, 3);     CSharpInvokeBinder         4             3
            // d[1, 2] = 3;    CSharpSetIndexBinder       4             2
            // d[1, 2, 3]      CSharpGetIndexBinder       4             3
            //
            // The "discard" parameter tells this function how many of the C# arg infos it
            // should not count as DLR arguments.

            int argCount = 0;
            List<string> argNames = new List<string>();
            CSharpArgumentInfo[] infoArray = ToArray(argInfos);
            argInfos = infoArray; // Write back the array to allow single enumeration.
            foreach (CSharpArgumentInfo info in infoArray)
            {
                if (info.NamedArgument)
                {
                    argNames.Add(info.Name);
                }
                ++argCount;
            }

            Debug.Assert(discard <= argCount);
            Debug.Assert(argNames.Count <= argCount - discard);

            return new CallInfo(argCount - discard, argNames);
        }

        internal static string GetCLROperatorName(this ExpressionType p)
        {
            switch (p)
            {
                default:
                    return null;

                // Binary Operators
                case ExpressionType.Add:
                    return SpecialNames.CLR_Add;
                case ExpressionType.Subtract:
                    return SpecialNames.CLR_Subtract;
                case ExpressionType.Multiply:
                    return SpecialNames.CLR_Multiply;
                case ExpressionType.Divide:
                    return SpecialNames.CLR_Division;
                case ExpressionType.Modulo:
                    return SpecialNames.CLR_Modulus;
                case ExpressionType.LeftShift:
                    return SpecialNames.CLR_LShift;
                case ExpressionType.RightShift:
                    return SpecialNames.CLR_RShift;
                case ExpressionType.LessThan:
                    return SpecialNames.CLR_LT;
                case ExpressionType.GreaterThan:
                    return SpecialNames.CLR_GT;
                case ExpressionType.LessThanOrEqual:
                    return SpecialNames.CLR_LTE;
                case ExpressionType.GreaterThanOrEqual:
                    return SpecialNames.CLR_GTE;
                case ExpressionType.Equal:
                    return SpecialNames.CLR_Equality;
                case ExpressionType.NotEqual:
                    return SpecialNames.CLR_Inequality;
                case ExpressionType.And:
                    return SpecialNames.CLR_BitwiseAnd;
                case ExpressionType.ExclusiveOr:
                    return SpecialNames.CLR_ExclusiveOr;
                case ExpressionType.Or:
                    return SpecialNames.CLR_BitwiseOr;

                // "op_LogicalNot";
                case ExpressionType.AddAssign:
                    return SpecialNames.CLR_InPlaceAdd;
                case ExpressionType.SubtractAssign:
                    return SpecialNames.CLR_InPlaceSubtract;
                case ExpressionType.MultiplyAssign:
                    return SpecialNames.CLR_InPlaceMultiply;
                case ExpressionType.DivideAssign:
                    return SpecialNames.CLR_InPlaceDivide;
                case ExpressionType.ModuloAssign:
                    return SpecialNames.CLR_InPlaceModulus;
                case ExpressionType.AndAssign:
                    return SpecialNames.CLR_InPlaceBitwiseAnd;
                case ExpressionType.ExclusiveOrAssign:
                    return SpecialNames.CLR_InPlaceExclusiveOr;
                case ExpressionType.OrAssign:
                    return SpecialNames.CLR_InPlaceBitwiseOr;
                case ExpressionType.LeftShiftAssign:
                    return SpecialNames.CLR_InPlaceLShift;
                case ExpressionType.RightShiftAssign:
                    return SpecialNames.CLR_InPlaceRShift;

                // Unary Operators
                case ExpressionType.Negate:
                    return SpecialNames.CLR_UnaryNegation;
                case ExpressionType.UnaryPlus:
                    return SpecialNames.CLR_UnaryPlus;
                case ExpressionType.Not:
                    return SpecialNames.CLR_LogicalNot;
                case ExpressionType.OnesComplement:
                    return SpecialNames.CLR_OnesComplement;
                case ExpressionType.IsTrue:
                    return SpecialNames.CLR_True;
                case ExpressionType.IsFalse:
                    return SpecialNames.CLR_False;

                case ExpressionType.Increment:
                    return SpecialNames.CLR_PreIncrement;
                case ExpressionType.Decrement:
                    return SpecialNames.CLR_PreDecrement;
            }
        }
    }
}


text:
create temp table copytest3 (
	c1 int,
	"col with , comma" text,
	"col with "" quote"  int) distributed by (c1);

copy copytest3 from stdin csv header;
this is just a line full of junk that would error out if parsed
1,a,1
2,b,2
\.

copy copytest3 to stdout csv header;
-- copy with error table
CREATE TABLE number (a INT) DISTRIBUTED BY (a);

COPY number FROM STDIN LOG ERRORS INTO err_copy SEGMENT REJECT LIMIT 10 ROWS;
these are invalid line should be insert into error table.
a
b
c
d
e
f
g
h
\.

select relname,filename,linenum,bytenum,errmsg,rawdata,rawbytes from err_copy order by linenum;
select * from number; --should be empty
\d err_copy

DROP TABLE err_copy;

COPY number FROM STDIN LOG ERRORS INTO err_copy SEGMENT REJECT LIMIT 10 ROWS;
these are invalid line should be insert into error table.
a
1
b
2
c
3
d
4
e
5
f
6
g
7
h
\.

select relname,filename,linenum,bytenum,errmsg,rawdata,rawbytes from err_copy order by linenum;
select count(*) from number; --should be 7
DROP TABLE err_copy;

TRUNCATE number;

COPY number FROM STDIN LOG ERRORS INTO err_copy SEGMENT REJECT LIMIT 10 ROWS;
these are invalid line should be insert into error table.
a
1
b
2
c
3
d
4
e
5
f
6
g
7
h
i
\.

select relname,filename,linenum,bytenum,errmsg,rawdata,rawbytes from err_copy order by linenum; -- should not exist
select count(*) from number; --should be empty

TRUNCATE number;
CREATE TABLE err_copy (cmdtime timestamp with time zone, relname text, filename text, linenum integer, bytenum integer, errmsg text, rawdata text, rawbytes bytea) distributed randomly;

COPY number FROM STDIN LOG ERRORS INTO err_copy SEGMENT REJECT LIMIT 10 ROWS;
these are invalid line should be insert into error table.
a
1
b
2
c
3
d
4
e
5
f
6
g
7
h
\.

select relname,filename,linenum,bytenum,errmsg,rawdata,rawbytes from err_copy order by linenum;
select count(*) from number; --should be 7
DROP TABLE err_copy;

-- invalid error table schema
TRUNCATE number;
create table invalid_error_table1 (a int) distributed randomly;
create table invalid_error_table3 (cmdtime timestamp with time zone, relname text, filename text, linenum integer, bytenum integer, errmsg text, rawdata text, rawbytes bytea)
		distributed by (cmdtime);

COPY number FROM STDIN LOG ERRORS INTO invalid_error_table1 SEGMENT REJECT LIMIT 10 ROWS; -- should fail
these are invalid line should be insert into error table.
1
\.

;

COPY number FROM STDIN LOG ERRORS INTO invalid_error_table3 SEGMENT REJECT LIMIT 10 ROWS; -- should fail
these are invalid line should be insert into error table.
1
\.

;

DROP TABLE invalid_error_table1;
DROP TABLE invalid_error_table3;

DROP TABLE number;


text:
package de.oliver_heger.linedj.pleditor.ui.playlist.export

import java.nio.file.Path

import akka.NotUsed
import akka.actor._
import akka.stream.scaladsl.Source
import akka.util.ByteString
import de.oliver_heger.linedj.io.stream.ActorSource.{ActorCompletionResult, ActorDataResult, ActorErrorResult}
import de.oliver_heger.linedj.io.stream._
import de.oliver_heger.linedj.shared.archive.media._
import de.oliver_heger.linedj.utils.ChildActorFactory

object CopyFileActor {

  /**
    * A message processed by [[CopyFileActor]] telling it to download a file and
    * copy it to the specified target path.
    *
    * Such a message is generated for each file in the playlist to be exported.
    * When the copy operation is complete, a corresponding ''MediumFileCopied''
    * message is sent to the owning actor.
    *
    * @param request the request for the file to be downloaded
    * @param target  the target path
    */
  case class CopyMediumFile(request: MediumFileRequest, target: Path)

  /**
    * A message sent by [[CopyFileActor]] after a file has been copied
    * successfully.
    *
    * The properties of this message correspond to the ones of the request
    * message.
    *
    * @param request the request for the file to be downloaded
    * @param target  the target path
    */
  case class MediumFileCopied(request: MediumFileRequest, target: Path)

  /**
    * A message processed by [[CopyFileActor]] which causes a currently
    * processed copy operation to be canceled.
    *
    * This is useful for instance if the user is presented a cancel button. In
    * this case not only the total export but also the current copy operation
    * has to be terminated because it may take a longer time.
    */
  case object CancelCopyOperation

  /**
    * A message sent by [[CopyFileActor]] if a configurable number of bytes of
    * a medium file has been copied.
    *
    * Messages of this type can be used for instance to update a progress
    * indicator. As media files may become large, it is not sufficient to update
    * an indicator on a per-file basis. Instead, updates during a file copy
    * operation may be necessary.
    *
    * @param copyRequest the copy request which is currently processed
    * @param size        the number of bytes copied for this file
    */
  case class CopyProgress(copyRequest: CopyMediumFile, size: Int)

  /**
    * Internal message used to report a crash of the current download actor.
    */
  private case object DownloadActorDied

  /**
    * Internal class representing a stream processing error.
    *
    * @param ex the exception
    */
  private case class StreamFailure(ex: Throwable)

  private class CopyFileActorImpl(parent: ActorRef, mediaManager: ActorRef, chunkSize: Int,
                                  progressSize: Int)
    extends CopyFileActor(parent, mediaManager, chunkSize, progressSize)
      with ChildActorFactory with CancelableStreamSupport

  /**
    * Creates a ''Props'' object for creating an instance of this actor class.
    *
    * @param parent       the parent actor (the one that receives responses)
    * @param mediaManager the media manager actor
    * @param chunkSize    the chunk size for I/O operations
    * @param progressSize the number of bytes when to send a progress
    *                     notification
    * @return a ''Props'' for creating an actor instance
    */
  def apply(parent: ActorRef, mediaManager: ActorRef, chunkSize: Int,
            progressSize: Int): Props =
    Props(classOf[CopyFileActorImpl], parent, mediaManager, chunkSize, progressSize)

}

/**
  * An actor class that copies a file received from the server into a target
  * directory.
  *
  * This actor class is used during the export of a playlist to write the single
  * files to their target destination. For each file to be copied the actor is
  * sent a message. It then queries the ''MediaManagerActor'' for a reader
  * actor to download this file. The file content is read and written to the
  * target location. After this is done, a confirmation message is sent to the
  * owning actor.
  *
  * Errors during a copy operation cause exceptions which are propagated to the
  * supervisor.
  *
  * @param parent       the parent actor (the one that receives responses)
  * @param mediaManager the media manager actor
  * @param chunkSize    the chunk size for I/O operations
  * @param progressSize the number of bytes after which a progress
  *                     notification message is sent
  */
class CopyFileActor(parent: ActorRef, mediaManager: ActorRef, chunkSize: Int,
                    progressSize: Int) extends AbstractFileWriterActor with ActorLogging {
  this: ChildActorFactory with CancelableStreamSupport =>

  import CopyFileActor._

  /** The currently processed copy request. */
  private var currentCopyRequest: CopyMediumFile = _

  /** The current download actor. */
  private var downloadActor: ActorRef = _

  override def customReceive: Receive = {
    case copyRequest: CopyMediumFile if currentCopyRequest == null =>
      mediaManager ! copyRequest.request
      currentCopyRequest = copyRequest

    case MediumFileResponse(_, optReader, _) if downloadActor == null &&
      currentCopyRequest != null =>
      optReader match {
        case Some(reader) =>
          downloadActor = createChildActor(Props(classOf[StreamSourceActorWrapper],
            reader, DownloadActorDied))
          runCopyStream()
        case None =>
          sendCopyCompletedNotification()
      }

    case CancelCopyOperation =>
      cancelCurrentStreams()
  }

  /**
    * @inheritdoc This implementation reacts on the result of stream
    *             processing. In case of an error, the actor stops itself.
    *             Otherwise, a completion message is sent to the parent.
    */
  override protected def propagateResult(client: ActorRef, result: Any): Unit = {
    copyRequestCompleted()
    super.propagateResult(client, result)
  }

  /**
    * Creates the source for the copy stream.
    *
    * @return the source
    */
  private[export] def createSource(): Source[ByteString, NotUsed] =
    ActorSource[ByteString](downloadActor, DownloadData(chunkSize)) {
      case DownloadDataResult(data) => ActorDataResult(data)
      case DownloadComplete => ActorCompletionResult()
      case DownloadActorDied => ActorErrorResult(new Exception("Download actor died!"))
    }

  /**
    * Starts the stream for the current copy operation.
    */
  private def runCopyStream(): Unit = {
    val source = createSource()
      .via(new CopyProgressNotificationStage(parent, currentCopyRequest, progressSize))
    writeFile(source, currentCopyRequest.target,
      MediumFileCopied(currentCopyRequest.request, currentCopyRequest.target),
      parent)
  }

  /**
    * This method is called when a copy request is complete. It cleans up some
    * internal fields and sends out corresponding messages.
    */
  private def copyRequestCompleted(): Unit = {
    context stop downloadActor
    downloadActor = null
    currentCopyRequest = null
  }

  /**
    * Sends a notification that the current copy operation is complete.
    */
  private def sendCopyCompletedNotification(): Unit = {
    parent ! MediumFileCopied(currentCopyRequest.request, currentCopyRequest.target)
    currentCopyRequest = null
  }
}


text:
package org.apache.uima.alchemy.annotator.mocked;

import org.apache.uima.alchemy.annotator.TextLanguageDetectionAnnotator;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * Mocking class for TextLanguageDetectionAnnotator to test AlchemyAPI calls' results
 */
public class MockedTextLanguageDetectionAnnotator extends TextLanguageDetectionAnnotator {

  private static final String path = "/languageDetectionResult.xml";

  @Override
  protected URL createServiceURI() throws MalformedURLException {
    return this.getClass().getResource(path);
  }

}


text:
#ifndef GRAPHLAB_SERIALIZE_HPP
#define GRAPHLAB_SERIALIZE_HPP
#include <graphlab/serialization/iarchive.hpp>
#include <graphlab/serialization/oarchive.hpp>
#include <graphlab/serialization/basic_types.hpp>

#include <graphlab/serialization/list.hpp>
#include <graphlab/serialization/set.hpp>
#include <graphlab/serialization/vector.hpp>
#include <graphlab/serialization/map.hpp>
#include <graphlab/serialization/unordered_map.hpp>
#include <graphlab/serialization/unordered_set.hpp>
#include <graphlab/serialization/serializable_pod.hpp>
#include <graphlab/serialization/unsupported_serialize.hpp>
#include <graphlab/serialization/serialize_to_from_string.hpp>
#include <graphlab/serialization/conditional_serialize.hpp>
#endif


text:
package org.jetbrains.plugins.scala
package lang
package navigation

import com.intellij.codeInsight.navigation.actions.GotoDeclarationAction
import com.intellij.testFramework.EditorTestUtil
import org.jetbrains.plugins.scala.base.{ScalaLightCodeInsightFixtureTestAdapter, ScalaLightPlatformCodeInsightTestCaseAdapter}
import org.junit.Assert.assertEquals

/**
  * Nikolay.Tropin
  * 08-Nov-17
  */
class ScalaGoToDeclarationTest extends ScalaLightPlatformCodeInsightTestCaseAdapter {

  import EditorTestUtil.{CARET_TAG => CARET}

  def testSyntheticApply(): Unit = doTest(
    s"""
       |case class Test(i: Int)
       |
       |object Test {
       |  def apply(boolean: Boolean) = ${CARET}Test(0)
       |}
      """,
    expected = "ScClass: Test"
  )

  def testSyntheticUnapply(): Unit = doTest(
    s"""
       |case class Test(i: Int)
       |
       |object Test {
       |  null match {
       |    case ${CARET}Test(1) =>
       |  }
       |}
      """,
    expected = "ScClass: Test"
  )

  def testSyntheticCopy(): Unit = doTest(
    s"""
       |case class Test(i: Int)
       |
       |object Test {
       |  Test(1).${CARET}copy(i = 2)
       |}
      """,
    expected = "ScClass: Test"
  )

  def testApply(): Unit = doTest(
    s"""
       |case class Test(i: Int)
       |
       |object Test {
       |  def apply(b: Boolean) = Test(0)
       |
       |  ${CARET}Test(false)
       |}
      """,
    expected = "ScObject: Test", "ScFunctionDefinition: apply"
  )

  def testPackageObjectOnly(): Unit = doTest(
    s"""
       |package org.example.foo
       |
       |package object bar {
       | def foo(): Unit = ???
       |}
       |
       |import org.example.foo.b${CARET}ar.foo
     """,
    expected = "ScPackageObject: bar"
  )

  def testPackageObjectAmbiguity(): Unit = doTest(
    s"""
       |package org.example.foo
       |
       |package object bar { }
       |
       |import org.example.foo.b${CARET}ar
     """,
    expected = "ScPackageObject: bar", "PsiPackage:org.example.foo.bar"
  )

  def testImportSelectorsMixed(): Unit = doTest(
    s"""
       |package org.example.foo
       |
       |package bar {
       |  object Bar
       |}
       |
       |package object bar {
       |  def baz(): Unit = ???
       |}
       |
       |import org.example.foo.ba${CARET}r.{Bar, baz}
     """,
    expected = "PsiPackage:org.example.foo.bar", "ScPackageObject: bar"
  )

  def testImportSelectorsExclusive(): Unit = doTest(
    s"""
       |package org.example.foo
       |
       |package bar {
       |  object Bar
       |}
       |
       |package object bar {
       |  def baz(): Unit = ???
       |  def qux(): Int = 52
       |}
       |
       |import org.example.foo.ba${CARET}r.{qux, baz}
     """,
    expected = "ScPackageObject: bar"
  )

  private def doTest(fileText: String, expected: String*): Unit = {
    val text = ScalaLightCodeInsightFixtureTestAdapter.normalize(fileText)
    configureFromFileTextAdapter("dummy.scala", text)

    val editor = getEditorAdapter
    val targets = GotoDeclarationAction.findAllTargetElements(
      project(),
      editor,
      editor.getCaretModel.getOffset
    ).map(_.toString).toSet

    assertEquals("Wrong number of targets: ", expected.size, targets.size)
    assertEquals("Wrong targets: ", expected.toSet, targets)
  }

}


text:
module LucidShopify
  class ProductAPI

    include LucidClient::API
    include LucidShopify::PaginatedResource

    def in_collection( collection_id, options = {} )
      all options.merge( :collection_id => collection_id )
    end

    private

    def _default_params
      super.merge( :published_status => 'published' )
    end

    def _model
      callable LucidShopify.config[:product_model]
    end

    def _resource
      'products'
    end

  end
end


text:
#!/usr/bin/env node
var fs = require('fs');
var JSONStream = require('JSONStream');
var through = require('through2');
var mkdirp = require('mkdirp');
var path = require('path');

var b = require('./args')(process.argv.slice(2));
process.stdout.on('error', process.exit);

if ((b.argv._[0] === 'help' && b.argv._[1]) === 'advanced'
|| (b.argv.h || b.argv.help) === 'advanced') {
    return fs.createReadStream(__dirname + '/advanced.txt')
        .pipe(process.stdout)
        .on('close', function () { process.exit(1) })
    ;
}
if (b.argv._[0] === 'help' || b.argv.h || b.argv.help
|| (process.argv.length <= 2 && process.stdin.isTTY)) {
    return fs.createReadStream(__dirname + '/usage.txt')
        .pipe(process.stdout)
        .on('close', function () { process.exit(1) })
    ;
}
if (b.argv.version) {
    return console.log(require('../package.json').version);
}

b.on('error', errorExit);

if (b.argv.pack) {
    process.stdin.pipe(b.pack()).pipe(process.stdout);
    process.stdin.resume();
    return;
}

if (b.argv.deps) {
    var stringify = JSONStream.stringify();
    stringify.pipe(process.stdout);
    b.pipeline.get('deps').push(through.obj(
        function (row, enc, next) { stringify.write(row); next() },
        function () { stringify.end() }
    ));
    return b.bundle();
}

if (b.argv.list) {
    b.pipeline.get('deps').push(through.obj(
        function (row, enc, next) {
            console.log(row.file || row.id);
            next()
        }
    ));
    return b.bundle();
}

var bundle = b.bundle();
bundle.on('error', errorExit);
bundle.on('end', successExit);

var tmpfile;
var outfile = b.argv.o || b.argv.outfile;
if (outfile) {
    mkdirp.sync(path.dirname(outfile));

    // we'll output to a temp file within same filesystem, then atomically overwrite outfile once successful
    tmpfile = outfile + ".tmp-browserify-" + Math.random().toFixed(20).slice(2)
    bundle.pipe(fs.createWriteStream(tmpfile));
}
else {
    bundle.pipe(process.stdout);
}

function errorExit(err) {
    if (tmpfile) fs.unlink(tmpfile, function (err) {
      if (err) /* no-op, we're already exiting unhappily… */;
    });
    if (err.stack) {
        console.error(err.stack);
    }
    else {
        console.error(String(err));
    }
    process.exit(1);
}

function successExit() {
  if (tmpfile && outfile) fs.rename(tmpfile, outfile, function (err) {
    if (err) errorExit(err);
  });
}


text:
Models
======

.. _component_sequence_model_sequence:

Sequence
--------

**Sequence** is a generated set of numbers and/or letters stored on a model. They may be useful for example as order or customer identifiers.

+------------+------------------------------+
| Property   | Description                  |
+============+==============================+
| id         | Unique id of the sequence    |
+------------+------------------------------+
| index      | The sequence's index         |
+------------+------------------------------+
| type       | The sequence's type          |
+------------+------------------------------+

.. note::
   This model implements the :ref:`component_sequence_model_sequence-interface`.

   For more detailed information go to `Sylius API Sequence`_.

.. _Sylius API Sequence: http://api.sylius.org/Sylius/Component/Sequence/Model/Sequence.html


text:
require 'minitest/autorun'
require 'minitest/spec'
require 'active_support/core_ext/kernel/reporting'
require 'active_model'
require 'rails'
begin
  require 'mongoid'
rescue LoadError
end

module RailsAdmin
end

require 'simple_form'
SimpleForm.setup {}

require 'formtastic'

module EnumerizeTest
  class Application < Rails::Application
    config.active_support.deprecation = :stderr
    config.active_support.test_order = :random
    config.eager_load = false
    config.secret_key_base = 'secret'
  end
end

EnumerizeTest::Application.initialize!

$VERBOSE=true

require 'enumerize'

Dir["#{File.dirname(__FILE__)}/support/*.rb"].each do |file|
  require file
end

module MiscHelpers
  def store_translations(locale, translations, &block)
    begin
      I18n.backend.store_translations locale, translations
      yield
    ensure
      I18n.reload!
    end
  end
end

class MiniTest::Spec
  include MiscHelpers
end


text:
"""
Testing Library for Indivo

Steve Zabak
steve.zabak@childrens.harvard.edu
"""

import os
import sys
import urllib
import socket
import httplib
import xml.parsers.expat
import xml_utils

from client_oauth import OAuth
try:
    from ..oauth import oauth
except:
    from oauth import oauth
from xml.dom import minidom
from urlparse import urlparse
from iaux import HTTP, Url, Reserved, Chars

class IUtils(OAuth):
    def __init__(self, scheme, host, port):
        self.request_response_info = {}
        signature = {'call' : ['name', 'method', 'url'], 'response' : ['element', 'attribute']}

        self.HTTP = HTTP()
        self.res = Reserved()
        self.chars = Chars()

        path_home = os.path.abspath(os.path.abspath(os.path.dirname(__file__)) + \
                                    self.chars.slash + self.chars.period + self.chars.period)

        self.empty_string = ''
        self.wd = self.chars.slash.join(__file__.split(self.chars.slash)[0:-2])
        self.url = Url(scheme, host, port)

    def _http_request(self, method, oauth_header, parameters):
        retval = {}
        try:
            uri = self.url.path
            if isinstance(parameters, dict):
                parameters = urllib.urlencode(parameters)

            # temporary hack (Ben)
            if method == "GET":
                self.url.query = parameters
                parameters = None

            # moved this here after query is regenerated (Ben)
            if len(self.url.query) > 0:
                uri = self.url.path + self.chars.qm + self.url.query

            if self.url.scheme == self.HTTP.https:
                connection = httplib.HTTPSConnection(self.url.host + self.url.portext)
            elif self.url.scheme == self.HTTP.http:
                connection = httplib.HTTPConnection(self.url.host + self.url.portext)

            # Make request
            connection.request(method, uri, parameters, headers = oauth_header)

            # Get response
            resp = connection.getresponse()
            retval[self.HTTP.ContentTypes.content_type] = self.empty_string
            for header in resp.getheaders():
                if header[0] == self.HTTP.content_type:
                    retval[self.HTTP.ContentTypes.content_type] = header[1]
            self.request_response_info[self.res.Debug.status] = resp.status
            self.request_response_info[self.res.Debug.content_type] = retval[self.HTTP.ContentTypes.content_type]

            # Handle status
            if resp.status == self.HTTP.Status.ok:
                retval[self.HTTP.content] = resp.read().strip(self.chars.newline)
                return retval
            elif resp.status == self.HTTP.Status.permission_denied:
                return self.HTTP.Errors.permission_denied + \
                            self.chars.colon + \
                            resp.read().strip(self.chars.newline)
            elif resp.status == self.HTTP.Status.not_found:
                retval[self.HTTP.content] = resp.read().strip(self.chars.newline)
                return retval
            elif resp.status == self.HTTP.Status.redirect:
                retval[self.HTTP.content] = resp.read().strip(self.chars.newline)
                return retval
            elif resp.status == self.HTTP.Status.server_error:
                raise Exception('Server Error')
                #return self.HTTP.Errors.server_error
            else:
                try:
                    msg = resp.read()
                except:
                    msg = '%s: %s' % (str(resp.status), uri)
                raise Exception(msg)

            # Handle Exceptions
        except httplib.ResponseNotReady:
            raise Exception(self.HTTP.Errors.server_not_ready)
        except httplib.CannotSendRequest:
            raise Exception(self.HTTP.Errors.cannot_send_request)
        except httplib.NotConnected:
            raise Exception(self.HTTP.Errors.not_connected)
        except httplib.CannotSendHeader:
            raise Exception(self.HTTP.Errors.cannot_send_header)
        except socket.error:
            raise Exception(self.HTTP.Errors.socket_error)
        except Exception, e:
            raise e

    def http_conn(self, method, url, app_info, parameters=None, data=None):
        """ """
        data = data or {}
        parameters  = parameters or {}

        content_type = self.get_content_type(parameters, data)
        if (url and self.set_url(url) and self.url_check(url)):
            if isinstance(method, str) or \
                isinstance(method, unicode):
                method = method.upper()
            else:
                return False

            if app_info.__contains__(self.res.oauth_token) and \
                    app_info.__contains__(self.res.oauth_token_secret):
                self.set_token(app_info[self.res.oauth_token], app_info[self.res.oauth_token_secret])
            else:
                self.set_token(None, None)
            oauth_header = self.get_oauth_request_header(
                                            method,
                                            parameters,
                                            data,
                                            app_info['consumer_key'],
                                            app_info['consumer_secret'],
                                            content_type=content_type)
            self.request_response_info[self.res.Debug.oauth_header] = oauth_header
            self.request_response_info[self.res.Debug.data] = data
            return self._http_request(method, oauth_header, data)
        else:
            return False

    def get_content_type(self, parameters, data):
        if not self.is_binary(data):
            if (isinstance(data, str) or isinstance(data, unicode)) and \
                len(data.strip()) > 0 and \
                data.strip()[0] == self.chars.lt:
                content_type = self.HTTP.ContentTypes.xml
            elif len(data) > 0 or len(parameters) > 0:
                content_type = self.HTTP.ContentTypes.form_urlencoded
            else:
                content_type = self.HTTP.ContentTypes.plain
        else:
            content_type = self.HTTP.ContentTypes.bzip2
        return content_type

    def is_binary(self, data):
        NULL_CHR = self.chars.hash
        count, null_count    = 1.0, 0.0
        threshold = 0.20
        if isinstance(data, str) or isinstance(data, unicode):
            printable = ''.join(["%s" % ((  ord(x) <= 127 and \
                                         len(repr(chr(ord(x)))) == 3 and \
                                         chr(ord(x))) or \
                                         NULL_CHR) for x in data])
            for char in printable:
                if char == NULL_CHR:
                    null_count += 1
                count += 1
            if null_count / count    > threshold:
                return True
        return False

    def read_resp(self, response_data, data_loc):
        # SZ: Clean code!
        if response_data:
            if isinstance(response_data, str):
                return response_data
            elif isinstance(response_data, dict):
                if response_data.__contains__(self.HTTP.ContentTypes.content_type):
                    if self.is_binary(response_data[self.HTTP.content]):
                        return response_data
                    if response_data[self.HTTP.ContentTypes.content_type] == self.HTTP.ContentTypes.xml:
                        return self.read_xml(response_data[self.HTTP.content], data_loc)
                    elif response_data[self.HTTP.ContentTypes.content_type] == self.HTTP.ContentTypes.html:
                        return self.read_text(response_data[self.HTTP.content])
                    elif response_data[self.HTTP.ContentTypes.content_type] == self.HTTP.ContentTypes.plain:
                        return self.read_text(response_data[self.HTTP.content])
                    elif response_data[self.HTTP.ContentTypes.content_type] == self.HTTP.ContentTypes.html:
                        return self.read_text(response_data[self.HTTP.content])
                    else:
                        # Assume Plain
                        return self.read_text(response_data[self.HTTP.content])
                else:
                    # Assume Plain
                    return self.read_text(response_data[self.HTTP.content])
        else:
            return False

    def read_text(self, plaintext):
        retval = {}
        self.request_response_info[self.res.Debug.response_data] = plaintext
        if plaintext.find(self.chars.amp) > 0:
            for i in plaintext.split(self.chars.amp):
                tmp = i.split(self.chars.eq)
                retval[tmp[0]] = tmp[1]
            return retval
        else:
            return plaintext

    def read_xml(self, xml_string, data_loc):
        # SZ: 'error' is deprecated
        error = 'error'
        self.request_response_info[self.res.Debug.response_data] = xml_string
        try:
            req_ids = {}
            if xml_string[0:5].lower() != error and len(data_loc) > 1:
                for i in xrange(0, len(data_loc), 2):
                    xml_list_node, xml_id_node = data_loc[i], data_loc[i+1]
                    req_ids[xml_list_node] = []
                    if xml_string is not None and \
                        isinstance(xml_string, str):
                        xmldoc = minidom.parseString(xml_string.strip())
                        doc_elem = xmldoc.documentElement
                        if doc_elem.nodeName == xml_list_node and \
                                hasattr(doc_elem.getAttributeNode(xml_id_node), 'value') and \
                                doc_elem.getAttributeNode(xml_id_node).value:
                                req_ids[xml_list_node].append(doc_elem.getAttributeNode(xml_id_node).value)
                        # If there are child nodes examine them
                        if doc_elem.hasChildNodes():
                            for node in doc_elem.childNodes:
                                if node is not None and \
                                    node.nodeName == xml_list_node:
                                    req_ids[xml_list_node].append(node.getAttribute(xml_id_node))
                return req_ids
            else:
                return False
        except AttributeError, e:
            raise Exception(e)
        except xml.parsers.expat.ExpatError:
            raise Exception("Expat Error: " + xml_string)

    def set_url(self, url):
        try:
            purl = urlparse(url)

            # SZ: For now only set the path
            #self.url.scheme    = purl.scheme
            #self.url.host      = purl.hostname
            #self.url.port      = purl.port

            self.url.path        = purl.path
            self.url.query   = purl.query
            return True
        except:
            return False

    def url_check(self, url):
        # This is in case convert_api_url is not used
        # self.url.url is deprecated
        if not hasattr(self.url, 'url'):
            self.url.url = url
        if self.url and self.url.url and \
                self.url_scheme_check() and self.url.host:
                if not self.url.port:
                    self.url.port = 80
                # SZ: Does not assume that path must be non-empty
                if hasattr(self.url, 'path'):
                    return True
        else:
            return False

    def url_scheme_check(self):
        #We'll need to build this out
        if self.url.scheme == self.HTTP.http or \
                self.url.scheme == self.HTTP.https:
            return True
        else:
            return False

    def reformat(self, dict):
        return self.chars.amp.join('%s=%s' % (str(n), str(v)) for n, v in dict.iteritems())

    def convert_api_url(self, url_path, kwargs):

        # Rebuild kwargs
        # ikwargs - inherited kwargs
        ikwargs = self.rebuild_kwargs(kwargs)

        query = ''
        for name, val in ikwargs.items():
            if isinstance(val, str) or isinstance(val, unicode):
                url_path = url_path.replace(self.chars.openbracket + name.upper() + self.chars.closebracket, val)
        # Remove any unmatched brackets
        url_path = self.remove_unmatched_vars(url_path)

        # Set the path
        try:
            qm_marker = url_path.index(self.chars.qm)
            self.url.path    = url_path[:qm_marker]
        except ValueError:
            self.url.path    = url_path

        # Set the query
        if url_path.find(self.chars.qm) > 0:
            query = url_path[url_path.find(self.chars.qm)+1:]
            if not query:
                url_path = url_path[0:-1]
        self.url.query = query

        # Set the entire url
        self.url.url = self.url.base + url_path

        # Add to debug
        self.request_response_info[self.res.Debug.url] = self.url.url

        return self.url.url

    def remove_unmatched_vars(self, path):
        lst = []
        count = 0
        for i in path:
            if i == self.chars.openbracket or \
                    i == self.chars.closebracket:
                lst.append(count)
            count += 1
        lst.sort()
        if len(lst) % 2 == 0:
            while len(lst) > 0:
                b = lst.pop()
                a = lst.pop()
                path = path[0:a] + path[b+1:]
        return path

    def get_response(self, api_config_name, api_method, api_url, resp_data_loc, app_info, req_data=None, **kwargs):
        req_data = req_data or {}
        retval = None

        # Reset debug info
        self.request_response_info = {}
        parameters = {}

        # Include parameters
        if kwargs.has_key(self.res.parameters) \
            and kwargs[self.res.parameters] \
            and len(kwargs[self.res.parameters]) > 0:

            # SZ: parameters should remain a dict
            # transform to a string in IClient
            # transform to a string in request
            # transform to a string for convert_api_url()

            # Set the parameters
            parameters = kwargs[self.res.parameters]
            kwargs[self.res.parameters] = urllib.urlencode(parameters)

        # Call http_conn(...)
        if api_method and api_url:
            self.request_response_info[self.res.Debug.method] = api_method
            retval = self.read_resp(
                        self.http_conn(api_method,
                            self.convert_api_url(
                                api_url, kwargs
                            ), app_info, parameters, req_data),
                    resp_data_loc)
            # PRD - Processed Response Data
            self.request_response_info['prd'] = retval
        if kwargs[self.res.Debug.debug]:
            self.print_debug_info()
        if retval is None:
            return False
        return self.request_response_info

    def rebuild_kwargs(self, kwargs):
        tmp_kwargs = {}
        for name, value in kwargs.items():
            if value:
                tmp_kwargs[name] = value
        return tmp_kwargs

    def print_debug_info(self):
        for n,v in self.request_response_info.items():
            print(n, self.chars.hyphen*10 + self.chars.gt, v)
        print(self.chars.eq*40)


text:
//
//
// MIT License
//
// Copyright (c) 2017 Stellacore Corporation.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject
// to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
// KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
// AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//

#ifndef math_QuadEq_INCL_
#define math_QuadEq_INCL_

/*! \file
\brief Declarations for math::QuadEq
*/

#include "libdat/validity.h"
#include "libmath/math.h"

#include <string>
#include <utility>
#include <vector>

namespace math
{

/*! \brief Classic quadratic equation.

\par Example
\dontinclude testmath/uQuadEq.cpp
\skip ExampleStart
\until ExampleEnd
*/
class QuadEq
{

	double const theA{ dat::nullValue<double>() }; // x^2 coefficent
	double const theB{ dat::nullValue<double>() }; // x^1
	double const theC{ dat::nullValue<double>() }; // x^0

	// cached intermediary
	double const theDescrim{ dat::nullValue<double>() }; // descrimant
	double const theDelta{ dat::nullValue<double>() }; // root(descrim)

public: // methods

	QuadEq
		() = default;

	//! Value ctor
	explicit
	QuadEq
		( double const coA
		, double const coB
		, double const coC
		);

	//! Check if instance is valid
	bool
	isValid
		() const;

	//! The more negative of the two roots
	double
	realRootMin
		() const;

	//! The more positive of the two roots
	double
	realRootMax
		() const;

	//! All roots: returns either: 0)empty, 1)averageMinMax, 2){min,max}
	std::vector<double>
	realUniqueRoots
		( double const & tol = math::eps
		) const;

	//! The smallest non-negative root (or null)
	double
	realRootMinPos
		() const;

	//! Descriptive information about this instance.
	std::string
	infoString
		( std::string const & title = std::string()
		) const;
};

}

// Inline definitions
// #include "libmath/QuadEq.inl"

#endif // math_QuadEq_INCL_