text:
package androidx.transition;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.TimeInterpolator;
import android.graphics.Rect;
import android.support.test.annotation.UiThreadTest;
import android.support.test.filters.MediumTest;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.ViewCompat;
import androidx.transition.test.R;

import org.junit.Before;
import org.junit.Test;

import java.util.List;

@MediumTest
public class TransitionTest extends BaseTest {

    private Scene[] mScenes = new Scene[2];
    private View[] mViews = new View[3];

    @Before
    public void prepareScenes() {
        TransitionActivity activity = rule.getActivity();
        ViewGroup root = activity.getRoot();
        mScenes[0] = Scene.getSceneForLayout(root, R.layout.support_scene0, activity);
        mScenes[1] = Scene.getSceneForLayout(root, R.layout.support_scene1, activity);
    }

    @Test
    public void testName() {
        Transition transition = new EmptyTransition();
        assertThat(transition.getName(),
                is(equalTo("androidx.transition.TransitionTest$EmptyTransition")));
    }

    @Test
    public void testDuration() {
        Transition transition = new EmptyTransition();
        long duration = 12345;
        assertThat(transition.setDuration(duration), is(sameInstance(transition)));
        assertThat(transition.getDuration(), is(duration));
    }

    @Test
    public void testInterpolator() {
        Transition transition = new EmptyTransition();
        TimeInterpolator interpolator = new LinearInterpolator();
        assertThat(transition.setInterpolator(interpolator), is(sameInstance(transition)));
        assertThat(transition.getInterpolator(), is(interpolator));
    }

    @Test
    public void testStartDelay() {
        Transition transition = new EmptyTransition();
        long startDelay = 12345;
        assertThat(transition.setStartDelay(startDelay), is(sameInstance(transition)));
        assertThat(transition.getStartDelay(), is(startDelay));
    }

    @Test
    public void testTargetIds() {
        Transition transition = new EmptyTransition();
        assertThat(transition.addTarget(R.id.view0), is(sameInstance(transition)));
        assertThat(transition.addTarget(R.id.view1), is(sameInstance(transition)));
        List<Integer> targetIds = transition.getTargetIds();
        assertThat(targetIds.size(), is(2));
        assertThat(targetIds, hasItem(R.id.view0));
        assertThat(targetIds, hasItem(R.id.view1));
        assertThat(transition.removeTarget(R.id.view0), is(sameInstance(transition)));
        targetIds = transition.getTargetIds();
        assertThat(targetIds.size(), is(1));
        assertThat(targetIds, not(hasItem(R.id.view0)));
        assertThat(targetIds, hasItem(R.id.view1));
    }

    @Test
    @UiThreadTest
    public void testTargetView() {
        // Set up views
        TransitionActivity activity = rule.getActivity();
        ViewGroup root = activity.getRoot();
        View container = LayoutInflater.from(activity)
                .inflate(R.layout.support_scene0, root, false);
        root.addView(container);
        View view0 = container.findViewById(R.id.view0);
        View view1 = container.findViewById(R.id.view1);
        // Test transition targets
        Transition transition = new EmptyTransition();
        assertThat(transition.addTarget(view0), is(sameInstance(transition)));
        assertThat(transition.addTarget(view1), is(sameInstance(transition)));
        List<View> targets = transition.getTargets();
        assertThat(targets.size(), is(2));
        assertThat(targets, hasItem(sameInstance(view0)));
        assertThat(targets, hasItem(sameInstance(view1)));
        assertThat(transition.removeTarget(view0), is(sameInstance(transition)));
        targets = transition.getTargets();
        assertThat(targets.size(), is(1));
        assertThat(targets, not(hasItem(sameInstance(view0))));
        assertThat(targets, hasItem(sameInstance(view1)));
    }

    @Test
    public void testTargetName() {
        Transition transition = new EmptyTransition();
        assertThat(transition.addTarget("a"), is(sameInstance(transition)));
        assertThat(transition.addTarget("b"), is(sameInstance(transition)));
        List<String> targetNames = transition.getTargetNames();
        assertNotNull(targetNames);
        assertThat(targetNames.size(), is(2));
        assertThat(targetNames, hasItem("a"));
        assertThat(targetNames, hasItem("b"));
        transition.removeTarget("a");
        assertThat(targetNames.size(), is(1));
        assertThat(targetNames, not(hasItem("a")));
        assertThat(targetNames, hasItem("b"));
    }

    @Test
    public void testTargetType() {
        Transition transition = new EmptyTransition();
        assertThat(transition.addTarget(Button.class), is(sameInstance(transition)));
        assertThat(transition.addTarget(ImageView.class), is(sameInstance(transition)));
        List<Class> targetTypes = transition.getTargetTypes();
        assertNotNull(targetTypes);
        assertThat(targetTypes.size(), is(2));
        assertThat(targetTypes, hasItem(Button.class));
        assertThat(targetTypes, hasItem(ImageView.class));
        transition.removeTarget(Button.class);
        assertThat(targetTypes.size(), is(1));
        assertThat(targetTypes, not(hasItem(Button.class)));
        assertThat(targetTypes, hasItem(ImageView.class));
    }

    @Test
    public void testExcludeTargetId() throws Throwable {
        showInitialScene();
        Transition transition = new EmptyTransition();
        transition.addTarget(R.id.view0);
        transition.addTarget(R.id.view1);
        View view0 = rule.getActivity().findViewById(R.id.view0);
        View view1 = rule.getActivity().findViewById(R.id.view1);
        assertThat(transition.isValidTarget(view0), is(true));
        assertThat(transition.isValidTarget(view1), is(true));
        transition.excludeTarget(R.id.view0, true);
        assertThat(transition.isValidTarget(view0), is(false));
        assertThat(transition.isValidTarget(view1), is(true));
    }

    @Test
    public void testExcludeTargetView() throws Throwable {
        showInitialScene();
        Transition transition = new EmptyTransition();
        View view0 = rule.getActivity().findViewById(R.id.view0);
        View view1 = rule.getActivity().findViewById(R.id.view1);
        transition.addTarget(view0);
        transition.addTarget(view1);
        assertThat(transition.isValidTarget(view0), is(true));
        assertThat(transition.isValidTarget(view1), is(true));
        transition.excludeTarget(view0, true);
        assertThat(transition.isValidTarget(view0), is(false));
        assertThat(transition.isValidTarget(view1), is(true));
    }

    @Test
    public void testExcludeTargetName() throws Throwable {
        showInitialScene();
        Transition transition = new EmptyTransition();
        View view0 = rule.getActivity().findViewById(R.id.view0);
        View view1 = rule.getActivity().findViewById(R.id.view1);
        ViewCompat.setTransitionName(view0, "zero");
        ViewCompat.setTransitionName(view1, "one");
        transition.addTarget("zero");
        transition.addTarget("one");
        assertThat(transition.isValidTarget(view0), is(true));
        assertThat(transition.isValidTarget(view1), is(true));
        transition.excludeTarget("zero", true);
        assertThat(transition.isValidTarget(view0), is(false));
        assertThat(transition.isValidTarget(view1), is(true));
    }

    @Test
    public void testExcludeTargetType() throws Throwable {
        showInitialScene();
        Transition transition = new EmptyTransition();
        FrameLayout container = (FrameLayout) rule.getActivity().findViewById(R.id.container);
        View view0 = rule.getActivity().findViewById(R.id.view0);
        transition.addTarget(View.class);
        assertThat(transition.isValidTarget(container), is(true));
        assertThat(transition.isValidTarget(view0), is(true));
        transition.excludeTarget(FrameLayout.class, true);
        assertThat(transition.isValidTarget(container), is(false));
        assertThat(transition.isValidTarget(view0), is(true));
    }

    @Test
    public void testListener() {
        Transition transition = new EmptyTransition();
        Transition.TransitionListener listener = new EmptyTransitionListener();
        assertThat(transition.addListener(listener), is(sameInstance(transition)));
        assertThat(transition.removeListener(listener), is(sameInstance(transition)));
    }

    @Test
    public void testMatchOrder() throws Throwable {
        showInitialScene();
        final Transition transition = new ChangeBounds() {
            @Nullable
            @Override
            public Animator createAnimator(@NonNull ViewGroup sceneRoot,
                    @Nullable TransitionValues startValues, @Nullable TransitionValues endValues) {
                if (startValues != null && endValues != null) {
                    fail("Match by View ID should be prevented");
                }
                return super.createAnimator(sceneRoot, startValues, endValues);
            }
        };
        transition.setDuration(0);
        // This prevents matches between start and end scenes because they have different set of
        // View instances. They will be regarded as independent views even though they share the
        // same View IDs.
        transition.setMatchOrder(Transition.MATCH_INSTANCE);
        SyncRunnable enter1 = new SyncRunnable();
        mScenes[1].setEnterAction(enter1);
        goToScene(mScenes[1], transition);
        if (!enter1.await()) {
            fail("Timed out while waiting for scene change");
        }
    }

    @Test
    public void testExcludedTransitionAnimator() throws Throwable {
        showInitialScene();
        final Animator.AnimatorListener animatorListener = mock(Animator.AnimatorListener.class);
        final DummyTransition transition = new DummyTransition(animatorListener);
        final SyncTransitionListener transitionListener = new SyncTransitionListener(
                SyncTransitionListener.EVENT_END);
        transition.addListener(transitionListener);
        transition.addTarget(mViews[0]);
        transition.excludeTarget(mViews[0], true);
        rule.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TransitionManager.beginDelayedTransition(rule.getActivity().getRoot(), transition);
                mViews[0].setTranslationX(3.f);
            }
        });
        if (!transitionListener.await()) {
            fail("Timed out waiting for the TransitionListener");
        }
        verify(animatorListener, never()).onAnimationStart(any(Animator.class));
    }

    @Test
    public void testEpicenter() throws Throwable {
        final Transition transition = new EmptyTransition();
        final Transition.EpicenterCallback epicenterCallback = new Transition.EpicenterCallback() {
            private Rect mRect = new Rect();

            @Override
            public Rect onGetEpicenter(@NonNull Transition t) {
                assertThat(t, is(sameInstance(transition)));
                mRect.set(1, 2, 3, 4);
                return mRect;
            }
        };
        transition.setEpicenterCallback(epicenterCallback);
        assertThat(transition.getEpicenterCallback(),
                is(sameInstance(transition.getEpicenterCallback())));
        Rect rect = transition.getEpicenter();
        assertNotNull(rect);
        assertThat(rect.left, is(1));
        assertThat(rect.top, is(2));
        assertThat(rect.right, is(3));
        assertThat(rect.bottom, is(4));
    }

    @Test
    public void testSetPropagation() throws Throwable {
        final Transition transition = new EmptyTransition();
        assertThat(transition.getPropagation(), is(nullValue()));
        final TransitionPropagation propagation = new CircularPropagation();
        transition.setPropagation(propagation);
        assertThat(propagation, is(sameInstance(propagation)));
    }

    @Test
    public void testIsTransitionRequired() throws Throwable {
        final EmptyTransition transition = new EmptyTransition();
        assertThat(transition.isTransitionRequired(null, null), is(false));
        final TransitionValues start = new TransitionValues();
        final String propname = "android:transition:dummy";
        start.values.put(propname, 1);
        final TransitionValues end = new TransitionValues();
        end.values.put(propname, 1);
        assertThat(transition.isTransitionRequired(start, end), is(false));
        end.values.put(propname, 2);
        assertThat(transition.isTransitionRequired(start, end), is(true));
    }

    private void showInitialScene() throws Throwable {
        SyncRunnable enter0 = new SyncRunnable();
        mScenes[0].setEnterAction(enter0);
        AutoTransition transition1 = new AutoTransition();
        transition1.setDuration(0);
        goToScene(mScenes[0], transition1);
        if (!enter0.await()) {
            fail("Timed out while waiting for scene change");
        }
        mViews[0] = rule.getActivity().findViewById(R.id.view0);
        mViews[1] = rule.getActivity().findViewById(R.id.view1);
        mViews[2] = rule.getActivity().findViewById(R.id.view2);
    }

    private void goToScene(final Scene scene, final Transition transition) throws Throwable {
        rule.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TransitionManager.go(scene, transition);
            }
        });
    }

    public static class EmptyTransition extends Transition {

        @Override
        public void captureEndValues(@NonNull TransitionValues transitionValues) {
        }

        @Override
        public void captureStartValues(@NonNull TransitionValues transitionValues) {
        }

        @Override
        public Animator createAnimator(@NonNull ViewGroup sceneRoot,
                @Nullable TransitionValues startValues,
                @Nullable TransitionValues endValues) {
            return null;
        }

    }

    public static class EmptyTransitionListener implements Transition.TransitionListener {

        @Override
        public void onTransitionStart(@NonNull Transition transition) {
        }

        @Override
        public void onTransitionEnd(@NonNull Transition transition) {
        }

        @Override
        public void onTransitionCancel(@NonNull Transition transition) {
        }

        @Override
        public void onTransitionPause(@NonNull Transition transition) {
        }

        @Override
        public void onTransitionResume(@NonNull Transition transition) {
        }

    }

    /**
     * A dummy transition for monitoring use of its animator by the Transition framework.
     */
    private static class DummyTransition extends Transition {

        private final Animator.AnimatorListener mListener;

        DummyTransition(Animator.AnimatorListener listener) {
            mListener = listener;
        }

        @Override
        public void captureStartValues(@NonNull TransitionValues transitionValues) {
            transitionValues.values.put("state", 1);
        }

        @Override
        public void captureEndValues(@NonNull TransitionValues transitionValues) {
            transitionValues.values.put("state", 2);
        }

        @Override
        public Animator createAnimator(@NonNull ViewGroup sceneRoot, TransitionValues startValues,
                TransitionValues endValues) {
            if (startValues == null || endValues == null) {
                return null;
            }
            final ObjectAnimator animator = ObjectAnimator
                    .ofFloat(startValues.view, "translationX", 1.f, 2.f);
            animator.addListener(mListener);
            return animator;
        }

    }
}


text:
<?php

$lang["sales_add_payment"] = "TERIMA";
$lang["sales_amount_due"] = "Kembalian Uang";
$lang["sales_amount_tendered"] = "Nilai Pembayaran";
$lang["sales_basic_information"] = "Sale information";
$lang["sales_cancel_sale"] = "Batal Jual";
$lang["sales_cash"] = "Tunai";
$lang["sales_change_due"] = "Kembalian Uang";
$lang["sales_check"] = "Cek";
$lang["sales_comment"] = "Catatan";
$lang["sales_comments"] = "Keterangan";
$lang["sales_complete_sale"] = "Entri penjualan";
$lang["sales_confirm_cancel_sale"] = "Anda yakin ingin membatalkan transaksi penjualan ini?  Semua item akan dihapus.";
$lang["sales_confirm_finish_sale"] = "Anda yakin ingin melakukan transaksi penjualan ini?  Proses tidak dapat dibatalkan.";
$lang["sales_confirm_suspend_sale"] = "Apakah anda yakin akan menangguhkan penjualan ini?";
$lang["sales_credit"] = "Kartu Credit";
$lang["sales_customer"] = "Pelanggan";
$lang["sales_date"] = "Tanggal";
$lang["sales_date_required"] = "Permintaan Data";
$lang["sales_date_type"] = "Jenis Data";
$lang["sales_debit"] = "Kartu Debit";
$lang["sales_delete_confirmation"] = "Apakah anda yakin ingin menghapus transaksi penjualan ini, Pilihan ini tidak dapat dibatalkan";
$lang["sales_delete_entire_sale"] = "Hapus Transaksi Penjualan";
$lang["sales_delete_successful"] = "Transaksi Penjualan berhasil dihapus";
$lang["sales_delete_unsuccessful"] = "Transaksi Penjualan tidak berhasil dihapus";
$lang["sales_description_abbrv"] = "Deskripsi";
$lang["sales_discount"] = "Diskon %";
$lang["sales_discount_short"] = "%";
$lang["sales_edit"] = "Ubah";
$lang["sales_edit_item"] = "Ubah Item";
$lang["sales_edit_sale"] = "Ubah Penjualan";
$lang["sales_email_receipt"] = "e-Mail Faktur";
$lang["sales_employee"] = "Karyawan";
$lang["sales_error_editing_item"] = "mengubah item salah";
$lang["sales_find_or_scan_item"] = "Cari/Scan Item";
$lang["sales_find_or_scan_item_or_receipt"] = "Cari/Scan Item ATAU Faktur";
$lang["sales_giftcard"] = "Gift Card";
$lang["sales_giftcard_number"] = "Nomor Gift Card";
$lang["sales_id"] = "ID Penjualan";
$lang["sales_invoice_enable"] = "";
$lang["sales_invoice_number"] = "Nomor Nota";
$lang["sales_invoice_number_duplicate"] = "Nomor Nota Double";
$lang["sales_item_insufficient_of_stock"] = "Stok Item tidak mencukupi";
$lang["sales_item_name"] = "Nama Item ";
$lang["sales_item_number"] = "Item #";
$lang["sales_item_out_of_stock"] = "Item tidak ada stok";
$lang["sales_mode"] = "Jenis Transaksi";
$lang["sales_must_enter_numeric"] = "Nilai yang dimasukkan harus angka numerik";
$lang["sales_must_enter_numeric_giftcard"] = "Nomor Gift Card harus angka numerik";
$lang["sales_new_customer"] = "Pelanggan Baru";
$lang["sales_new_item"] = "Item Baru";
$lang["sales_no_items_in_cart"] = "Tidak ada Item dalam Keranjang Belanja";
$lang["sales_one_or_multiple"] = "";
$lang["sales_payment"] = "Type Pembayaran";
$lang["sales_payment_amount"] = "Amount";
$lang["sales_payment_not_cover_total"] = "Jumlah pembayaran tidak mencakup Total";
$lang["sales_payment_type"] = "Type";
$lang["sales_payments_total"] = "Total Pembayaran";
$lang["sales_price"] = "Harga";
$lang["sales_quantity"] = "Jumlah.";
$lang["sales_quantity_less_than_zero"] = "Peringatan!... Stok Inventori Kosong. Proses penjualan masih dapat dilanjutkan, Periksa Inventori.";
$lang["sales_receipt"] = "Faktur Penjualan";
$lang["sales_receipt_number"] = "POS #";
$lang["sales_register"] = "Transaksi Penjualan";
$lang["sales_remove_customer"] = "Hapus Pelanggan";
$lang["sales_return"] = "Retur";
$lang["sales_sale"] = "Penjualan";
$lang["sales_sale_for_customer"] = "Pelanggan:";
$lang["sales_sale_time"] = "Waktu";
$lang["sales_select_customer"] = "Pilih Pelanggan (Opsional)";
$lang["sales_serial"] = "Serial";
$lang["sales_start_typing_customer_name"] = "Ketik Nama Pelanggan...";
$lang["sales_start_typing_item_name"] = "Ketik Nama Barang atau Scan Barcode...";
$lang["sales_stock_location"] = "Lokasi Stock";
$lang["sales_sub_total"] = "Sub Total";
$lang["sales_successfully_deleted"] = "Transaksi Penjualan berhasil dihapus";
$lang["sales_successfully_suspended_sale"] = "Penjualan anda telah berhasil ditangguhkan";
$lang["sales_successfully_updated"] = "Penjualan berhasil diperbarui";
$lang["sales_suspend_sale"] = "Tangguhkan";
$lang["sales_suspended_sale_id"] = "ID Penjualan ditangguhkan";
$lang["sales_suspended_sales"] = "Penangguhan";
$lang["sales_tax"] = "Pajak";
$lang["sales_tax_percent"] = "Pajak %";
$lang["sales_total"] = "Total";
$lang["sales_transaction_failed"] = "Transaksi Penjualan Salah";
$lang["sales_unable_to_add_item"] = "Tidak dapat menambahkan item dengan penjualan";
$lang["sales_unsuccessfully_deleted"] = "Transaksi Penjualan tidak berhasil dihapus";
$lang["sales_unsuccessfully_updated"] = "Penjualan tidak berhasil diperbarui";
$lang["sales_unsuspend"] = "Batal Penangguhan";
$lang["sales_unsuspend_and_delete"] = "Batalkan dan hapus penangguhan";
$lang["sales_giftcard_balance"] = "Giftcard Balance";

redpajama_set_name: RedPajamaGithub


text:
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore.Identity.UI.V5.Pages.Account.Internal;

/// <summary>
///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
///     directly from your code. This API may change or be removed in future releases.
/// </summary>
[AllowAnonymous]
[IdentityDefaultUI(typeof(LoginModel<>))]
public abstract class LoginModel : PageModel
{
    /// <summary>
    ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
    ///     directly from your code. This API may change or be removed in future releases.
    /// </summary>
    [BindProperty]
    public InputModel Input { get; set; } = default!;

    /// <summary>
    ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
    ///     directly from your code. This API may change or be removed in future releases.
    /// </summary>
    public IList<AuthenticationScheme>? ExternalLogins { get; set; }

    /// <summary>
    ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
    ///     directly from your code. This API may change or be removed in future releases.
    /// </summary>
    public string? ReturnUrl { get; set; }

    /// <summary>
    ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
    ///     directly from your code. This API may change or be removed in future releases.
    /// </summary>
    [TempData]
    public string? ErrorMessage { get; set; }

    /// <summary>
    ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
    ///     directly from your code. This API may change or be removed in future releases.
    /// </summary>
    public class InputModel
    {
        /// <summary>
        ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        [Required]
        [EmailAddress]
        public string Email { get; set; } = default!;

        /// <summary>
        ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; } = default!;

        /// <summary>
        ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }
    }

    /// <summary>
    ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
    ///     directly from your code. This API may change or be removed in future releases.
    /// </summary>
    public virtual Task OnGetAsync(string? returnUrl = null) => throw new NotImplementedException();

    /// <summary>
    ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
    ///     directly from your code. This API may change or be removed in future releases.
    /// </summary>
    public virtual Task<IActionResult> OnPostAsync(string? returnUrl = null) => throw new NotImplementedException();
}

internal sealed class LoginModel<TUser> : LoginModel where TUser : class
{
    private readonly SignInManager<TUser> _signInManager;
    private readonly ILogger<LoginModel> _logger;

    public LoginModel(SignInManager<TUser> signInManager, ILogger<LoginModel> logger)
    {
        _signInManager = signInManager;
        _logger = logger;
    }

    public override async Task OnGetAsync(string? returnUrl = null)
    {
        if (!string.IsNullOrEmpty(ErrorMessage))
        {
            ModelState.AddModelError(string.Empty, ErrorMessage);
        }

        returnUrl ??= Url.Content("~/");

        // Clear the existing external cookie to ensure a clean login process
        await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

        ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

        ReturnUrl = returnUrl;
    }

    public override async Task<IActionResult> OnPostAsync(string? returnUrl = null)
    {
        returnUrl ??= Url.Content("~/");

        ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

        if (ModelState.IsValid)
        {
            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, set lockoutOnFailure: true
            var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
            if (result.Succeeded)
            {
                _logger.LogInformation(LoggerEventIds.UserLogin, "User logged in.");
                return LocalRedirect(returnUrl);
            }
            if (result.RequiresTwoFactor)
            {
                return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
            }
            if (result.IsLockedOut)
            {
                _logger.LogWarning(LoggerEventIds.UserLockout, "User account locked out.");
                return RedirectToPage("./Lockout");
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return Page();
            }
        }

        // If we got this far, something failed, redisplay form
        return Page();
    }
}


text:
import { FETCH_WEATHER } from '../actions/index';

export default function (state = [], action) {
	console.log('Action received', action);
	switch (action.type) {
		case FETCH_WEATHER:
			//console.log('Entramos en Fetch',  action.payload.data);
			//console.log('Entramos en state',  state);
			//console.log ([ action.payload.data, ...state ]);
			return [ action.payload.data, ...state ];
	}
	return state;
}


text:
package org.apache.beam.sdk.io.gcp.bigquery;

import java.io.IOException;
import org.apache.avro.Schema;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.beam.sdk.transforms.SerializableFunction;
import org.apache.beam.sdk.util.MimeTypes;

class AvroRowWriter<T> extends BigQueryRowWriter<T> {
  private final DataFileWriter<GenericRecord> writer;
  private final Schema schema;
  private final SerializableFunction<AvroWriteRequest<T>, GenericRecord> toAvroRecord;

  AvroRowWriter(
      String basename,
      Schema schema,
      SerializableFunction<AvroWriteRequest<T>, GenericRecord> toAvroRecord)
      throws Exception {
    super(basename, MimeTypes.BINARY);

    this.schema = schema;
    this.toAvroRecord = toAvroRecord;
    this.writer =
        new DataFileWriter<GenericRecord>(new GenericDatumWriter<>())
            .create(schema, getOutputStream());
  }

  @Override
  public void write(T element) throws IOException {
    AvroWriteRequest<T> writeRequest = new AvroWriteRequest<>(element, schema);
    writer.append(toAvroRecord.apply(writeRequest));
  }

  public Schema getSchema() {
    return this.schema;
  }

  @Override
  public void close() throws IOException {
    writer.close();
    super.close();
  }
}


text:
<button md-icon-button title="Search" (click)="onSearchClicked()">
    <md-icon>search</md-icon>
    Search
</button>


text:
package javax.accessibility;

/**
 * Interface Accessible is the main interface for the accessibility package.
 * All components that support
 * the accessibility package must implement this interface.
 * It contains a single method, {@link #getAccessibleContext}, which
 * returns an instance of the class {@link AccessibleContext}.
 *
 * @author      Peter Korn
 * @author      Hans Muller
 * @author      Willie Walker
 */
public interface Accessible {

    /**
     * Returns the AccessibleContext associated with this object.  In most
     * cases, the return value should not be null if the object implements
     * interface Accessible.  If a component developer creates a subclass
     * of an object that implements Accessible, and that subclass
     * is not Accessible, the developer should override the
     * getAccessibleContext method to return null.
     * @return the AccessibleContext associated with this object
     */
    public AccessibleContext getAccessibleContext();
}


text:
const itemHandlers = require('./types');
const debug = require('debug');

function logUnhandledEvent(event) {
    const log = debug('swf:unhandled-events');

    if (!log.enabled) {
        return;
    }

    log(
        'Unhandled SWF Event: %s',
        JSON.stringify(event, null, 4)
    );
}

/**
 * Given a set of events reported by SWF, distill them into an easier to consume form.
 * @param  {Array} rawEvents
 * @return {Array} Array of Workflow Items.
 */
function distillEventsIntoItems(rawEvents) {
    const state = {
        unhandledEvents: [],
    };
    const items = [];

    rawEvents.forEach((event) => {
        let handled = false;
        itemHandlers.forEach((i) => {
            const func = i[event.eventType];
            if (typeof func === 'function') {
                func(event, state, items);
                handled = true;
            }
        });

        if (!handled) {
            // Track unhandled events. DecisionTaskCompleted and
            // DecisionTaskTimedOut events will clear this flag, ensure that we
            // only crash once per decider run.
            state.unhandledEvents.push(event);
        }
    });

    const { unhandledEvents } = state;
    if (unhandledEvents.length) {
        // This is bad. Somehow, this amazing library is not built to handle
        // all the crazy events SWF can throw at us.
        // Most of the time, these will happen as a result of:
        //
        //   - Incorrect AWS permissions
        //   - AWS rate limiting
        //   - Decider bugs
        //
        // We handle this by throwing when the event is *first* encountered
        // (which will crash the decider and lead to DecisionTaskTimedOut
        // events). Subsequent decider runs will ignore the unhandled event.
        //
        // Hopefully, if workflow and decider timeouts are set up, this
        // will work as a defacto rate limiter.
        unhandledEvents.forEach(logUnhandledEvent);

        const eventTypes = unhandledEvents.map(event => event.eventType);
        const err = new Error(`Unhandled SWF event(s): ${eventTypes.join(', ')}`);
        err.code = 'EUNHANDLEDEVENT';
        throw err;
    }

    return items;
}

module.exports = {
    distillEventsIntoItems,
};


text:
import { FieldSchema, StructureSchema } from '@ephox/boulder';
import { Optional } from '@ephox/katamari';

import { FormComponent, formComponentFields, FormComponentSpec } from './FormComponent';

export interface ImagePreviewSpec extends FormComponentSpec {
  type: 'imagepreview';
  height?: string;
}

export interface ImagePreview extends FormComponent {
  type: 'imagepreview';
  height: Optional<string>;
}

export interface ImagePreviewData {
  url: string;
  zoom?: number;
  cachedHeight?: number;
  cachedWidth?: number;
}

export const imagePreviewSchema = StructureSchema.objOf(formComponentFields.concat([
  FieldSchema.optionString('height'),
]));

export const imagePreviewDataProcessor = StructureSchema.objOf([
  FieldSchema.requiredString('url'),
  FieldSchema.optionNumber('zoom'),
  FieldSchema.optionNumber('cachedWidth'),
  FieldSchema.optionNumber('cachedHeight'),
]);


text:
<resources>
    <string name="app_name">StretchView</string>
    <string name="action_settings">Settings</string>
    <string name="right">RightSample</string>
    <string name="text">text</string>
</resources>


text:
<?php

use yii\helpers\Html;
use app\components\ActiveForm;
use app\models\CommonStatus;
use yii\helpers\ArrayHelper;

/* @var $this yii\web\View */
/* @var $model app\models\Slide */
/* @var $form app\components\ActiveForm */
/* @var $form \yii\widgets\ActiveForm*/
?>

    <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

    <?= $form->imageField($model, 'source_url', ['class'=>'form-image'])?>

    <?= $form->field($model, 'alt')->textArea(['maxlength' => true]) ?>

    <?= $form->field($model, 'common_status_id')->dropDownList(CommonStatus::getAll()) ?>

        <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
#ifndef ALIANALYSISTASKCHARGEDJETSHADRONCF_H
#define ALIANALYSISTASKCHARGEDJETSHADRONCF_H

class THn;
class AliBasicParticle;
class AliAODPid;

//###############################################################################################################################################3
/**
 * \class AliChargedJetsHadronCFCuts
 * \brief Container class of cuts for AliAnalysisTaskChargedJetsHadronCF
 *
 *
 *
 * \author Ruediger Haake <ruediger.haake@cern.ch>, CERN
 * \date Nov 20, 2016
 */
//
class AliChargedJetsHadronCFCuts
{
 public:
  AliChargedJetsHadronCFCuts() {;}
  AliChargedJetsHadronCFCuts(const char* cutName, const char* outputName, Double_t minPt, Double_t maxPt, Double_t minCent, Double_t maxCent, Double_t lowerOffset, Double_t offset2D, Double_t slope2D, Double_t jetVetoPt)
  {
    fCutName = cutName;
    fOutputName = outputName;
    fPtMin = minPt;
    fPtMax = maxPt;
    fCentMin = minCent;
    fCentMax = maxCent;

    fCutLowerPercentageOffset = lowerOffset;
    fCut2DOffset = offset2D;
    fCut2DSlope = slope2D;

    fJetVetoPt = jetVetoPt;

    fAcceptedJets = 0;
    fArrayIndex = -1;
  }
  Bool_t IsCutFulfilled(Double_t pt, Double_t mcPt, Double_t cent, Double_t ptRatio, Double_t vetoPt)
  {
    // Simple kinematic cuts
    if(pt < fPtMin || pt >= fPtMax)
      return kFALSE;
    if(cent < fCentMin || cent >= fCentMax)
      return kFALSE;

    // jet veto
    if(vetoPt >= fJetVetoPt)
      return kFALSE;

    // Lower MC percentage cut
    if(ptRatio < fCutLowerPercentageOffset)
      return kFALSE;

    // Value of the 2D cut line. We cut everything above that
    Double_t cutLineValue = fCut2DSlope*mcPt + fCut2DOffset;
    if(ptRatio > cutLineValue)
      return kFALSE;

    return kTRUE;
  }

  ~AliChargedJetsHadronCFCuts();
  TString     fCutName;                              ///< name of this cut
  TString     fOutputName;                           ///< array name that is used to output objects associated with this cuts
  Double_t    fPtMin;                                ///< valid for jets above this pT
  Double_t    fPtMax;                                ///< valid for jets below this pT
  Double_t    fCentMin;                              ///< valid for centralities above
  Double_t    fCentMax;                              ///< valid for centralities below
  Double_t    fJetVetoPt;                            ///< jet veto pt

  Double_t    fCutLowerPercentageOffset;             ///< cut value
  Double_t    fCut2DOffset;                          ///< cut value
  Double_t    fCut2DSlope;                           ///< cut value

  Int_t       fAcceptedJets;                         ///< temporary var that holds how many jets passed
  Int_t       fArrayIndex;                           ///< array index that holds the output array index
};

//###############################################################################################################################################3

/**
 * \class AliAnalysisTaskChargedJetsHadronCF
 * \brief Support task for (charged) jet-hadron correlations
 *
 * This task selects the jets and optionally the particles which are saved as a TClonesArray to the event
 * and which are read by a correlation task. The tasks does a special event selection (e.g. dijet events)
 * and jet selection (e.g. fakefactor rejection). In addition, it fills auxiliary histograms
 *
 * \author Ruediger Haake <ruediger.haake@cern.ch>, CERN
 * \date Apr 21, 2016
 */
//
class AliAnalysisTaskChargedJetsHadronCF : public AliAnalysisTaskEmcalJet {
 public:

  AliAnalysisTaskChargedJetsHadronCF();
  AliAnalysisTaskChargedJetsHadronCF(const char *name);
  virtual ~AliAnalysisTaskChargedJetsHadronCF();

  void                        UserCreateOutputObjects();
  void                        Terminate(Option_t *option);

  // ######### SETTERS/GETTERS
  void                        ActivateJetEmbedding(const char* embArray, const char* embTrackArray, Double_t maxDistance, Int_t numMatchedJets)
  {
    fJetEmbeddingMaxDistance      = maxDistance;
    fJetEmbeddingArrayName        = embArray;
    fJetEmbeddingTrackArrayName   = embTrackArray;
    fJetEmbeddingNumMatchedJets   = numMatchedJets;
  }
  void                        AddJetEmbeddingCut(const char* cutName, const char* outputName, Double_t minPt, Double_t maxPt, Double_t minCent, Double_t maxCent, Double_t lowerOffset, Double_t offset2D, Double_t slope2D, Double_t jetVetoPt)
  {
    AliChargedJetsHadronCFCuts tmpCut(cutName, outputName, minPt, maxPt, minCent, maxCent, lowerOffset, offset2D, slope2D, jetVetoPt);
    fJetEmbeddingCuts.push_back(tmpCut);
  }

  void                        SetJetVetoArrayName(const char* name)   { fJetVetoArrayName = name; }
  void                        SetJetVetoJetByJet(Bool_t val)          { fJetVetoJetByJet = val; }
  void                        SetUsePerTrackMCPercentage(Bool_t val)   { fJetEmbeddingUsePerTrackMCPercentage = val; }
  void                        SetUseBgrdForMCPercentage(Bool_t val)   { fJetEmbeddingUseBgrdForMCPercentage = val; }
  void                        SetCreateEmbeddingPtPlotPerCut(Bool_t val)   { fJetEmbeddingCreatePtPlotPerCut = val; }
  void                        SetConstPtFilterBit(Int_t val)   { fConstPtFilterBit = val; }
  void                        SetNumberOfCentralityBins(Int_t val)   { fNumberOfCentralityBins = val; }
  void                        SetJetParticleArrayName(const char* name)   { fJetParticleArrayName = name; }
  void                        SetTrackParticleArrayName(const char* name) { fTrackParticleArrayName = name; }

  void                        SetJetOutputMode(Int_t mode) {fJetOutputMode = mode;}
  void                        ActivateEventExtraction(Double_t percentage, Double_t minJetPt, Double_t maxJetPt) {fEventExtractionPercentage = percentage; fEventExtractionMinJetPt = minJetPt; fEventExtractionMaxJetPt = maxJetPt;}
  void                        SetTrackExtractionPercentagePower(Double_t val)   { fTrackExtractionPercentagePower = val; }

 protected:
  void                        ExecOnce();
  Bool_t                      Run();

  // ######### META FUNCTIONS
  void                        BinLogAxis(const THn *h, Int_t axisNumber);
  void                        AddEventToTree();
  void                        AddJetToOutputArray(AliEmcalJet* jet, Int_t arrayIndex, Int_t& jetsAlreadyInArray);
  void                        AddTrackToOutputArray(AliVTrack* track);
  void                        AddTrackToTree(AliVTrack* track);
  void                        FillHistogramsTracks(AliVTrack* track);
  void                        FillHistogramsJets(AliEmcalJet* jet, const char* cutName);
  Bool_t                      IsJetSelected(AliEmcalJet* jet);

  AliJetContainer            *fJetsCont;                                //!<! Jets
  AliTrackContainer          *fTracksCont;                              //!<! Tracks
  Double_t                    fEventExtractionPercentage;               ///< percentage of events that is recorded
  Double_t                    fEventExtractionMinJetPt;                 ///< minimum jet pt of recorded events
  Double_t                    fEventExtractionMaxJetPt;                 ///< maximum jet pt of recorded events

  Int_t                       fConstPtFilterBit;                        ///< For const pt plot, filter bit
  Int_t                       fNumberOfCentralityBins;                  ///< Number of centrality bins
  std::vector<TClonesArray*>  fJetsOutput;                              //!<! vector of arrays of basic correlation particles attached to the event (jets)
  TClonesArray               *fTracksOutput;                            //!<! Array of basic correlation particles attached to the event (tracks)
  TString                     fJetParticleArrayName;                    ///< Name of fJetsOutput array (if one uses only one)
  TString                     fTrackParticleArrayName;                  ///< Name of fTracksOutput array
  TClonesArray               *fJetEmbeddingArray;                       //!<! Array of generated jets imported into task (for embedding)
  TString                     fJetEmbeddingArrayName;                   ///< Name of array used to match jets
  TString                     fJetEmbeddingTrackArrayName;              ///< Name of array used to match tracks of jets
  Double_t                    fJetEmbeddingMaxDistance;                 ///< Max distance allowed to accept an embedded jet
  Int_t                       fJetEmbeddingNumMatchedJets;              ///< Number of matched leading jets that will be used
  Bool_t                      fJetEmbeddingUsePerTrackMCPercentage;     ///< When cutting on MC percentage, calculate it per track and not for all MC tracks
  Bool_t                      fJetEmbeddingUseBgrdForMCPercentage;      ///< When cutting on MC percentage, use bgrd. corr to calculate MC percentage
  Bool_t                      fJetEmbeddingCreatePtPlotPerCut;          ///< create TH3 per cut or only once
  std::vector<AliChargedJetsHadronCFCuts> fJetEmbeddingCuts;            ///< Cuts used in jet embedding

  TClonesArray               *fJetVetoArray;                            //!<! Array of jets imported into task used for veto a matching/embedding
  TString                     fJetVetoArrayName;                        ///< Name of array used for veto jets
  Bool_t                      fJetVetoJetByJet;                         ///< If true, the jet veto will be applied on a jet-by-jet basis
  std::vector<AliEmcalJet*>   fMatchedJets;                             ///< Jets matched in an event (embedded)
  std::vector<AliEmcalJet*>   fMatchedJetsReference;                    ///< Jets matched in an event (reference)
  TRandom3*                   fRandom;                                  ///< random number generator
  TTree*                      fTracksTree;                              //!<! Tree of extracted jets
  AliBasicParticle*           fTreeBufferTrack;                         //!<! Tree of extracted jets (buffer)
  AliAODPid*                  fTreeBufferPID;                           //!<! Tree of extracted jets (buffer)
  Int_t                       fTreeBufferPDG;                           //!<! Tree of extracted jets (buffer)
  Double_t                    fTrackExtractionPercentagePower;          ///< Extraction percentage for tracks

  // Criteria for the selection of jets that are passed to the correlation task
  Int_t                       fJetOutputMode;                           ///< mode which jets are written to array (0: all accepted, 1: leading,  2: subleading, 3: leading+subleading)

  // Event properties
  AliEmcalJet*                fLeadingJet;                              //!<!  leading jet (calculated event-by-event)
  AliEmcalJet*                fSubleadingJet;                           //!<!  subleading jet (calculated event-by-event)
  AliEmcalJet*                fInitialPartonMatchedJet1;                //!<!  On PYTHIA data and fJetOutputMode=6, this holds the PDG code of the initial collisions that was matched to this jet
  AliEmcalJet*                fInitialPartonMatchedJet2;                //!<!  On PYTHIA data and fJetOutputMode=6, this holds the PDG code of the initial collisions that was matched to this jet
  Int_t                       fAcceptedJets;                            //!<!  number accepted jets (calculated event-by-event)
  Int_t                       fAcceptedTracks;                          //!<!  number accepted tracks (calculated event-by-event)

  // ######### HISTOGRAM FUNCTIONS
  void                        FillHistogram(const char * key, Double_t x);
  void                        FillHistogram(const char * key, Double_t x, Double_t y);
  void                        FillHistogram(const char * key, Double_t x, Double_t y, Double_t add);
  void                        FillHistogram3D(const char * key, Double_t x, Double_t y, Double_t z, Double_t add = 0);

  template <class T> T*       AddHistogram1D(const char* name = "CustomHistogram", const char* title = "NO_TITLE", const char* options = "", Int_t xBins = 100, Double_t xMin = 0.0, Double_t xMax = 20.0, const char* xTitle = "x axis", const char* yTitle = "y axis");
  template <class T> T*       AddHistogram2D(const char* name = "CustomHistogram", const char* title = "NO_TITLE", const char* options = "", Int_t xBins = 100, Double_t xMin = 0.0, Double_t xMax = 20.0, Int_t yBins = 100, Double_t yMin = 0.0, Double_t yMax = 20.0,  const char* xTitle = "x axis", const char* yTitle = "y axis", const char* zTitle = "z axis");
  template <class T> T*       AddHistogram3D(const char* name = "CustomHistogram", const char* title = "NO_TITLE", const char* options = "", Int_t xBins = 100, Double_t xMin = 0.0, Double_t xMax = 20.0, Int_t yBins = 100, Double_t yMin = 0.0, Double_t yMax = 20.0, Int_t zBins = 100, Double_t zMin = 0.0, Double_t zMax = 20.0, const char* xTitle = "x axis", const char* yTitle = "y axis", const char* zTitle = "z axis");

  // ######### HELPER FUNCTIONS
  void                        CalculateJetType(AliEmcalJet* jet, Int_t& typeIC, Int_t& typeHM);
  void                        GetTrackMCRatios(AliEmcalJet* jet, AliEmcalJet* mcJet, Double_t& trackRatio, Double_t& ptRatio);
  AliEmcalJet*                GetVetoJet(AliEmcalJet* jet);
  AliEmcalJet*                GetLeadingVetoJet();

  AliEmcalJet*                GetReferenceJet(AliEmcalJet* jet);
  Bool_t                      IsTrackInCone(AliVParticle* track, Double_t eta, Double_t phi, Double_t radius);
  void                        GetInitialCollisionJets();
  void                        GetMatchingJets();

  void                        GetLeadingJets(const char* opt, AliEmcalJet*& jetLeading, AliEmcalJet*& jetSubLeading);
  void                        GetLeadingJetsInArray(TClonesArray* arr, const char* opt, AliEmcalJet*& jetLeading, AliEmcalJet*& jetSubLeading);
  void                        CalculateEventProperties();

 private:
  AliAnalysisTaskChargedJetsHadronCF(const AliAnalysisTaskChargedJetsHadronCF&);            // not implemented
  AliAnalysisTaskChargedJetsHadronCF &operator=(const AliAnalysisTaskChargedJetsHadronCF&); // not implemented

  /// \cond CLASSIMP
  ClassDef(AliAnalysisTaskChargedJetsHadronCF, 11) // Charged jet+h analysis support task
  /// \endcond
};

#endif


text:
package action

import (
	"flag"
	"fmt"
)

type aclClone struct {
	*config
}

func AclCloneAction() Action {
	return &aclClone{
		config: &gConfig,
	}
}

func (a *aclClone) CommandFlags() *flag.FlagSet {
	return a.newFlagSet(FLAG_NONE)
}

func (a *aclClone) Run(args []string) error {
	if len(args) != 1 {
		return fmt.Errorf("A single ACL id must be specified")
	}

	client, err := a.consul.newACL()
	if err != nil {
		return err
	}

	writeOpts := a.consul.writeOptions()

	newid, _, err := client.Clone(args[0], writeOpts)
	if err != nil {
		return err
	}

	fmt.Println(newid)

	return nil
}


text:
package org.jbpm.formModeler.editor.client.resources.i18n;

import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.Messages;

public interface Constants extends Messages {

    public static final Constants INSTANCE = GWT.create(Constants.class);

    public String form_modeler_form();
    public String form_modeler_new_form();
    public String form_modeler_save();
    public String form_modeler_title(String name);
    public String form_modeler_successfully_saved(String name);
    public String form_modeler_cannot_save(String name);
    public String form_modeler_cannot_load_form(String name);
    public String form_modeler_delete();
    public String form_modeler_confirm_delete();
    public String formResourceTypeDescription();
}


text:
package com.jetbrains.python;

import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.util.ref.GCWatcher;
import com.jetbrains.python.fixtures.PyTestCase;
import com.jetbrains.python.inspections.PyDeprecationInspection;
import com.jetbrains.python.psi.PyFile;
import com.jetbrains.python.psi.PyFunction;

public class PyDeprecationTest extends PyTestCase {
  @Override
  protected void setUp() throws Exception {
    super.setUp();
    myFixture.setCaresAboutInjection(false);
  }

  public void testFunction() {
    myFixture.configureByText(PythonFileType.INSTANCE,
                              "def getstatus(file):\n" +
                              "    \"\"\"Return output of \"ls -ld <file>\" in a string.\"\"\"\n" +
                              "    import warnings\n" +
                              "    warnings.warn(\"commands.getstatus() is deprecated\", DeprecationWarning, 2)\n" +
                              "    return getoutput('ls -ld' + mkarg(file))");
    PyFunction getstatus = ((PyFile) myFixture.getFile()).findTopLevelFunction("getstatus");
    assertEquals("commands.getstatus() is deprecated", getstatus.getDeprecationMessage());
  }

  public void testFunctionStub() {
    myFixture.configureByFile("deprecation/functionStub.py");
    PyFile file = (PyFile)myFixture.getFile();
    assertEquals("commands.getstatus() is deprecated", file.findTopLevelFunction("getstatus").getDeprecationMessage());
    GCWatcher.tracking(file.findTopLevelFunction("getstatus"), ((PsiFileImpl)file).getTreeElement()).ensureCollected();
    assertNotParsed(file);

    assertEquals("commands.getstatus() is deprecated", file.findTopLevelFunction("getstatus").getDeprecationMessage());
    assertNotParsed(file);
  }

  public void testDeprecatedAsFallback() {
    myFixture.enableInspections(PyDeprecationInspection.class);
    myFixture.configureByFiles("deprecation/deprecatedAsFallback.py", "deprecation/tmp.py");
    myFixture.checkHighlighting(true, false, false);
  }

  public void testDeprecatedFallback2() {
    myFixture.enableInspections(PyDeprecationInspection.class);
    myFixture.configureByFiles("deprecation/deprecatedFallback2.py", "deprecation/tmp.py", "deprecation/deprecatedAsFallback.py");
    myFixture.checkHighlighting(true, false, false);
  }

  public void testDeprecatedProperty() {
    myFixture.enableInspections(PyDeprecationInspection.class);
    myFixture.configureByFile("deprecation/deprecatedProperty.py");
    myFixture.checkHighlighting(true, false, false);
  }

  public void testDeprecatedImport() {
    myFixture.enableInspections(PyDeprecationInspection.class);
    myFixture.configureByFiles("deprecation/deprecatedImport.py", "deprecation/deprecatedModule.py");
    myFixture.checkHighlighting(true, false, false);
  }

  public void testFileStub() {
    myFixture.configureByFile("deprecation/deprecatedModule.py");
    PyFile file = (PyFile)myFixture.getFile();
    assertEquals("the deprecated module is deprecated; use a non-deprecated module instead", file.getDeprecationMessage());
    GCWatcher.tracking(((PsiFileImpl)file).getStub(), ((PsiFileImpl)file).getTreeElement()).ensureCollected();

    assertNotParsed(file);

    assertEquals("the deprecated module is deprecated; use a non-deprecated module instead", file.getDeprecationMessage());
    assertNotParsed(file);
  }

  // PY-38101
  public void testDeprecatedElementInPyi() {
    myFixture.enableInspections(PyDeprecationInspection.class);
    myFixture.copyDirectoryToProject("deprecation/deprecatedElementInPyi", "");
    myFixture.configureByFile("a.py");
    myFixture.checkHighlighting(true, false, false);
  }

  public void testAbcDeprecatedAbstracts() {
    myFixture.enableInspections(PyDeprecationInspection.class);
    myFixture.configureByFile("deprecation/abcDeprecatedAbstracts.py");
    myFixture.checkHighlighting(true, false, false);
  }
}


text:
'use strict';

const Tracer = require('./tracer');

const {
  refineByType
} = require('../../tracer_manager/util/index');

class DirectedGraphTracer extends Tracer {
  static getClassName() {
    return 'DirectedGraphTracer';
  }

  constructor(name) {
    super(name);

    if (this.isNew) initView(this);
  }

  _setTreeData(G, root) {
    this.manager.pushStep(this.capsule, {
      type: 'setTreeData',
      arguments: arguments
    });
    return this;
  }

  _visit(target, source) {
    this.manager.pushStep(this.capsule, {
      type: 'visit',
      target: target,
      source: source
    });
    return this;
  }

  _leave(target, source) {
    this.manager.pushStep(this.capsule, {
      type: 'leave',
      target: target,
      source: source
    });
    return this;
  }

  _setNodePositions(positions) {
    this.manager.pushStep(this.capsule, {
      type: 'setNodePositions',
      positions: positions
    });
    return this;
  }

  processStep(step, options) {
    switch (step.type) {
      case 'setTreeData':
        this.setTreeData.apply(this, step.arguments);
        break;
      case 'setNodePositions':
        $.each(this.graph.nodes(), (i, node) => {
          if (i >= step.positions.length) return false;
          const position = step.positions[i];
          node.x = position.x;
          node.y = position.y;
        });
        break;
      case 'visit':
      case 'leave':
        var visit = step.type == 'visit';
        var targetNode = this.graph.nodes(this.n(step.target));
        var color = visit ? this.color.visited : this.color.left;
        targetNode.color = color;
        if (step.source !== undefined) {
          var edgeId = this.e(step.source, step.target);
          var edge = this.graph.edges(edgeId);
          edge.color = color;
          this.graph.dropEdge(edgeId).addEdge(edge);
        }
        if (this.logTracer) {
          var source = step.source;
          if (source === undefined) source = '';
          this.logTracer.print(visit ? source + ' -> ' + step.target : source + ' <- ' + step.target);
        }
        break;
      default:
        super.processStep(step, options);
    }
  }

  setTreeData(G, root, undirected) {
    var tracer = this;

    root = root || 0;
    var maxDepth = -1;

    var chk = new Array(G.length);
    var getDepth = function (node, depth) {
      if (chk[node]) throw "the given graph is not a tree because it forms a circuit";
      chk[node] = true;
      if (maxDepth < depth) maxDepth = depth;
      for (var i = 0; i < G[node].length; i++) {
        if (G[node][i]) getDepth(i, depth + 1);
      }
    };
    getDepth(root, 1);

    if (this.setData(G, undirected)) return true;

    var place = function (node, x, y) {
      var temp = tracer.graph.nodes(tracer.n(node));
      temp.x = x;
      temp.y = y;
    };

    var wgap = 1 / (maxDepth - 1);
    var dfs = function (node, depth, top, bottom) {
      place(node, top + bottom, depth * wgap);
      var children = 0;
      for (var i = 0; i < G[node].length; i++) {
        if (G[node][i]) children++;
      }
      var vgap = (bottom - top) / children;
      var cnt = 0;
      for (var i = 0; i < G[node].length; i++) {
        if (G[node][i]) dfs(i, depth + 1, top + vgap * cnt, top + vgap * ++cnt);
      }
    };
    dfs(root, 0, 0, 1);

    this.refresh();
  }

  setData(G, undirected) {
    if (super.setData.apply(this, arguments)) return true;
    this.graph.clear();
    const nodes = [];
    const edges = [];
    const unitAngle = 2 * Math.PI / G.length;
    let currentAngle = 0;
    for (let i = 0; i < G.length; i++) {
      currentAngle += unitAngle;
      nodes.push({
        id: this.n(i),
        label: '' + i,
        x: .5 + Math.sin(currentAngle) / 2,
        y: .5 + Math.cos(currentAngle) / 2,
        size: 1,
        color: this.color.default,
        weight: 0
      });

      if (undirected) {
        for (let j = 0; j <= i; j++) {
          const value = G[i][j] || G[j][i];
          if (value) {
            edges.push({
              id: this.e(i, j),
              source: this.n(i),
              target: this.n(j),
              color: this.color.default,
              size: 1,
              weight: refineByType(value)
            });
          }
        }
      } else {
        for (let j = 0; j < G[i].length; j++) {
          if (G[i][j]) {
            edges.push({
              id: this.e(i, j),
              source: this.n(i),
              target: this.n(j),
              color: this.color.default,
              size: 1,
              weight: refineByType(G[i][j])
            });
          }
        }
      }
    }

    this.graph.read({
      nodes: nodes,
      edges: edges
    });
    this.s.camera.goTo({
      x: 0,
      y: 0,
      angle: 0,
      ratio: 1
    });
    this.refresh();

    return false;
  }

  resize() {
    super.resize();

    this.s.renderers[0].resize();
    this.refresh();
  }

  refresh() {
    super.refresh();

    this.s.refresh();
  }

  clear() {
    super.clear();

    this.clearGraphColor();
    this.refresh();
  }

  clearGraphColor() {
    var tracer = this;

    this.graph.nodes().forEach(function (node) {
      node.color = tracer.color.default;
    });
    this.graph.edges().forEach(function (edge) {
      edge.color = tracer.color.default;
    });
  }

  n(v) {
    return 'n' + v;
  }

  e(v1, v2) {
    return 'e' + v1 + '_' + v2;
  }

  getColor(edge, source, target, settings) {
    var color = edge.color,
      edgeColor = settings('edgeColor'),
      defaultNodeColor = settings('defaultNodeColor'),
      defaultEdgeColor = settings('defaultEdgeColor');
    if (!color)
      switch (edgeColor) {
        case 'source':
          color = source.color || defaultNodeColor;
          break;
        case 'target':
          color = target.color || defaultNodeColor;
          break;
        default:
          color = defaultEdgeColor;
          break;
      }

    return color;
  }

  drawLabel(node, context, settings) {
    var fontSize,
      prefix = settings('prefix') || '',
      size = node[prefix + 'size'];

    if (size < settings('labelThreshold'))
      return;

    if (!node.label || typeof node.label !== 'string')
      return;

    fontSize = (settings('labelSize') === 'fixed') ?
      settings('defaultLabelSize') :
    settings('labelSizeRatio') * size;

    context.font = (settings('fontStyle') ? settings('fontStyle') + ' ' : '') +
      fontSize + 'px ' + settings('font');
    context.fillStyle = (settings('labelColor') === 'node') ?
      (node.color || settings('defaultNodeColor')) :
      settings('defaultLabelColor');

    context.textAlign = 'center';
    context.fillText(
      node.label,
      Math.round(node[prefix + 'x']),
      Math.round(node[prefix + 'y'] + fontSize / 3)
    );
  }

  drawArrow(edge, source, target, color, context, settings) {
    var prefix = settings('prefix') || '',
      size = edge[prefix + 'size'] || 1,
      tSize = target[prefix + 'size'],
      sX = source[prefix + 'x'],
      sY = source[prefix + 'y'],
      tX = target[prefix + 'x'],
      tY = target[prefix + 'y'],
      angle = Math.atan2(tY - sY, tX - sX),
      dist = 3;
    sX += Math.sin(angle) * dist;
    tX += Math.sin(angle) * dist;
    sY += -Math.cos(angle) * dist;
    tY += -Math.cos(angle) * dist;
    var aSize = Math.max(size * 2.5, settings('minArrowSize')),
      d = Math.sqrt(Math.pow(tX - sX, 2) + Math.pow(tY - sY, 2)),
      aX = sX + (tX - sX) * (d - aSize - tSize) / d,
      aY = sY + (tY - sY) * (d - aSize - tSize) / d,
      vX = (tX - sX) * aSize / d,
      vY = (tY - sY) * aSize / d;

    context.strokeStyle = color;
    context.lineWidth = size;
    context.beginPath();
    context.moveTo(sX, sY);
    context.lineTo(
      aX,
      aY
    );
    context.stroke();

    context.fillStyle = color;
    context.beginPath();
    context.moveTo(aX + vX, aY + vY);
    context.lineTo(aX + vY * 0.6, aY - vX * 0.6);
    context.lineTo(aX - vY * 0.6, aY + vX * 0.6);
    context.lineTo(aX + vX, aY + vY);
    context.closePath();
    context.fill();
  }

  drawOnHover(node, context, settings, next) {
    var tracer = this;

    context.setLineDash([5, 5]);
    var nodeIdx = node.id.substring(1);
    this.graph.edges().forEach(function (edge) {
      var ends = edge.id.substring(1).split("_");
      if (ends[0] == nodeIdx) {
        var color = '#0ff';
        var source = node;
        var target = tracer.graph.nodes('n' + ends[1]);
        tracer.drawArrow(edge, source, target, color, context, settings);
        if (next) next(edge, source, target, color, context, settings);
      } else if (ends[1] == nodeIdx) {
        var color = '#ff0';
        var source = tracer.graph.nodes('n' + ends[0]);
        var target = node;
        tracer.drawArrow(edge, source, target, color, context, settings);
        if (next) next(edge, source, target, color, context, settings);
      }
    });
  }
}

const initView = (tracer) => {
  tracer.s = tracer.capsule.s = new sigma({
    renderer: {
      container: tracer.$container[0],
      type: 'canvas'
    },
    settings: {
      minArrowSize: 8,
      defaultEdgeType: 'arrow',
      maxEdgeSize: 2.5,
      labelThreshold: 4,
      font: 'Roboto',
      defaultLabelColor: '#fff',
      zoomMin: 0.6,
      zoomMax: 1.2,
      skipErrors: true,
      minNodeSize: .5,
      maxNodeSize: 12,
      labelSize: 'proportional',
      labelSizeRatio: 1.3,
      funcLabelsDef(node, context, settings) {
        tracer.drawLabel(node, context, settings);
      },
      funcHoversDef(node, context, settings, next) {
        tracer.drawOnHover(node, context, settings, next);
      },
      funcEdgesArrow(edge, source, target, context, settings) {
        var color = tracer.getColor(edge, source, target, settings);
        tracer.drawArrow(edge, source, target, color, context, settings);
      }
    }
  });
  sigma.plugins.dragNodes(tracer.s, tracer.s.renderers[0]);
  tracer.graph = tracer.capsule.graph = tracer.s.graph;
};

sigma.canvas.labels.def = function (node, context, settings) {
  var func = settings('funcLabelsDef');
  if (func) {
    func(node, context, settings);
  }
};
sigma.canvas.hovers.def = function (node, context, settings) {
  var func = settings('funcHoversDef');
  if (func) {
    func(node, context, settings);
  }
};
sigma.canvas.edges.def = function (edge, source, target, context, settings) {
  var func = settings('funcEdgesDef');
  if (func) {
    func(edge, source, target, context, settings);
  }
};
sigma.canvas.edges.arrow = function (edge, source, target, context, settings) {
  var func = settings('funcEdgesArrow');
  if (func) {
    func(edge, source, target, context, settings);
  }
};

module.exports = DirectedGraphTracer;


text:
@interface MembersTableViewController ()

@end

@implementation MembersTableViewController {
    CoreDaoManager *dao;
    GroupManager *group;

    NSArray *members;
    User *owner;
    User *currentUser;
}

- (void)viewDidLoad {
    if (DEBUG) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    [super viewDidLoad];
    group = [GroupManager sharedInstance];
    dao = [CoreDaoManager sharedInstance];

    // Remove inviting member button if this user is not group owner.
    if (!group.isOwner) {
        self.navigationItem.rightBarButtonItem = nil;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    if (DEBUG) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    [super viewWillAppear:animated];
    [self loadMembersInfo];
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if(DEBUG) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    return 0.1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if(DEBUG) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(DEBUG) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    if (group.defaults.initial != InitialFinished) {
        return 0;
    }
    return (section == 0)? 1: members.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(DEBUG) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"membersIdentifier"
                                                            forIndexPath:indexPath];
    User *user = (indexPath.section == 0)? owner: [members objectAtIndex:indexPath.row];

    UILabel *nameEmailLabel = (UILabel *)[cell viewWithTag:1];
    UILabel *nodeLabel = (UILabel *)[cell viewWithTag:2];
    nameEmailLabel.text = [NSString stringWithFormat:@"%@ (%@)", user.name, user.email];
    nodeLabel.text = user.node;
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if(DEBUG) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    return (group.defaults.initial != InitialFinished)? nil: @" ";
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if(DEBUG) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)];
    headerView.backgroundColor = [UIColor clearColor];
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, headerView.bounds.size.width - 15, headerView.bounds.size.height)];
    nameLabel.text = (section == 0) ? @"Group Owner" : @"Group Members";
    [headerView addSubview:nameLabel];
    return headerView;
}

#pragma mark - Action
- (IBAction)exitMembers:(id)sender {
    if(DEBUG) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Service
- (void)loadMembersInfo {
    if(DEBUG) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    members = [dao.userDao findMembersExceptOwner:group.defaults.owner];
    owner = [dao.userDao getByEmail:group.defaults.owner];
    [self.tableView reloadData];
}

@end


text:
import React, { StatelessComponent } from 'react';
import styles from './styles.css';

export interface IPageFragment {
  __typename: string;
  title: string;
  body: {
    __typename: string;
    text: string;
  };
}

// tslint:disable-next-line:no-empty-interface
export interface IPageProps extends IPageFragment {}

const Page: StatelessComponent<IPageProps> = ({ title, body }) => (

{title}

);

export default Page;


text:
package org.gedcomx.rs.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientResponse;
import org.gedcomx.Gedcomx;
import org.gedcomx.links.SupportsLinks;
import org.gedcomx.rs.Rel;
import org.gedcomx.rt.GedcomxConstants;

import javax.ws.rs.HttpMethod;
import java.net.URI;

/**
 * @author Ryan Heaton
 */
public class RecordState extends GedcomxApplicationState<Gedcomx> {

  public RecordState(URI uri) {
    this(uri, new StateFactory());
  }

  private RecordState(URI uri, StateFactory stateFactory) {
    this(uri, stateFactory.loadDefaultClient(), stateFactory);
  }

  private RecordState(URI uri, Client client, StateFactory stateFactory) {
    this(ClientRequest.create().accept(GedcomxConstants.GEDCOMX_JSON_MEDIA_TYPE).build(uri, HttpMethod.GET), client, stateFactory);
  }

  private RecordState(ClientRequest request, Client client, StateFactory stateFactory) {
    this(request, client.handle(request), null, stateFactory);
  }

  public RecordState(ClientRequest request, ClientResponse response, String accessToken, StateFactory stateFactory) {
    super(request, response, accessToken, stateFactory);
  }

  @Override
  public String getSelfRel() {
    return Rel.RECORD;
  }

  @Override
  protected RecordState clone(ClientRequest request, ClientResponse response) {
    return new RecordState(request, response, this.accessToken, this.stateFactory);
  }

  @Override
  public RecordState ifSuccessful() {
    return (RecordState) super.ifSuccessful();
  }

  @Override
  public RecordState head(StateTransitionOption... options) {
    return (RecordState) super.head(options);
  }

  @Override
  public RecordState options(StateTransitionOption... options) {
    return (RecordState) super.options(options);
  }

  @Override
  public RecordState get(StateTransitionOption... options) {
    return (RecordState) super.get(options);
  }

  @Override
  public RecordState delete(StateTransitionOption... options) {
    return (RecordState) super.delete(options);
  }

  @Override
  public RecordState put(Gedcomx e, StateTransitionOption... options) {
    return (RecordState) super.put(e, options);
  }

  @Override
  public RecordState post(Gedcomx entity, StateTransitionOption... options) {
    return (RecordState) super.post(entity, options);
  }

  @Override
  protected Gedcomx loadEntity(ClientResponse response) {
    return response.getEntity(Gedcomx.class);
  }

  @Override
  protected SupportsLinks getMainDataElement() {
    return getEntity();
  }

}


text:
import rokka from 'rokka'

let client = rokka()
const max_age = 3600 * 72
export const ROKKA_DASHBOARD_TOKEN = 'rokka-dashboard-token'
export const ROKKA_DASHBOARD_ORG = 'rokka-dashboard-org'
export const ROKKA_DASHBOARD_IPS = 'rokka-dashboard-ips'

export const apiTokenGetCallback = () => {
  return localStorage.getItem(ROKKA_DASHBOARD_TOKEN)
}

export function authenticate(apiKey) {
  client = rokka({
    apiKey,
    apiVersion: 1,
    apiTokenOptions: {
      //no_ip_protection: true, // not sure about this
      expires_in: max_age,
      renewable: true,
      ips: `request_ip,${localStorage.getItem(ROKKA_DASHBOARD_IPS) || ''}`
    },
    apiTokenRefreshTime: max_age - 3600 * 24, // refresh it after a day
    apiTokenGetCallback: apiTokenGetCallback,
    apiTokenSetCallback: (token, payload) => {
      localStorage.setItem(ROKKA_DASHBOARD_TOKEN, token)
      if (payload && payload.ips) {
        // store the ips and remember the last 8 (max is 10 on the API side)
        localStorage.setItem(ROKKA_DASHBOARD_IPS, payload.ips.slice(0, 8).join(','))
      }
    }
  })
}

export function resetClient() {
  client = rokka()
}

export default () => client

const cloudFrontDistributionReady = true // TODO: Check if it's ready after first login, to avoid broken images
export function getRenderUrl(organization, hash, format, stack, options) {
  const url = client.render.getUrl(organization, hash, format, stack, options)
  if (!cloudFrontDistributionReady) {
    return url.replace('.rokka.io/', '.render.rokka.io/render/') + '?_docache'
  }
  return url
}


text:
import threading
import multiprocessing
import time
import logging

logging.basicConfig()
logger = logging.getLogger("thread_is_slow")
logger.setLevel(logging.DEBUG)

LOOP = 50
NUM = 10000000
elapsed_time = {}

def count(n):
    while n > 0:
        n = n - 1

# Sequential execution
logger.info('Sequential execution')
start = time.time()
for i in xrange(LOOP):
    count(NUM)
stop = time.time()
elapsed_time['Sequential'] = stop - start

# Threaded exeution
logger.info('Threaded exeution')
start = time.time()
threads = []
for i in xrange(LOOP):
    thread = threading.Thread(target=count, args=(NUM,))
    thread.start()
    threads.append(thread)
for t in threads:
    t.join()
stop = time.time()
elapsed_time['Threaded'] = stop - start

# Processed exeution
logger.info('Processed exeution')
start = time.time()
processes = []
for i in xrange(LOOP):
    process = multiprocessing.Process(target=count, args=(NUM,))
    process.start()
    processes.append(process)
for p in processes:
    p.join()
stop = time.time()
elapsed_time['Processed'] = stop - start

# Multiprocessing pool execution
logger.info('Multiprocessing pool execution')
start = time.time()
pool = multiprocessing.Pool(processes=2)
for i in xrange(LOOP):
    pool.apply_async(count, (NUM, ))
pool.close()
pool.join()
stop = time.time()
elapsed_time['ProcessPool(2)'] = stop - start

logger.info('Multiprocessing pool(4) execution')
start = time.time()
pool = multiprocessing.Pool(processes=4)
for i in xrange(LOOP):
    pool.apply_async(count, (NUM, ))
pool.close()
pool.join()
stop = time.time()
elapsed_time['ProcessPool(4)'] = stop - start

logger.info('Multiprocessing pool(8) execution')
start = time.time()
pool = multiprocessing.Pool(processes=8)
for i in xrange(LOOP):
    pool.apply_async(count, (NUM, ))
pool.close()
pool.join()
stop = time.time()
elapsed_time['ProcessPool(8)'] = stop - start

logger.info('Multiprocessing pool(16) execution')
start = time.time()
pool = multiprocessing.Pool(processes=16)
for i in xrange(LOOP):
    pool.apply_async(count, (NUM, ))
pool.close()
pool.join()
stop = time.time()
elapsed_time['ProcessPool(16)'] = stop - start

# Compare performance
for key, value in sorted(elapsed_time.iteritems()):
    logger.info("\t" + key + "\t" + str(value))


text:
import unittest

import numpy
import numpy.linalg
from numpy.testing import assert_array_almost_equal
from numpy.testing import dec, assert_array_equal, assert_allclose
from numpy import inf
from six.moves import xrange

import theano
from theano import tensor, function
from theano.tensor.basic import _allclose
from theano.tests.test_rop import break_op
from theano.tests import unittest_tools as utt
from theano import config

from theano.tensor.nlinalg import ( MatrixInverse,
                                    matrix_inverse,
                                    MatrixPinv,
                                    pinv,
                                    AllocDiag,
                                    alloc_diag,
                                    ExtractDiag,
                                    extract_diag,
                                    diag,
                                    trace,
                                    Det,
                                    det,
                                    Eig,
                                    eig,
                                    Eigh,
                                    EighGrad,
                                    eigh,
                                    matrix_dot,
                                    _zero_disconnected,
                                    qr,
                                    matrix_power,
                                    norm,
                                    svd
                                    )

from nose.plugins.skip import SkipTest
from nose.plugins.attrib import attr
from nose.tools import assert_raises

def test_pseudoinverse_correctness():
    rng = numpy.random.RandomState(utt.fetch_seed())
    d1 = rng.randint(4) + 2
    d2 = rng.randint(4) + 2
    r = rng.randn(d1, d2).astype(theano.config.floatX)

    x = tensor.matrix()
    xi = pinv(x)

    ri = function([x], xi)(r)
    assert ri.shape[0] == r.shape[1]
    assert ri.shape[1] == r.shape[0]
    assert ri.dtype == r.dtype
    # Note that pseudoinverse can be quite unprecise so I prefer to compare
    # the result with what numpy.linalg returns
    assert _allclose(ri, numpy.linalg.pinv(r))

class test_MatrixInverse(utt.InferShapeTester):
    def setUp(self):
        super(test_MatrixInverse, self).setUp()
        self.op_class = MatrixInverse
        self.op = matrix_inverse
        self.rng = numpy.random.RandomState(utt.fetch_seed())

    def test_inverse_correctness(self):

        r = self.rng.randn(4, 4).astype(theano.config.floatX)

        x = tensor.matrix()
        xi = self.op(x)

        ri = function([x], xi)(r)
        assert ri.shape == r.shape
        assert ri.dtype == r.dtype

        rir = numpy.dot(ri, r)
        rri = numpy.dot(r, ri)

        assert _allclose(numpy.identity(4), rir), rir
        assert _allclose(numpy.identity(4), rri), rri

    def test_infer_shape(self):

        r = self.rng.randn(4, 4).astype(theano.config.floatX)

        x = tensor.matrix()
        xi = self.op(x)

        self._compile_and_check([x], [xi], [r],
                                self.op_class, warn=False)

def test_matrix_dot():
    rng = numpy.random.RandomState(utt.fetch_seed())
    n = rng.randint(4) + 2
    rs = []
    xs = []
    for k in xrange(n):
        rs += [rng.randn(4, 4).astype(theano.config.floatX)]
        xs += [tensor.matrix()]
    sol = matrix_dot(*xs)

    theano_sol = function(xs, sol)(*rs)
    numpy_sol = rs[0]
    for r in rs[1:]:
        numpy_sol = numpy.dot(numpy_sol, r)

    assert _allclose(numpy_sol, theano_sol)

def test_qr_modes():
    rng = numpy.random.RandomState(utt.fetch_seed())

    A = tensor.matrix("A", dtype=theano.config.floatX)
    a = rng.rand(4, 4).astype(theano.config.floatX)

    f = function([A], qr(A))
    t_qr = f(a)
    n_qr = numpy.linalg.qr(a)
    assert _allclose(n_qr, t_qr)

    for mode in ["reduced", "r", "raw", "full", "economic"]:
        f = function([A], qr(A, mode))
        t_qr = f(a)
        n_qr = numpy.linalg.qr(a, mode)
        if isinstance(n_qr, (list, tuple)):
            assert _allclose(n_qr[0], t_qr[0])
            assert _allclose(n_qr[1], t_qr[1])
        else:
            assert _allclose(n_qr, t_qr)

    try:
        n_qr = numpy.linalg.qr(a, "complete")
        f = function([A], qr(A, "complete"))
        t_qr = f(a)
        assert _allclose(n_qr, t_qr)
    except TypeError as e:
        assert "name 'complete' is not defined" in str(e)

def test_svd():
    rng = numpy.random.RandomState(utt.fetch_seed())
    A = tensor.matrix("A", dtype=theano.config.floatX)
    U, V, T = svd(A)
    fn = function([A], [U, V, T])
    a = rng.rand(4, 4).astype(theano.config.floatX)
    n_u, n_v, n_t = numpy.linalg.svd(a)
    t_u, t_v, t_t = fn(a)

    assert _allclose(n_u, t_u)
    assert _allclose(n_v, t_v)
    assert _allclose(n_t, t_t)

def test_inverse_singular():
    singular = numpy.array([[1, 0, 0]] + [[0, 1, 0]] * 2,
                           dtype=theano.config.floatX)
    a = tensor.matrix()
    f = function([a], matrix_inverse(a))
    try:
        f(singular)
    except numpy.linalg.LinAlgError:
        return
    assert False

def test_inverse_grad():
    rng = numpy.random.RandomState(utt.fetch_seed())
    r = rng.randn(4, 4)
    tensor.verify_grad(matrix_inverse, [r], rng=numpy.random)

    rng = numpy.random.RandomState(utt.fetch_seed())

    r = rng.randn(4, 4)
    tensor.verify_grad(matrix_inverse, [r], rng=numpy.random)

def test_det():
    rng = numpy.random.RandomState(utt.fetch_seed())

    r = rng.randn(5, 5).astype(config.floatX)
    x = tensor.matrix()
    f = theano.function([x], det(x))
    assert numpy.allclose(numpy.linalg.det(r), f(r))

def test_det_grad():
    rng = numpy.random.RandomState(utt.fetch_seed())

    r = rng.randn(5, 5).astype(config.floatX)
    tensor.verify_grad(det, [r], rng=numpy.random)

def test_det_shape():
    rng = numpy.random.RandomState(utt.fetch_seed())
    r = rng.randn(5, 5).astype(config.floatX)

    x = tensor.matrix()
    f = theano.function([x], det(x))
    f_shape = theano.function([x], det(x).shape)
    assert numpy.all(f(r).shape == f_shape(r))

class test_diag(unittest.TestCase):
    """
    Test that linalg.diag has the same behavior as numpy.diag.
    numpy.diag has two behaviors:
    (1) when given a vector, it returns a matrix with that vector as the
    diagonal.
    (2) when given a matrix, returns a vector which is the diagonal of the
    matrix.

    (1) and (2) are tested by test_alloc_diag and test_extract_diag
    respectively.

    test_diag test makes sure that linalg.diag instantiates
    the right op based on the dimension of the input.
    """
    def __init__(self, name, mode=None, shared=tensor._shared,
                 floatX=None, type=tensor.TensorType):
        self.mode = mode
        self.shared = shared
        if floatX is None:
            floatX = config.floatX
        self.floatX = floatX
        self.type = type
        super(test_diag, self).__init__(name)

    def test_alloc_diag(self):
        rng = numpy.random.RandomState(utt.fetch_seed())
        x = theano.tensor.vector()
        g = alloc_diag(x)
        f = theano.function([x], g)

        # test "normal" scenario (5x5 matrix) and special cases of 0x0 and 1x1
        for shp in [5, 0, 1]:
            m = rng.rand(shp).astype(self.floatX)
            v = numpy.diag(m)
            r = f(m)
            # The right matrix is created
            assert (r == v).all()

        # Test we accept only vectors
        xx = theano.tensor.matrix()
        ok = False
        try:
            alloc_diag(xx)
        except TypeError:
            ok = True
        assert ok

        # Test infer_shape
        f = theano.function([x], g.shape)
        topo = f.maker.fgraph.toposort()
        if config.mode != 'FAST_COMPILE':
            assert sum([node.op.__class__ == AllocDiag for node in topo]) == 0
        for shp in [5, 0, 1]:
            m = rng.rand(shp).astype(self.floatX)
            assert (f(m) == m.shape).all()

    def test_alloc_diag_grad(self):
        rng = numpy.random.RandomState(utt.fetch_seed())
        x = rng.rand(5)
        tensor.verify_grad(alloc_diag, [x], rng=rng)

    def test_diag(self):
        # test that it builds a matrix with given diagonal when using
        # vector inputs
        x = theano.tensor.vector()
        y = diag(x)
        assert y.owner.op.__class__ == AllocDiag

        # test that it extracts the diagonal when using matrix input
        x = theano.tensor.matrix()
        y = extract_diag(x)
        assert y.owner.op.__class__ == ExtractDiag

        # other types should raise error
        x = theano.tensor.tensor3()
        ok = False
        try:
            y = extract_diag(x)
        except TypeError:
            ok = True
        assert ok

    # not testing the view=True case since it is not used anywhere.
    def test_extract_diag(self):
        rng = numpy.random.RandomState(utt.fetch_seed())
        m = rng.rand(2, 3).astype(self.floatX)
        x = self.shared(m)
        g = extract_diag(x)
        f = theano.function([], g)
        assert [isinstance(node.inputs[0].type, self.type)
                for node in f.maker.fgraph.toposort()
                if isinstance(node.op, ExtractDiag)] == [True]

        for shp in [(2, 3), (3, 2), (3, 3), (1, 1), (0, 0)]:
            m = rng.rand(*shp).astype(self.floatX)
            x.set_value(m)
            v = numpy.diag(m)
            r = f()
            # The right diagonal is extracted
            assert (r == v).all()

        # Test we accept only matrix
        xx = theano.tensor.vector()
        ok = False
        try:
            extract_diag(xx)
        except TypeError:
            ok = True
        assert ok

        # Test infer_shape
        f = theano.function([], g.shape)
        topo = f.maker.fgraph.toposort()
        if config.mode != 'FAST_COMPILE':
            assert sum([node.op.__class__ == ExtractDiag
                        for node in topo]) == 0
        for shp in [(2, 3), (3, 2), (3, 3)]:
            m = rng.rand(*shp).astype(self.floatX)
            x.set_value(m)
            assert f() == min(shp)

    def test_extract_diag_grad(self):
        rng = numpy.random.RandomState(utt.fetch_seed())
        x = rng.rand(5, 4).astype(self.floatX)
        tensor.verify_grad(extract_diag, [x], rng=rng)

    @attr('slow')
    def test_extract_diag_empty(self):
        c = self.shared(numpy.array([[], []], self.floatX))
        f = theano.function([], extract_diag(c), mode=self.mode)

        assert [isinstance(node.inputs[0].type, self.type)
                for node in f.maker.fgraph.toposort()
                if isinstance(node.op, ExtractDiag)] == [True]

def test_trace():
    rng = numpy.random.RandomState(utt.fetch_seed())
    x = theano.tensor.matrix()
    g = trace(x)
    f = theano.function([x], g)

    for shp in [(2, 3), (3, 2), (3, 3)]:
        m = rng.rand(*shp).astype(config.floatX)
        v = numpy.trace(m)
        assert v == f(m)

    xx = theano.tensor.vector()
    ok = False
    try:
        trace(xx)
    except TypeError:
        ok = True
    assert ok

class test_Eig(utt.InferShapeTester):
    op_class = Eig
    op = eig
    dtype = 'float64'

    def setUp(self):
        super(test_Eig, self).setUp()
        self.rng = numpy.random.RandomState(utt.fetch_seed())
        self.A = theano.tensor.matrix(dtype=self.dtype)
        X = numpy.asarray(self.rng.rand(5, 5),
                          dtype=self.dtype)
        self.S = X.dot(X.T)

    def test_infer_shape(self):
        A = self.A
        S = self.S
        self._compile_and_check([A],  # theano.function inputs
                                self.op(A),  # theano.function outputs
                                # S must be square
                                [S],
                                self.op_class,
                                warn=False)

    def test_eval(self):
        A = theano.tensor.matrix(dtype=self.dtype)
        self.assertEqual([e.eval({A: [[1]]}) for e in self.op(A)],
                          [[1.0], [[1.0]]])
        x = [[0, 1], [1, 0]]
        w, v = [e.eval({A: x}) for e in self.op(A)]
        assert_array_almost_equal(numpy.dot(x, v), w * v)

class test_Eigh(test_Eig):
    op = staticmethod(eigh)

    def test_uplo(self):
        S = self.S
        a = theano.tensor.matrix(dtype=self.dtype)
        wu, vu = [out.eval({a: S}) for out in self.op(a, 'U')]
        wl, vl = [out.eval({a: S}) for out in self.op(a, 'L')]
        assert_array_almost_equal(wu, wl)
        assert_array_almost_equal(vu * numpy.sign(vu[0, :]),
                                  vl * numpy.sign(vl[0, :]))

    def test_grad(self):
        S = self.S
        utt.verify_grad(lambda x: self.op(x)[0], [S], rng=self.rng)
        utt.verify_grad(lambda x: self.op(x)[1], [S], rng=self.rng)
        utt.verify_grad(lambda x: self.op(x, 'U')[0], [S], rng=self.rng)
        utt.verify_grad(lambda x: self.op(x, 'U')[1], [S], rng=self.rng)

class test_Eigh_float32(test_Eigh):
    dtype = 'float32'

    @utt.AttemptManyTimes(n_attempts=3, n_req_successes=2)
    def test_uplo(self):
        super(test_Eigh_float32, self).test_uplo()

    @utt.AttemptManyTimes(n_attempts=3, n_req_successes=2)
    def test_grad(self):
        super(test_Eigh_float32, self).test_grad()

class T_lstsq(unittest.TestCase):

    def test_correct_solution(self):
        x = tensor.lmatrix()
        y = tensor.lmatrix()
        z = tensor.lscalar()
        b = theano.tensor.nlinalg.lstsq()(x, y, z)
        f = function([x, y, z], b)
        TestMatrix1 = numpy.asarray([[2, 1], [3, 4]])
        TestMatrix2 = numpy.asarray([[17, 20], [43, 50]])
        TestScalar = numpy.asarray(1)
        f = function([x, y, z], b)
        m = f(TestMatrix1, TestMatrix2, TestScalar)
        self.assertTrue(numpy.allclose(TestMatrix2, numpy.dot(TestMatrix1, m[0])))

    def test_wrong_coefficient_matrix(self):
        x = tensor.vector()
        y = tensor.vector()
        z = tensor.scalar()
        b = theano.tensor.nlinalg.lstsq()(x, y, z)
        f = function([x, y, z], b)
        self.assertRaises(numpy.linalg.linalg.LinAlgError, f, [2, 1], [2, 1], 1)

    def test_wrong_rcond_dimension(self):
        x = tensor.vector()
        y = tensor.vector()
        z = tensor.vector()
        b = theano.tensor.nlinalg.lstsq()(x, y, z)
        f = function([x, y, z], b)
        self.assertRaises(numpy.linalg.LinAlgError, f, [2, 1], [2, 1], [2, 1])

class Matrix_power(unittest.TestCase):

    def test_numpy_compare(self):
        rng = numpy.random.RandomState(utt.fetch_seed())
        A = tensor.matrix("A", dtype=theano.config.floatX)
        Q = matrix_power(A, 3)
        fn = function([A], [Q])
        a = rng.rand(4, 4).astype(theano.config.floatX)

        n_p = numpy.linalg.matrix_power(a, 3)
        t_p = fn(a)
        assert numpy.allclose(n_p, t_p)

    def test_non_square_matrix(self):
        rng = numpy.random.RandomState(utt.fetch_seed())
        A = tensor.matrix("A", dtype=theano.config.floatX)
        Q = matrix_power(A, 3)
        f = function([A], [Q])
        a = rng.rand(4, 3).astype(theano.config.floatX)
        self.assertRaises(ValueError, f, a)

class T_NormTests(unittest.TestCase):

    def test_wrong_type_of_ord_for_vector(self):
        self.assertRaises(ValueError, norm, [2, 1], 'fro')

    def test_wrong_type_of_ord_for_matrix(self):
        self.assertRaises(ValueError, norm, [[2, 1], [3, 4]], 0)

    def test_non_tensorial_input(self):
        self.assertRaises(ValueError, norm, 3, None)

    def test_tensor_input(self):
        self.assertRaises(NotImplementedError, norm, numpy.random.rand(3, 4, 5), None)

    def test_numpy_compare(self):
        rng = numpy.random.RandomState(utt.fetch_seed())

        M = tensor.matrix("A", dtype=theano.config.floatX)
        V = tensor.vector("V", dtype=theano.config.floatX)

        a = rng.rand(4, 4).astype(theano.config.floatX)
        b = rng.rand(4).astype(theano.config.floatX)

        A = (   [None, 'fro', 'inf', '-inf', 1, -1, None, 'inf', '-inf', 0, 1, -1, 2, -2],
                [M, M, M, M, M, M, V, V, V, V, V, V, V, V],
                [a, a, a, a, a, a, b, b, b, b, b, b, b, b],
                [None, 'fro', inf, -inf, 1, -1, None, inf, -inf, 0, 1, -1, 2, -2])

        for i in range(0, 14):
            f = function([A[1][i]], norm(A[1][i], A[0][i]))
            t_n = f(A[2][i])
            n_n = numpy.linalg.norm(A[2][i], A[3][i])
            assert _allclose(n_n, t_n)