text:
import re
from dataclasses import dataclass
from typing import Any

from pants.backend.shell.shell_setup import ShellSetup
from pants.backend.shell.shunit2 import Shunit2
from pants.backend.shell.target_types import (
    ShellSourceField,
    Shunit2Shell,
    Shunit2ShellField,
    Shunit2TestsGeneratorTarget,
    Shunit2TestSourceField,
    Shunit2TestTimeoutField,
    SkipShunit2TestsField,
)
from pants.core.goals.test import (
    BuildPackageDependenciesRequest,
    BuiltPackageDependencies,
    RuntimePackageDependenciesField,
    TestDebugAdapterRequest,
    TestDebugRequest,
    TestExtraEnv,
    TestFieldSet,
    TestRequest,
    TestResult,
    TestSubsystem,
)
from pants.core.target_types import FileSourceField, ResourceSourceField
from pants.core.util_rules.external_tool import DownloadedExternalTool, ExternalToolRequest
from pants.core.util_rules.source_files import SourceFiles, SourceFilesRequest
from pants.core.util_rules.system_binaries import (
    BinaryNotFoundError,
    BinaryPath,
    BinaryPathRequest,
    BinaryPaths,
)
from pants.engine.addresses import Address
from pants.engine.fs import CreateDigest, Digest, DigestContents, FileContent, MergeDigests
from pants.engine.platform import Platform
from pants.engine.process import (
    FallibleProcessResult,
    InteractiveProcess,
    Process,
    ProcessCacheScope,
)
from pants.engine.rules import Get, MultiGet, collect_rules, rule
from pants.engine.target import SourcesField, Target, TransitiveTargets, TransitiveTargetsRequest
from pants.engine.unions import UnionRule
from pants.option.global_options import GlobalOptions
from pants.util.docutil import bin_name
from pants.util.logging import LogLevel
from pants.util.strutil import create_path_env_var

@dataclass(frozen=True)
class Shunit2FieldSet(TestFieldSet):
    required_fields = (Shunit2TestSourceField,)

    sources: Shunit2TestSourceField
    timeout: Shunit2TestTimeoutField
    shell: Shunit2ShellField
    runtime_package_dependencies: RuntimePackageDependenciesField

    @classmethod
    def opt_out(cls, tgt: Target) -> bool:
        return tgt.get(SkipShunit2TestsField).value

class Shunit2TestRequest(TestRequest):
    tool_subsystem = Shunit2
    field_set_type = Shunit2FieldSet

@dataclass(frozen=True)
class TestSetupRequest:
    field_set: Shunit2FieldSet

@dataclass(frozen=True)
class TestSetup:
    process: Process

class ShellNotConfigured(Exception):
    pass

SOURCE_SHUNIT2_REGEX = re.compile(rb"(?:source|\.)\s+[.${}/'\"\w]*shunit2\b['\"]?")

def add_source_shunit2(fc: FileContent, binary_name: str) -> FileContent:
    # NB: We always run tests from the build root, so we source `shunit2` relative to there.
    source_line = f"source ./{binary_name}".encode()

    lines = []
    already_had_source = False
    for line in fc.content.splitlines():
        if SOURCE_SHUNIT2_REGEX.search(line):
            lines.append(SOURCE_SHUNIT2_REGEX.sub(source_line, line))
            already_had_source = True
        else:
            lines.append(line)

    if not already_had_source:
        lines.append(source_line)

    return FileContent(fc.path, b"\n".join(lines))

@dataclass(frozen=True)
class Shunit2RunnerRequest:
    address: Address
    test_file_content: FileContent
    shell_field: Shunit2ShellField

@dataclass(frozen=True)
class Shunit2Runner:
    shell: Shunit2Shell
    binary_path: BinaryPath

@rule(desc="Determine shunit2 shell")
async def determine_shunit2_shell(
    request: Shunit2RunnerRequest,
    shell_setup: ShellSetup.EnvironmentAware,
) -> Shunit2Runner:
    if request.shell_field.value is not None:
        tgt_shell = Shunit2Shell(request.shell_field.value)
    else:
        parse_result = Shunit2Shell.parse_shebang(request.test_file_content.content)
        if parse_result is None:
            raise ShellNotConfigured(
                f"Could not determine which shell to use to run shunit2 on {request.address}.\n\n"
                f"Please either specify the `{Shunit2ShellField.alias}` field or add a "
                f"shebang to {request.test_file_content.path} with one of the supported shells in "
                f"the format `!#/path/to/shell` or `!#/path/to/env shell`"
                f"(run `{bin_name()} help {Shunit2TestsGeneratorTarget.alias}` for valid shells)."
            )
        tgt_shell = parse_result

    path_request = BinaryPathRequest(
        binary_name=tgt_shell.name,
        search_path=shell_setup.executable_search_path,
        test=tgt_shell.binary_path_test,
    )
    paths = await Get(BinaryPaths, BinaryPathRequest, path_request)
    first_path = paths.first_path
    if not first_path:
        raise BinaryNotFoundError.from_request(
            path_request, rationale=f"run shunit2 on {request.address}"
        )
    return Shunit2Runner(tgt_shell, first_path)

@rule(desc="Setup shunit2", level=LogLevel.DEBUG)
async def setup_shunit2_for_target(
    request: TestSetupRequest,
    shell_setup: ShellSetup.EnvironmentAware,
    test_subsystem: TestSubsystem,
    test_extra_env: TestExtraEnv,
    global_options: GlobalOptions,
    shunit2: Shunit2,
) -> TestSetup:
    shunit2_script, transitive_targets, built_package_dependencies = await MultiGet(
        Get(DownloadedExternalTool, ExternalToolRequest, shunit2.get_request(Platform.current)),
        Get(TransitiveTargets, TransitiveTargetsRequest([request.field_set.address])),
        Get(
            BuiltPackageDependencies,
            BuildPackageDependenciesRequest(request.field_set.runtime_package_dependencies),
        ),
    )

    dependencies_source_files_request = Get(
        SourceFiles,
        SourceFilesRequest(
            (tgt.get(SourcesField) for tgt in transitive_targets.dependencies),
            for_sources_types=(ShellSourceField, FileSourceField, ResourceSourceField),
            enable_codegen=True,
        ),
    )
    dependencies_source_files, field_set_sources = await MultiGet(
        dependencies_source_files_request,
        Get(SourceFiles, SourceFilesRequest([request.field_set.sources])),
    )

    field_set_digest_content = await Get(DigestContents, Digest, field_set_sources.snapshot.digest)
    # `ShellTestSourceField` validates that there's exactly one file.
    test_file_content = field_set_digest_content[0]
    updated_test_file_content = add_source_shunit2(test_file_content, shunit2_script.exe)

    updated_test_digest, runner = await MultiGet(
        Get(Digest, CreateDigest([updated_test_file_content])),
        Get(
            Shunit2Runner,
            Shunit2RunnerRequest(
                request.field_set.address, test_file_content, request.field_set.shell
            ),
        ),
    )

    input_digest = await Get(
        Digest,
        MergeDigests(
            (
                shunit2_script.digest,
                updated_test_digest,
                dependencies_source_files.snapshot.digest,
                *(pkg.digest for pkg in built_package_dependencies),
            )
        ),
    )

    env_dict = {
        "PATH": create_path_env_var(shell_setup.executable_search_path),
        "SHUNIT_COLOR": "always" if global_options.colors else "none",
        **test_extra_env.env,
    }
    argv = (
        # Zsh requires extra args. See https://github.com/kward/shunit2/#-zsh.
        [runner.binary_path.path, "-o", "shwordsplit", "--", *field_set_sources.snapshot.files]
        if runner.shell == Shunit2Shell.zsh
        else [runner.binary_path.path, *field_set_sources.snapshot.files]
    )
    cache_scope = (
        ProcessCacheScope.PER_SESSION if test_subsystem.force else ProcessCacheScope.SUCCESSFUL
    )
    process = Process(
        argv=argv,
        input_digest=input_digest,
        description=f"Run shunit2 for {request.field_set.address}.",
        level=LogLevel.DEBUG,
        env=env_dict,
        timeout_seconds=request.field_set.timeout.calculate_from_global_options(test_subsystem),
        cache_scope=cache_scope,
    )
    return TestSetup(process)

@rule(desc="Run tests with Shunit2", level=LogLevel.DEBUG)
async def run_tests_with_shunit2(
    batch: Shunit2TestRequest.Batch[Shunit2FieldSet, Any], test_subsystem: TestSubsystem
) -> TestResult:
    field_set = batch.single_element

    setup = await Get(TestSetup, TestSetupRequest(field_set))
    result = await Get(FallibleProcessResult, Process, setup.process)
    return TestResult.from_fallible_process_result(
        result,
        address=field_set.address,
        output_setting=test_subsystem.output,
    )

@rule(desc="Setup Shunit2 to run interactively", level=LogLevel.DEBUG)
async def setup_shunit2_debug_test(
    batch: Shunit2TestRequest.Batch[Shunit2FieldSet, Any]
) -> TestDebugRequest:
    setup = await Get(TestSetup, TestSetupRequest(batch.single_element))
    return TestDebugRequest(
        InteractiveProcess.from_process(
            setup.process, forward_signals_to_process=False, restartable=True
        )
    )

@rule
async def setup_shunit2_debug_adapter_test(
    _: Shunit2TestRequest.Batch[Shunit2FieldSet, Any]
) -> TestDebugAdapterRequest:
    raise NotImplementedError("Debugging Shell using a debug adapter has not yet been implemented.")

def rules():
    return [
        *collect_rules(),
        UnionRule(TestFieldSet, Shunit2FieldSet),
        *Shunit2TestRequest.rules(),
    ]


text:
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.android_webview.common.variations;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;

/**
 * Stores values related to the collection of variations service metrics.
 *
 * The values maintained by this class can be initialized from and serialized to a dedicated
 * variations SharedPreferences, or from a Bundle suitable for sending in AIDL IPC calls.
 */
public class VariationsServiceMetricsHelper {
    private static final String PREF_FILE_NAME = "variations_prefs";

    // The time in milliseconds between the start of the two most recent seed downloads.
    private static final String JOB_INTERVAL = "job_interval";
    // The time in milliseconds between scheduling and executing the last seed download job.
    private static final String JOB_QUEUE_TIME = "job_queue_time";
    // The result of the last seed download.

    // Name of a SharedPreferences pref that stores the time in milliseconds since UNIX epoch of
    // when the most recent seed download job was scheduled.
    private static final String LAST_ENQUEUE_TIME = "last_enqueue_time";
    // Name of a SharedPreferences pref that stores the time in milliseconds since UNIX epoch of
    // when the most recent seed download job was started.
    private static final String LAST_JOB_START_TIME = "last_job_start_time";

    /**
     * Creates a new VariationsServiceMetricsHelper instance initialized with the contents of the
     * given Bundle.
     */
    public static VariationsServiceMetricsHelper fromBundle(Bundle bundle) {
        return new VariationsServiceMetricsHelper(bundle);
    }

    /**
     * Creates a new VariationsServiceMetricsHelper instance initialized with the contents of the
     * variations SharedPreferences instance for the given Context.
     */
    public static VariationsServiceMetricsHelper fromVariationsSharedPreferences(Context context) {
        Bundle bundle = new Bundle();
        SharedPreferences prefs =
                context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
        if (prefs.contains(JOB_INTERVAL)) {
            bundle.putLong(JOB_INTERVAL, prefs.getLong(JOB_INTERVAL, 0));
        }
        if (prefs.contains(JOB_QUEUE_TIME)) {
            bundle.putLong(JOB_QUEUE_TIME, prefs.getLong(JOB_QUEUE_TIME, 0));
        }
        if (prefs.contains(LAST_ENQUEUE_TIME)) {
            bundle.putLong(LAST_ENQUEUE_TIME, prefs.getLong(LAST_ENQUEUE_TIME, 0));
        }
        if (prefs.contains(LAST_JOB_START_TIME)) {
            bundle.putLong(LAST_JOB_START_TIME, prefs.getLong(LAST_JOB_START_TIME, 0));
        }
        return new VariationsServiceMetricsHelper(bundle);
    }

    private final Bundle mBundle;

    public Bundle toBundle() {
        // Create a copy of the Bundle to make sure it won't be modified by future mutator method
        // calls in this class.
        return new Bundle(mBundle);
    }

    // This method should only be called from within WebView's service.
    public boolean writeMetricsToVariationsSharedPreferences(Context context) {
        SharedPreferences.Editor prefsEditor =
                context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE).edit();
        prefsEditor.clear();
        if (hasJobInterval()) {
            prefsEditor.putLong(JOB_INTERVAL, getJobInterval());
        }
        if (hasJobQueueTime()) {
            prefsEditor.putLong(JOB_QUEUE_TIME, getJobQueueTime());
        }
        if (hasLastEnqueueTime()) {
            prefsEditor.putLong(LAST_ENQUEUE_TIME, getLastEnqueueTime());
        }
        if (hasLastJobStartTime()) {
            prefsEditor.putLong(LAST_JOB_START_TIME, getLastJobStartTime());
        }
        return prefsEditor.commit();
    }

    public void clearJobInterval() {
        mBundle.remove(JOB_INTERVAL);
    }
    public void setJobInterval(long seedFetchTime) {
        mBundle.putLong(JOB_INTERVAL, seedFetchTime);
    }
    public boolean hasJobInterval() {
        return mBundle.containsKey(JOB_INTERVAL);
    }
    public long getJobInterval() {
        return mBundle.getLong(JOB_INTERVAL);
    }

    public void clearJobQueueTime() {
        mBundle.remove(JOB_QUEUE_TIME);
    }
    public void setJobQueueTime(long seedFetchTime) {
        mBundle.putLong(JOB_QUEUE_TIME, seedFetchTime);
    }
    public boolean hasJobQueueTime() {
        return mBundle.containsKey(JOB_QUEUE_TIME);
    }
    public long getJobQueueTime() {
        return mBundle.getLong(JOB_QUEUE_TIME);
    }

    public void clearLastEnqueueTime() {
        mBundle.remove(LAST_ENQUEUE_TIME);
    }
    public void setLastEnqueueTime(long seedFetchTime) {
        mBundle.putLong(LAST_ENQUEUE_TIME, seedFetchTime);
    }
    public boolean hasLastEnqueueTime() {
        return mBundle.containsKey(LAST_ENQUEUE_TIME);
    }
    public long getLastEnqueueTime() {
        return mBundle.getLong(LAST_ENQUEUE_TIME);
    }

    public void clearLastJobStartTime() {
        mBundle.remove(LAST_JOB_START_TIME);
    }
    public void setLastJobStartTime(long seedFetchTime) {
        mBundle.putLong(LAST_JOB_START_TIME, seedFetchTime);
    }
    public boolean hasLastJobStartTime() {
        return mBundle.containsKey(LAST_JOB_START_TIME);
    }
    public long getLastJobStartTime() {
        return mBundle.getLong(LAST_JOB_START_TIME);
    }

    private VariationsServiceMetricsHelper(Bundle bundle) {
        mBundle = bundle;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.lothrazar.cyclic.block.bedrock;

import com.lothrazar.cyclic.block.BlockCyclic;
import com.lothrazar.cyclic.util.UtilParticle;
import net.minecraft.core.BlockPos;
import net.minecraft.core.particles.DustParticleOptions;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BooleanProperty;
import net.minecraft.world.phys.BlockHitResult;

public class UnbreakableBlock extends BlockCyclic {

  public static final BooleanProperty BREAKABLE = BooleanProperty.create("breakable");

  public UnbreakableBlock(Properties properties) {
    super(properties.strength(50.0F, 1200.0F));
  }

  @Override
  public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) {
    ItemStack heldItemStack = player.getItemInHand(hand);
    Item heldItem = heldItemStack.getItem();
    if (state.hasProperty(BREAKABLE) &&
        hand == InteractionHand.MAIN_HAND &&
        heldItem == Items.REDSTONE ||
        heldItem == Items.REDSTONE_TORCH ||
        heldItem == Items.REDSTONE_BLOCK) {
      toggle(state, world, pos);
      return InteractionResult.SUCCESS;
    }
    return super.use(state, world, pos, player, hand, hit);
  }

  private void toggle(BlockState state, Level world, BlockPos pos) {
    setBreakable(state, world, pos, !state.getValue(BREAKABLE));
  }

  private void setBreakable(BlockState state, Level world, BlockPos pos, boolean isBreakable) {
    boolean oldBreakable = state.getValue(BREAKABLE);
    world.setBlockAndUpdate(pos, state.setValue(BREAKABLE, isBreakable));
    if (world.isClientSide && oldBreakable != isBreakable) {
      UtilParticle.spawnParticle(world, DustParticleOptions.REDSTONE, pos, 5);
    }
  }

  @Override
  public void neighborChanged(BlockState state, Level worldIn, BlockPos pos, Block blockIn, BlockPos fromPos, boolean isMoving) {
    BlockState neighborState = worldIn.getBlockState(fromPos);
    if (!isMoving && neighborState.hasProperty(BREAKABLE) && state.hasProperty(BREAKABLE)) {
      setBreakable(state, worldIn, pos, neighborState.getValue(BREAKABLE));
    }
  }

  @Override
  @SuppressWarnings("deprecation")
  public float getDestroyProgress(BlockState state, Player player, BlockGetter worldIn, BlockPos pos) {
    return (state.hasProperty(BREAKABLE) && !state.getValue(BREAKABLE)) ? 0.0F : super.getDestroyProgress(state, player, worldIn, pos);
  }

  @Override
  protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
    builder.add(BREAKABLE);
  }
}


text:
#pragma once

#include <vector>
#include "DynamicQuadTreeNode.h"

// Template class implementing hierarchy array, which is a quad tree indexed by
// quad tree node location
template <class T>
class HierarchyArray
{
public:
	T& operator [] (const SQuadTreeNodeLocation &at)
	{
		return m_data[at.level][at.horzOrder + (at.vertOrder << at.level)];
	}
	const T& operator [] (const SQuadTreeNodeLocation &at) const
	{
		return m_data[at.level][at.horzOrder + (at.vertOrder << at.level)];
	}

	void Resize(size_t numLevelsInHierarchy)
	{
		m_data.resize(numLevelsInHierarchy);
		if( numLevelsInHierarchy )
		{
			for(size_t level = numLevelsInHierarchy; level--; )
			{
				size_t numElementsInLevel = 1 << level;
				m_data[level].resize(numElementsInLevel*numElementsInLevel);
			}
		}
	}

	bool Empty() const
	{
		return m_data.empty();
	}

private:
	std::vector<std::vector<T> > m_data;
};

// end of file


text:
[#]: subject: "I Ditched Ubuntu for Manjaro: Here's What I Think After a Week"
[#]: via: "https://news.itsfoss.com/manjaro-linux-experience/"
[#]: author: "Ankush Das https://news.itsfoss.com/author/ankush/"
[#]: collector: "lujun9972"
[#]: translator: " "
[#]: reviewer: " "
[#]: publisher: " "
[#]: url: " "

I Ditched Ubuntu for Manjaro: Here's What I Think After a Week
======

Primarily, I rely on Ubuntu-based distributions like Pop!_OS, Zorin OS, Linux Mint, or Ubuntu itself for work.

They get out of the way when I work on something, along with seamless software updates. Not to forget, they get along well with my Intel-Nvidia-powered system.

Everything (can be subjective) works out of the box.

However, I recently decided to switch to Arch Linux on bare metal (because I mostly used it on virtual machines).

And then, I ended up using **Manjaro Linux** (an Arch-based distro).

### Here's Why I Picked Manjaro Linux

To my surprise, I couldn't even get past the "_nouveau DRM: core notifier timeout_" error, let alone proceed with the installation when using a **live USB for Arch Linux**. Yes, I'm aware of the [guided installer with Arch Linux][1], but the connected displays just kept on flickering, highlighting this error, no matter what.

The best solution to this problem was not to get an NVIDIA card with my recent upgrade.

_Too bad, I prefer Nvidia GPUs…_

AMD's RX 6600 XT is similarly priced to RTX 3060 Ti; it did not make sense to get that card for 1440p.

So, yes, RTX 3060 Ti can be the problem in my case.

While I found some methods to troubleshoot the issue, I was too lazy. I just wanted to see if I could experience Arch Linux without putting in a great effort.

**So, here's what I did:**

The next-best option would be to try any of the [best Arch-based distros][2] tailored to make things easy, right?

And that's where **Manjaro Linux** comes in.

Manjaro Linux is a popular Arch-based distro, and I've noticed regular improvements to it with every update (while using it on a VM).

Furthermore, I like Manjaro's default theme accent color for my desktop experience.

So, I decided to give it a try…

### Manjaro Linux: Rough Start

![][3]

I did not have any issues installing Manjaro with proprietary Nvidia drivers. However, a recent point update, i.e., **Manjaro Linux 21.2.6,** messed up the system.

I couldn't access the login screen and the [TTY][4] (all I could see was the motherboard's manufacturer logo)

So, I had to re-install Manjaro Linux using the latest ISO, and so far, so good (touch wood).

And during my usage of Manjaro Linux, I noticed a few things that make up for its good and bad points.

Here, I highlight some of my experiences. These insights should help you explore more about it if you haven't tried it yet.

#### 1\. Easy Installation

The primary highlight of an Arch-based distro is to make things easy to set up. And I had no issues whatsoever.

It was a breeze installing Manjaro Linux on my secondary drive. The bootloader was correctly configured to display the Manjaro-themed boot menu that lets me select Windows/Manjaro Linux for dual-boot.

#### 2\. Manjaro Hello

![][5]

The welcome experience makes up for a significant part of a user experience when trying something new. And Manjaro Linux does not disappoint in this regard.

You get all the essential information if you pay close attention to the information available via the welcome screen.

The GNOME Layouts Manager lets you pick a suitable layout to get yourself comfortable.

![][6]

However, I couldn't get the "**Window Tiling**" functionality working when I tried to enable it here:

![][7]

#### 3\. Package Manager is Fast and Versatile

![][8]

Considering that GNOME is my favorite desktop environment, I have had terrible experiences with the software center (or even with distro-specific stores like Pop!_Shop).

While they get the work done, sometimes they do not respond or aren't responsive enough as I expect them to be.

With Manjaro Linux, I found [Pamac][9] installed as the package manager. It seems to be one of the [best ways to install and remove software on Manjaro Linux][10].

In my experience, it was blazing fast with installations and removing packages. You also get prompts for conflicts in packages or if something needs to be replaced/removed. The package manager gives plenty of information about the optional/required dependencies when you install something.

Overall, it was a pretty good experience without any slowdowns. To sweeten the experience, the package manager lets you quickly enable the support for **Flatpaks/Snaps/AUR** by tweaking the preferences of pamac.

![][11]

So, you do not have to use the terminal or different software stores. Everything will be available under a single roof, which is a big time saver.

#### 4\. Trying out the ZSH Shell

![][12]

I am used to the bash shell on Ubuntu-based distros. However, Manjaro Linux features the ZSH shell by default. I believe ZSH is better than bash, but I'll take a deep dive into the comparison with a separate article soon.

In other words, I get to try something different out of the box. To my excitement, the terminal prompt and the theme for the shell (or the terminal) that follows the Manjaro branding accent colors look pretty impressive!

![][12]

Hence, I do not need to [customize the look of the terminal here][13].

To explore more, you might want to check some of our resources on [what ZSH is][14] and [how to install it][15].

#### 5\. Lack of Official Software Support

![][16]

I hope this improves soon. But, as of now, many software/utilities offer direct support for Ubuntu and Fedora only.

You can find official DEB/RPM packages for various tools, but neither will work directly with Manjaro Linux.

You will have to rely on the packages available in Arch Linux repositories or [AUR][17].

Fortunately, there are good chances to find the software in AUR or their repositories maintained by the community or distro developers. Just like I was able to get [Insync][18] (_affiliate link_) to work on Manjaro Linux with file manage integration extensions available.

However, without official support for the platform, you may/may not miss out on some features or quick updates.

Of course, if you rely on [Flatpak][19] or Snap packages, it should not be an issue for you. Furthermore, if you are new to Linux, you can refer to our [Flatpak guide][20] for more information.

#### 6\. No Fractional Scaling

I have a dual-monitor setup with 1080p + 1440p resolutions. So, fractional scaling helps, but I can manage without it.

To enable fractional scaling on Manjaro, you will have to install x11-scaling enabled packages for Mutter and GNOME control center. The packages include:

  * **mutter-x11-scaling**
  * **gnome-control-center-x11-scaling**

This will replace your existing mutter and gnome control center packages. So, you will lose the default theme/accent settings for your desktop.

You may have to utilize GNOME Tweaks to get things right. But, it can turn out to be an annoying experience.

### Final Thoughts

Overall, I enjoy the desktop experience with Manjaro Linux. If another system update doesn't break the experience, I think I will continue with Manjaro Linux as my new daily driver.

_What do you think are the strong/weak points for Manjaro Linux? Did I miss something as part of my new experience? Do you have any suggestions as an experienced Arch Linux user?_

_Please let me know your thoughts in the comments below._

--------------------------------------------------------------------------------

via: https://news.itsfoss.com/manjaro-linux-experience/

作者:[Ankush Das][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]: https://news.itsfoss.com/author/ankush/
[b]: https://github.com/lujun9972
[1]: https://news.itsfoss.com/arch-new-guided-installer/
[2]: https://itsfoss.com/arch-based-linux-distros/
[3]: data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjkwMCIgd2lkdGg9IjE2MDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIi8+
[4]: https://itsfoss.com/what-is-tty-in-linux/
[5]: data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjcxMyIgd2lkdGg9IjkzNSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiLz4=
[6]: data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjY1MSIgd2lkdGg9Ijg1MiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiLz4=
[7]: data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjY3MyIgd2lkdGg9Ijg1MiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiLz4=
[8]: data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjYwMiIgd2lkdGg9IjEwMDIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIi8+
[9]: https://wiki.manjaro.org/index.php/Pamac
[10]: https://itsfoss.com/install-remove-software-manjaro/
[11]: data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjYyOCIgd2lkdGg9IjY5MiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiLz4=
[12]: data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjYwMSIgd2lkdGg9Ijc4OCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiLz4=
[13]: https://itsfoss.com/customize-linux-terminal/
[14]: https://linuxhandbook.com/why-zsh/
[15]: https://linuxhandbook.com/install-zsh/
[16]: data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjYxNyIgd2lkdGg9IjEwMjQiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIi8+
[17]: https://itsfoss.com/aur-arch-linux/
[18]: https://itsfoss.com/recommends/get-insync/
[19]: https://itsfoss.com/what-is-flatpak/
[20]: https://itsfoss.com/flatpak-guide/


text:
/*
 *  eXist Image Module Extension GetHeightFunction
 *  Copyright (C) 2006 Adam Retter <adam.retter@devon.gov.uk>
 *  www.adamretter.co.uk
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *  $Id: GetHeightFunction.java 5415 2007-02-28 12:10:35Z deliriumsky $
 */

package org.exist.xquery.modules.image;

import java.awt.Image;
import java.io.IOException;

import org.exist.dom.QName;
import org.exist.xquery.BasicFunction;
import org.exist.xquery.Cardinality;
import org.exist.xquery.FunctionSignature;
import org.exist.xquery.XPathException;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.value.Base64Binary;
import org.exist.xquery.value.IntegerValue;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceType;
import org.exist.xquery.value.Type;

/**
 * eXist Image Module Extension GetHeightFunction
 *
 * Get's the height of an Image
 *
 * @author Adam Retter <adam.retter@devon.gov.uk>
 * @serial 2006-03-12
 * @version 1.1
 *
 * @see org.exist.xquery.BasicFunction#BasicFunction(org.exist.xquery.XQueryContext, org.exist.xquery.FunctionSignature)
 */
public class GetHeightFunction extends BasicFunction
{
	public final static FunctionSignature signature =
		new FunctionSignature(
			new QName("get-height", ImageModule.NAMESPACE_URI, ImageModule.PREFIX),
			"Get's the Height of the image passed in $a, returning an integer of the images Height in pixels or an empty sequence if $a is invalid.",
			new SequenceType[]
			{
				new SequenceType(Type.BASE64_BINARY, Cardinality.EXACTLY_ONE)
			},
			new SequenceType(Type.INTEGER, Cardinality.ZERO_OR_ONE));

	/**
	 * GetHeightFunction Constructor
	 *
	 * @param context	The Context of the calling XQuery
	 */
	public GetHeightFunction(XQueryContext context)
	{
		super(context, signature);
    }

	/**
	 * evaluate the call to the xquery get-height() function,
	 * it is really the main entry point of this class
	 *
	 * @param args		arguments from the get-height() function call
	 * @param contextSequence	the Context Sequence to operate on (not used here internally!)
	 * @return		A sequence representing the result of the get-height() function call
	 *
	 * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
	 */
	public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException
	{
		//was an image speficifed
		if (args[0].isEmpty())
            return Sequence.EMPTY_SEQUENCE;

        //get the image
        Image image = null;
        try
        {
        	image = ImageModule.getImage((Base64Binary)args[0].itemAt(0));
        }
        catch(IOException ioe)
        {
        	LOG.error("Unable to read image data!", ioe);
        	return Sequence.EMPTY_SEQUENCE;
        }

        if(image == null)
        {
        	LOG.error("Unable to read image data!");
        	return Sequence.EMPTY_SEQUENCE;
        }

        //Get the Height of the image
        int iHeight = image.getHeight(null);

        //did we get the Height of the image?
        if(iHeight == -1)
        {
        	//no, log the error
        	LOG.error("Unable to read image data!");
        	return Sequence.EMPTY_SEQUENCE;
        }
        else
        {
        	//return the Height of the image
        	return new IntegerValue(iHeight);
        }
	}
}


text:
package main

import (
	"os"
	"path/filepath"

	"github.com/cilium/cilium/common"
	"github.com/cilium/cilium/pkg/logging"
	"github.com/cilium/cilium/pkg/logging/logfields"
	"github.com/cilium/cilium/plugins/cilium-docker/driver"

	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
)

var (
	log        = logging.DefaultLogger.WithField(logfields.LogSubsys, "cilium-docker")
	pluginPath string
	driverSock string
	debug      bool
	ciliumAPI  string
)

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
	Use:   "cilium-docker",
	Short: "Cilium plugin for Docker (libnetwork)",
	Long: `Cilium plugin for Docker (libnetwork)

Docker plugin implementing the networking and IPAM API.

The plugin handles requests from the local Docker runtime to provide
network connectivity and IP address management for containers that are
connected to a Docker network of type "cilium".`,
	Example: `  docker network create my_network --ipam-driver cilium --driver cilium
  docker run --net my_network hello-world
`,
	Run: func(cmd *cobra.Command, args []string) {
		if d, err := driver.NewDriver(ciliumAPI); err != nil {
			log.WithError(err).Fatal("Unable to create cilium-net driver")
		} else {
			log.WithField(logfields.Path, driverSock).Info("Listening for events from Docker")
			if err := d.Listen(driverSock); err != nil {
				log.Fatal(err)
			}
		}
	},
}

func main() {
	if err := RootCmd.Execute(); err != nil {
		log.Fatal(err)
		os.Exit(-1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)
	flags := RootCmd.PersistentFlags()
	flags.BoolVarP(&debug, "debug", "D", false, "Enable debug messages")
	flags.StringVar(&ciliumAPI, "cilium-api", "", "URI to server-side API")
	flags.StringVar(&pluginPath, "docker-plugins", "/run/docker/plugins",
		"Path to Docker plugins directory")
}

func initConfig() {
	if debug {
		log.Logger.SetLevel(logrus.DebugLevel)
	} else {
		log.Logger.SetLevel(logrus.InfoLevel)
	}

	common.RequireRootPrivilege("cilium-docker")

	driverSock = filepath.Join(pluginPath, "cilium.sock")

	if err := os.MkdirAll(pluginPath, 0755); err != nil && !os.IsExist(err) {
		log.WithError(err).Fatal("Could not create net plugin path directory")
	}

	if _, err := os.Stat(driverSock); err == nil {
		log.WithField(logfields.Path, driverSock).Debug("socket file already exists, unlinking the old file handle.")
		os.RemoveAll(driverSock)
	}
}


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.autofill;

import android.content.Context;
import android.text.format.DateUtils;

import androidx.annotation.VisibleForTesting;

import org.chromium.base.ThreadUtils;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.autofill.settings.AutofillEditorBase;
import org.chromium.chrome.browser.preferences.Pref;
import org.chromium.chrome.browser.preferences.PrefServiceBridge;
import org.chromium.content_public.browser.WebContents;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

/**
 * Android wrapper of the PersonalDataManager which provides access from the Java
 * layer.
 *
 * Only usable from the UI thread as it's primary purpose is for supporting the Android
 * preferences UI.
 *
 * See chrome/browser/autofill/personal_data_manager.h for more details.
 */
@JNINamespace("autofill")
public class PersonalDataManager {

    /**
     * Observer of PersonalDataManager events.
     */
    public interface PersonalDataManagerObserver {
        /**
         * Called when the data is changed.
         */
        void onPersonalDataChanged();
    }

    /**
     * Callback for full card request.
     */
    public interface FullCardRequestDelegate {
        /**
         * Called when user provided the full card details, including the CVC and the full PAN.
         *
         * @param card The full card.
         * @param cvc The CVC for the card.
         */
        @CalledByNative("FullCardRequestDelegate")
        void onFullCardDetails(CreditCard card, String cvc);

        /**
         * Called when user did not provide full card details.
         */
        @CalledByNative("FullCardRequestDelegate")
        void onFullCardError();
    }

    /**
     * Callback for subKeys request.
     */
    public interface GetSubKeysRequestDelegate {
        /**
         * Called when the subkeys are received sucessfully.
         * Here the subkeys are admin areas.
         *
         * @param subKeysCodes The subkeys' codes.
         * @param subKeysNames The subkeys' names.
         */
        @CalledByNative("GetSubKeysRequestDelegate")
        void onSubKeysReceived(String[] subKeysCodes, String[] subKeysNames);
    }

    /**
     * Callback for normalized addresses.
     */
    public interface NormalizedAddressRequestDelegate {
        /**
         * Called when the address has been sucessfully normalized.
         *
         * @param profile The profile with the normalized address.
         */
        @CalledByNative("NormalizedAddressRequestDelegate")
        void onAddressNormalized(AutofillProfile profile);

        /**
         * Called when the address could not be normalized.
         *
         * @param profile The non normalized profile.
         */
        @CalledByNative("NormalizedAddressRequestDelegate")
        void onCouldNotNormalize(AutofillProfile profile);
    }

    /**
     * Autofill address information.
     */
    public static class AutofillProfile {
        private String mGUID;
        private String mOrigin;
        private boolean mIsLocal;
        private String mFullName;
        private String mCompanyName;
        private String mStreetAddress;
        private String mRegion;
        private String mLocality;
        private String mDependentLocality;
        private String mPostalCode;
        private String mSortingCode;
        private String mCountryCode;
        private String mPhoneNumber;
        private String mEmailAddress;
        private String mLabel;
        private String mLanguageCode;

        @CalledByNative("AutofillProfile")
        public static AutofillProfile create(String guid, String origin, boolean isLocal,
                String fullName, String companyName, String streetAddress, String region,
                String locality, String dependentLocality, String postalCode, String sortingCode,
                String country, String phoneNumber, String emailAddress, String languageCode) {
            return new AutofillProfile(guid, origin, isLocal, fullName, companyName, streetAddress,
                    region, locality, dependentLocality, postalCode, sortingCode, country,
                    phoneNumber, emailAddress, languageCode);
        }

        public AutofillProfile(String guid, String origin, boolean isLocal, String fullName,
                String companyName, String streetAddress, String region, String locality,
                String dependentLocality, String postalCode, String sortingCode, String countryCode,
                String phoneNumber, String emailAddress, String languageCode) {
            mGUID = guid;
            mOrigin = origin;
            mIsLocal = isLocal;
            mFullName = fullName;
            mCompanyName = companyName;
            mStreetAddress = streetAddress;
            mRegion = region;
            mLocality = locality;
            mDependentLocality = dependentLocality;
            mPostalCode = postalCode;
            mSortingCode = sortingCode;
            mCountryCode = countryCode;
            mPhoneNumber = phoneNumber;
            mEmailAddress = emailAddress;
            mLanguageCode = languageCode;
        }

        /**
         * Builds an empty local profile with "settings" origin and country code from the default
         * locale. All other fields are empty strings, because JNI does not handle null strings.
         */
        public AutofillProfile() {
            this("" /* guid */, AutofillEditorBase.SETTINGS_ORIGIN /* origin */, true /* isLocal */,
                    "" /* fullName */, "" /* companyName */, "" /* streetAddress */,
                    "" /* region */, "" /* locality */, "" /* dependentLocality */,
                    "" /* postalCode */, "" /* sortingCode */,
                    Locale.getDefault().getCountry() /* country */, "" /* phoneNumber */,
                    "" /* emailAddress */, "" /* languageCode */);
        }

        /* Builds an AutofillProfile that is an exact copy of the one passed as parameter. */
        public AutofillProfile(AutofillProfile profile) {
            mGUID = profile.getGUID();
            mOrigin = profile.getOrigin();
            mIsLocal = profile.getIsLocal();
            mFullName = profile.getFullName();
            mCompanyName = profile.getCompanyName();
            mStreetAddress = profile.getStreetAddress();
            mRegion = profile.getRegion();
            mLocality = profile.getLocality();
            mDependentLocality = profile.getDependentLocality();
            mPostalCode = profile.getPostalCode();
            mSortingCode = profile.getSortingCode();
            mCountryCode = profile.getCountryCode();
            mPhoneNumber = profile.getPhoneNumber();
            mEmailAddress = profile.getEmailAddress();
            mLanguageCode = profile.getLanguageCode();
            mLabel = profile.getLabel();
        }

        /** TODO(estade): remove this constructor. */
        @VisibleForTesting
        public AutofillProfile(String guid, String origin, String fullName, String companyName,
                String streetAddress, String region, String locality, String dependentLocality,
                String postalCode, String sortingCode, String countryCode, String phoneNumber,
                String emailAddress, String languageCode) {
            this(guid, origin, true /* isLocal */, fullName, companyName, streetAddress, region,
                    locality, dependentLocality, postalCode, sortingCode, countryCode, phoneNumber,
                    emailAddress, languageCode);
        }

        @CalledByNative("AutofillProfile")
        public String getGUID() {
            return mGUID;
        }

        @CalledByNative("AutofillProfile")
        public String getOrigin() {
            return mOrigin;
        }

        @CalledByNative("AutofillProfile")
        public String getFullName() {
            return mFullName;
        }

        @CalledByNative("AutofillProfile")
        public String getCompanyName() {
            return mCompanyName;
        }

        @CalledByNative("AutofillProfile")
        public String getStreetAddress() {
            return mStreetAddress;
        }

        @CalledByNative("AutofillProfile")
        public String getRegion() {
            return mRegion;
        }

        @CalledByNative("AutofillProfile")
        public String getLocality() {
            return mLocality;
        }

        @CalledByNative("AutofillProfile")
        public String getDependentLocality() {
            return mDependentLocality;
        }

        public String getLabel() {
            return mLabel;
        }

        @CalledByNative("AutofillProfile")
        public String getPostalCode() {
            return mPostalCode;
        }

        @CalledByNative("AutofillProfile")
        public String getSortingCode() {
            return mSortingCode;
        }

        @CalledByNative("AutofillProfile")
        public String getCountryCode() {
            return mCountryCode;
        }

        @CalledByNative("AutofillProfile")
        public String getPhoneNumber() {
            return mPhoneNumber;
        }

        @CalledByNative("AutofillProfile")
        public String getEmailAddress() {
            return mEmailAddress;
        }

        @CalledByNative("AutofillProfile")
        public String getLanguageCode() {
            return mLanguageCode;
        }

        public boolean getIsLocal() {
            return mIsLocal;
        }

        @VisibleForTesting
        public void setGUID(String guid) {
            mGUID = guid;
        }

        public void setLabel(String label) {
            mLabel = label;
        }

        public void setOrigin(String origin) {
            mOrigin = origin;
        }

        public void setFullName(String fullName) {
            mFullName = fullName;
        }

        public void setCompanyName(String companyName) {
            mCompanyName = companyName;
        }

        @VisibleForTesting
        public void setStreetAddress(String streetAddress) {
            mStreetAddress = streetAddress;
        }

        public void setRegion(String region) {
            mRegion = region;
        }

        public void setLocality(String locality) {
            mLocality = locality;
        }

        public void setDependentLocality(String dependentLocality) {
            mDependentLocality = dependentLocality;
        }

        public void setPostalCode(String postalCode) {
            mPostalCode = postalCode;
        }

        public void setSortingCode(String sortingCode) {
            mSortingCode = sortingCode;
        }

        @VisibleForTesting
        public void setCountryCode(String countryCode) {
            mCountryCode = countryCode;
        }

        public void setPhoneNumber(String phoneNumber) {
            mPhoneNumber = phoneNumber;
        }

        public void setEmailAddress(String emailAddress) {
            mEmailAddress = emailAddress;
        }

        @VisibleForTesting
        public void setLanguageCode(String languageCode) {
            mLanguageCode = languageCode;
        }

        public void setIsLocal(boolean isLocal) {
            mIsLocal = isLocal;
        }

        /** Used by ArrayAdapter in credit card settings. */
        @Override
        public String toString() {
            return mLabel;
        }
    }

    /**
     * Autofill credit card information.
     */
    public static class CreditCard {
        // Note that while some of these fields are numbers, they're predominantly read,
        // marshaled and compared as strings. To save conversions, we sometimes use strings.
        private String mGUID;
        private String mOrigin;
        private boolean mIsLocal;
        private boolean mIsCached;
        private String mName;
        private String mNumber;
        private String mObfuscatedNumber;
        private String mMonth;
        private String mYear;
        private String mBasicCardIssuerNetwork;
        private int mIssuerIconDrawableId;
        private String mBillingAddressId;
        private String mServerId;
        // The label set for the card. This could be one of Card Network + LastFour, Nickname +
        // LastFour or a Google specific string for Google-issued cards. This is used for displaying
        // the card in PaymentMethods in Settings.
        private String mCardLabel;

        @CalledByNative("CreditCard")
        public static CreditCard create(String guid, String origin, boolean isLocal,
                boolean isCached, String name, String number, String mObfuscatedNumber,
                String month, String year, String basicCardIssuerNetwork, int iconId,
                String billingAddressId, String serverId, String cardLabel) {
            return new CreditCard(guid, origin, isLocal, isCached, name, number, mObfuscatedNumber,
                    month, year, basicCardIssuerNetwork, iconId, billingAddressId, serverId,
                    cardLabel);
        }

        public CreditCard(String guid, String origin, boolean isLocal, boolean isCached,
                String name, String number, String obfuscatedNumber, String month, String year,
                String basicCardIssuerNetwork, int issuerIconDrawableId, String billingAddressId,
                String serverId) {
            this(guid, origin, isLocal, isCached, name, number, obfuscatedNumber, month, year,
                    basicCardIssuerNetwork, issuerIconDrawableId, billingAddressId, serverId,
                    /* cardLabel= */ obfuscatedNumber);
        }

        public CreditCard(String guid, String origin, boolean isLocal, boolean isCached,
                String name, String number, String obfuscatedNumber, String month, String year,
                String basicCardIssuerNetwork, int issuerIconDrawableId, String billingAddressId,
                String serverId, String cardLabel) {
            mGUID = guid;
            mOrigin = origin;
            mIsLocal = isLocal;
            mIsCached = isCached;
            mName = name;
            mNumber = number;
            mObfuscatedNumber = obfuscatedNumber;
            mMonth = month;
            mYear = year;
            mBasicCardIssuerNetwork = basicCardIssuerNetwork;
            mIssuerIconDrawableId = issuerIconDrawableId;
            mBillingAddressId = billingAddressId;
            mServerId = serverId;
            mCardLabel = cardLabel;
        }

        public CreditCard() {
            this("" /* guid */, AutofillEditorBase.SETTINGS_ORIGIN /*origin */, true /* isLocal */,
                    false /* isCached */, "" /* name */, "" /* number */, "" /* obfuscatedNumber */,
                    "" /* month */, "" /* year */, "" /* basicCardIssuerNetwork */,
                    0 /* issuerIconDrawableId */, "" /* billingAddressId */, "" /* serverId */);
        }

        /** TODO(estade): remove this constructor. */
        @VisibleForTesting
        public CreditCard(String guid, String origin, String name, String number,
                String obfuscatedNumber, String month, String year) {
            this(guid, origin, true /* isLocal */, false /* isCached */, name, number,
                    obfuscatedNumber, month, year, "" /* basicCardIssuerNetwork */,
                    0 /* issuerIconDrawableId */, "" /* billingAddressId */, "" /* serverId */);
        }

        @CalledByNative("CreditCard")
        public String getGUID() {
            return mGUID;
        }

        @CalledByNative("CreditCard")
        public String getOrigin() {
            return mOrigin;
        }

        @CalledByNative("CreditCard")
        public String getName() {
            return mName;
        }

        @CalledByNative("CreditCard")
        public String getNumber() {
            return mNumber;
        }

        public String getObfuscatedNumber() {
            return mObfuscatedNumber;
        }

        @CalledByNative("CreditCard")
        public String getMonth() {
            return mMonth;
        }

        @CalledByNative("CreditCard")
        public String getYear() {
            return mYear;
        }

        public String getFormattedExpirationDate(Context context) {
            return getMonth()
                    + context.getResources().getString(R.string.autofill_expiration_date_separator)
                    + getYear();
        }

        @CalledByNative("CreditCard")
        public boolean getIsLocal() {
            return mIsLocal;
        }

        @CalledByNative("CreditCard")
        public boolean getIsCached() {
            return mIsCached;
        }

        @CalledByNative("CreditCard")
        public String getBasicCardIssuerNetwork() {
            return mBasicCardIssuerNetwork;
        }

        public int getIssuerIconDrawableId() {
            return mIssuerIconDrawableId;
        }

        @CalledByNative("CreditCard")
        public String getBillingAddressId() {
            return mBillingAddressId;
        }

        @CalledByNative("CreditCard")
        public String getServerId() {
            return mServerId;
        }

        public String getCardLabel() {
            return mCardLabel;
        }

        @VisibleForTesting
        public void setGUID(String guid) {
            mGUID = guid;
        }

        public void setOrigin(String origin) {
            mOrigin = origin;
        }

        public void setName(String name) {
            mName = name;
        }

        @VisibleForTesting
        public void setNumber(String number) {
            mNumber = number;
        }

        public void setObfuscatedNumber(String obfuscatedNumber) {
            mObfuscatedNumber = obfuscatedNumber;
        }

        @VisibleForTesting
        public void setMonth(String month) {
            mMonth = month;
        }

        public void setYear(String year) {
            mYear = year;
        }

        public void setBasicCardIssuerNetwork(String network) {
            mBasicCardIssuerNetwork = network;
        }

        public void setIssuerIconDrawableId(int id) {
            mIssuerIconDrawableId = id;
        }

        public void setBillingAddressId(String id) {
            mBillingAddressId = id;
        }

        public void setCardLabel(String cardLabel) {
            mCardLabel = cardLabel;
        }

        public boolean hasValidCreditCardExpirationDate() {
            if (mMonth.isEmpty() || mYear.isEmpty()) return false;

            Calendar expiryDate = Calendar.getInstance();
            // The mMonth value is 1 based but the month in calendar is 0 based.
            expiryDate.set(Calendar.MONTH, Integer.parseInt(mMonth) - 1);
            expiryDate.set(Calendar.YEAR, Integer.parseInt(mYear));
            // Add 1 minute to the expiry instance to ensure that the card is still valid on its
            // exact expiration date.
            expiryDate.add(Calendar.MINUTE, 1);
            return Calendar.getInstance().before(expiryDate);
        }
    }

    private static PersonalDataManager sManager;

    // Suppress FindBugs warning, since |sManager| is only used on the UI thread.
    public static PersonalDataManager getInstance() {
        ThreadUtils.assertOnUiThread();
        if (sManager == null) {
            sManager = new PersonalDataManager();
        }
        return sManager;
    }

    private static int sRequestTimeoutSeconds = 5;

    private final long mPersonalDataManagerAndroid;
    private final List<PersonalDataManagerObserver> mDataObservers =
            new ArrayList<PersonalDataManagerObserver>();

    private PersonalDataManager() {
        // Note that this technically leaks the native object, however, PersonalDataManager
        // is a singleton that lives forever and there's no clean shutdown of Chrome on Android
        mPersonalDataManagerAndroid = PersonalDataManagerJni.get().init(PersonalDataManager.this);
    }

    /**
     * Called from native when template URL service is done loading.
     */
    @CalledByNative
    private void personalDataChanged() {
        ThreadUtils.assertOnUiThread();
        for (PersonalDataManagerObserver observer : mDataObservers) {
            observer.onPersonalDataChanged();
        }
    }

    /**
     * Registers a PersonalDataManagerObserver on the native side.
     */
    public boolean registerDataObserver(PersonalDataManagerObserver observer) {
        ThreadUtils.assertOnUiThread();
        assert !mDataObservers.contains(observer);
        mDataObservers.add(observer);
        return PersonalDataManagerJni.get().isDataLoaded(
                mPersonalDataManagerAndroid, PersonalDataManager.this);
    }

    /**
     * Unregisters the provided observer.
     */
    public void unregisterDataObserver(PersonalDataManagerObserver observer) {
        ThreadUtils.assertOnUiThread();
        assert (mDataObservers.size() > 0);
        assert (mDataObservers.contains(observer));
        mDataObservers.remove(observer);
    }

    /**
     * TODO(crbug.com/616102): Reduce the number of Java to Native calls when getting profiles.
     *
     * Gets the profiles to show in the settings page. Returns all the profiles without any
     * processing.
     *
     * @return The list of profiles to show in the settings.
     */
    public List<AutofillProfile> getProfilesForSettings() {
        ThreadUtils.assertOnUiThread();
        return getProfilesWithLabels(PersonalDataManagerJni.get().getProfileLabelsForSettings(
                                             mPersonalDataManagerAndroid, PersonalDataManager.this),
                PersonalDataManagerJni.get().getProfileGUIDsForSettings(
                        mPersonalDataManagerAndroid, PersonalDataManager.this));
    }

    /**
     * TODO(crbug.com/616102): Reduce the number of Java to Native calls when getting profiles
     *
     * Gets the profiles to suggest when filling a form or completing a transaction. The profiles
     * will have been processed to be more relevant to the user.
     *
     * @param includeNameInLabel Whether to include the name in the profile's label.
     * @return The list of profiles to suggest to the user.
     */
    public ArrayList<AutofillProfile> getProfilesToSuggest(boolean includeNameInLabel) {
        ThreadUtils.assertOnUiThread();
        return getProfilesWithLabels(
                PersonalDataManagerJni.get().getProfileLabelsToSuggest(mPersonalDataManagerAndroid,
                        PersonalDataManager.this, includeNameInLabel,
                        true /* includeOrganizationInLabel */, true /* includeCountryInLabel */),
                PersonalDataManagerJni.get().getProfileGUIDsToSuggest(
                        mPersonalDataManagerAndroid, PersonalDataManager.this));
    }

    /**
     * TODO(crbug.com/616102): Reduce the number of Java to Native calls when getting profiles.
     *
     * Gets the profiles to suggest when associating a billing address to a credit card. The
     * profiles will have been processed to be more relevant to the user.
     *
     * @param includeOrganizationInLabel Whether the organization name should be included in the
     *                                   label.
     *
     * @return The list of billing addresses to suggest to the user.
     */
    public ArrayList<AutofillProfile> getBillingAddressesToSuggest(
            boolean includeOrganizationInLabel) {
        ThreadUtils.assertOnUiThread();
        return getProfilesWithLabels(
                PersonalDataManagerJni.get().getProfileLabelsToSuggest(mPersonalDataManagerAndroid,
                        PersonalDataManager.this, true /* includeNameInLabel */,
                        includeOrganizationInLabel, false /* includeCountryInLabel */),
                PersonalDataManagerJni.get().getProfileGUIDsToSuggest(
                        mPersonalDataManagerAndroid, PersonalDataManager.this));
    }

    private ArrayList<AutofillProfile> getProfilesWithLabels(
            String[] profileLabels, String[] profileGUIDs) {
        ArrayList<AutofillProfile> profiles = new ArrayList<AutofillProfile>(profileGUIDs.length);
        for (int i = 0; i < profileGUIDs.length; i++) {
            AutofillProfile profile = PersonalDataManagerJni.get().getProfileByGUID(
                    mPersonalDataManagerAndroid, PersonalDataManager.this, profileGUIDs[i]);
            profile.setLabel(profileLabels[i]);
            profiles.add(profile);
        }

        return profiles;
    }

    public AutofillProfile getProfile(String guid) {
        ThreadUtils.assertOnUiThread();
        return PersonalDataManagerJni.get().getProfileByGUID(
                mPersonalDataManagerAndroid, PersonalDataManager.this, guid);
    }

    public void deleteProfile(String guid) {
        ThreadUtils.assertOnUiThread();
        PersonalDataManagerJni.get().removeByGUID(
                mPersonalDataManagerAndroid, PersonalDataManager.this, guid);
    }

    public String setProfile(AutofillProfile profile) {
        ThreadUtils.assertOnUiThread();
        return PersonalDataManagerJni.get().setProfile(
                mPersonalDataManagerAndroid, PersonalDataManager.this, profile);
    }

    public String setProfileToLocal(AutofillProfile profile) {
        ThreadUtils.assertOnUiThread();
        return PersonalDataManagerJni.get().setProfileToLocal(
                mPersonalDataManagerAndroid, PersonalDataManager.this, profile);
    }

    /**
     * Gets the credit cards to show in the settings page. Returns all the cards without any
     * processing.
     */
    public List<CreditCard> getCreditCardsForSettings() {
        ThreadUtils.assertOnUiThread();
        return getCreditCards(PersonalDataManagerJni.get().getCreditCardGUIDsForSettings(
                mPersonalDataManagerAndroid, PersonalDataManager.this));
    }

    /**
     * Gets the credit cards to suggest when filling a form or completing a transaction. The cards
     * will have been processed to be more relevant to the user.
     * @param includeServerCards Whether server cards should be included in the response.
     */
    public ArrayList<CreditCard> getCreditCardsToSuggest(boolean includeServerCards) {
        ThreadUtils.assertOnUiThread();
        return getCreditCards(PersonalDataManagerJni.get().getCreditCardGUIDsToSuggest(
                mPersonalDataManagerAndroid, PersonalDataManager.this, includeServerCards));
    }

    private ArrayList<CreditCard> getCreditCards(String[] creditCardGUIDs) {
        ArrayList<CreditCard> cards = new ArrayList<CreditCard>(creditCardGUIDs.length);
        for (int i = 0; i < creditCardGUIDs.length; i++) {
            cards.add(PersonalDataManagerJni.get().getCreditCardByGUID(
                    mPersonalDataManagerAndroid, PersonalDataManager.this, creditCardGUIDs[i]));
        }
        return cards;
    }

    public CreditCard getCreditCard(String guid) {
        ThreadUtils.assertOnUiThread();
        return PersonalDataManagerJni.get().getCreditCardByGUID(
                mPersonalDataManagerAndroid, PersonalDataManager.this, guid);
    }

    public CreditCard getCreditCardForNumber(String cardNumber) {
        ThreadUtils.assertOnUiThread();
        return PersonalDataManagerJni.get().getCreditCardForNumber(
                mPersonalDataManagerAndroid, PersonalDataManager.this, cardNumber);
    }

    public String setCreditCard(CreditCard card) {
        ThreadUtils.assertOnUiThread();
        assert card.getIsLocal();
        return PersonalDataManagerJni.get().setCreditCard(
                mPersonalDataManagerAndroid, PersonalDataManager.this, card);
    }

    public void updateServerCardBillingAddress(CreditCard card) {
        ThreadUtils.assertOnUiThread();
        PersonalDataManagerJni.get().updateServerCardBillingAddress(
                mPersonalDataManagerAndroid, PersonalDataManager.this, card);
    }

    public String getBasicCardIssuerNetwork(String cardNumber, boolean emptyIfInvalid) {
        ThreadUtils.assertOnUiThread();
        return PersonalDataManagerJni.get().getBasicCardIssuerNetwork(
                mPersonalDataManagerAndroid, PersonalDataManager.this, cardNumber, emptyIfInvalid);
    }

    @VisibleForTesting
    public void addServerCreditCardForTest(CreditCard card) {
        ThreadUtils.assertOnUiThread();
        assert !card.getIsLocal();
        PersonalDataManagerJni.get().addServerCreditCardForTest(
                mPersonalDataManagerAndroid, PersonalDataManager.this, card);
    }

    @VisibleForTesting
    public void addServerCreditCardForTestWithAdditionalFields(
            CreditCard card, String nickname, int cardIssuer) {
        ThreadUtils.assertOnUiThread();
        assert !card.getIsLocal();
        PersonalDataManagerJni.get().addServerCreditCardForTestWithAdditionalFields(
                mPersonalDataManagerAndroid, PersonalDataManager.this, card, nickname, cardIssuer);
    }

    public void deleteCreditCard(String guid) {
        ThreadUtils.assertOnUiThread();
        PersonalDataManagerJni.get().removeByGUID(
                mPersonalDataManagerAndroid, PersonalDataManager.this, guid);
    }

    public void clearUnmaskedCache(String guid) {
        PersonalDataManagerJni.get().clearUnmaskedCache(
                mPersonalDataManagerAndroid, PersonalDataManager.this, guid);
    }

    public String getShippingAddressLabelWithCountryForPaymentRequest(AutofillProfile profile) {
        return PersonalDataManagerJni.get().getShippingAddressLabelWithCountryForPaymentRequest(
                mPersonalDataManagerAndroid, PersonalDataManager.this, profile);
    }

    public String getShippingAddressLabelWithoutCountryForPaymentRequest(AutofillProfile profile) {
        return PersonalDataManagerJni.get().getShippingAddressLabelWithoutCountryForPaymentRequest(
                mPersonalDataManagerAndroid, PersonalDataManager.this, profile);
    }

    public String getBillingAddressLabelForPaymentRequest(AutofillProfile profile) {
        return PersonalDataManagerJni.get().getBillingAddressLabelForPaymentRequest(
                mPersonalDataManagerAndroid, PersonalDataManager.this, profile);
    }

    public void getFullCard(WebContents webContents, CreditCard card,
            FullCardRequestDelegate delegate) {
        PersonalDataManagerJni.get().getFullCardForPaymentRequest(
                mPersonalDataManagerAndroid, PersonalDataManager.this, webContents, card, delegate);
    }

    /**
     * Records the use of the profile associated with the specified {@code guid}. Effectively
     * increments the use count of the profile and sets its use date to the current time. Also logs
     * usage metrics.
     *
     * @param guid The GUID of the profile.
     */
    public void recordAndLogProfileUse(String guid) {
        ThreadUtils.assertOnUiThread();
        PersonalDataManagerJni.get().recordAndLogProfileUse(
                mPersonalDataManagerAndroid, PersonalDataManager.this, guid);
    }

    @VisibleForTesting
    protected void setProfileUseStatsForTesting(String guid, int count, long date) {
        ThreadUtils.assertOnUiThread();
        PersonalDataManagerJni.get().setProfileUseStatsForTesting(
                mPersonalDataManagerAndroid, PersonalDataManager.this, guid, count, date);
    }

    @VisibleForTesting
    int getProfileUseCountForTesting(String guid) {
        ThreadUtils.assertOnUiThread();
        return PersonalDataManagerJni.get().getProfileUseCountForTesting(
                mPersonalDataManagerAndroid, PersonalDataManager.this, guid);
    }

    @VisibleForTesting
    long getProfileUseDateForTesting(String guid) {
        ThreadUtils.assertOnUiThread();
        return PersonalDataManagerJni.get().getProfileUseDateForTesting(
                mPersonalDataManagerAndroid, PersonalDataManager.this, guid);
    }

    /**
     * Records the use of the credit card associated with the specified {@code guid}. Effectively
     * increments the use count of the credit card and set its use date to the current time. Also
     * logs usage metrics.
     *
     * @param guid The GUID of the credit card.
     */
    public void recordAndLogCreditCardUse(String guid) {
        ThreadUtils.assertOnUiThread();
        PersonalDataManagerJni.get().recordAndLogCreditCardUse(
                mPersonalDataManagerAndroid, PersonalDataManager.this, guid);
    }

    @VisibleForTesting
    protected void setCreditCardUseStatsForTesting(String guid, int count, long date) {
        ThreadUtils.assertOnUiThread();
        PersonalDataManagerJni.get().setCreditCardUseStatsForTesting(
                mPersonalDataManagerAndroid, PersonalDataManager.this, guid, count, date);
    }

    @VisibleForTesting
    int getCreditCardUseCountForTesting(String guid) {
        ThreadUtils.assertOnUiThread();
        return PersonalDataManagerJni.get().getCreditCardUseCountForTesting(
                mPersonalDataManagerAndroid, PersonalDataManager.this, guid);
    }

    @VisibleForTesting
    long getCreditCardUseDateForTesting(String guid) {
        ThreadUtils.assertOnUiThread();
        return PersonalDataManagerJni.get().getCreditCardUseDateForTesting(
                mPersonalDataManagerAndroid, PersonalDataManager.this, guid);
    }

    @VisibleForTesting
    long getCurrentDateForTesting() {
        ThreadUtils.assertOnUiThread();
        return PersonalDataManagerJni.get().getCurrentDateForTesting(
                mPersonalDataManagerAndroid, PersonalDataManager.this);
    }

    /**
     * Starts loading the address validation rules for the specified {@code regionCode}.
     *
     * @param regionCode The code of the region for which to load the rules.
     */
    public void loadRulesForAddressNormalization(String regionCode) {
        ThreadUtils.assertOnUiThread();
        PersonalDataManagerJni.get().loadRulesForAddressNormalization(
                mPersonalDataManagerAndroid, PersonalDataManager.this, regionCode);
    }

    /**
     * Starts loading the sub-key request rules for the specified {@code regionCode}.
     *
     * @param regionCode The code of the region for which to load the rules.
     */
    public void loadRulesForSubKeys(String regionCode) {
        ThreadUtils.assertOnUiThread();
        PersonalDataManagerJni.get().loadRulesForSubKeys(
                mPersonalDataManagerAndroid, PersonalDataManager.this, regionCode);
    }

    /**
     * Starts requesting the subkeys for the specified {@code regionCode}, if the rules
     * associated with the {@code regionCode} are done loading. Otherwise sets up the callback to
     * start loading the subkeys when the rules are loaded. The received subkeys will be sent
     * to the {@code delegate}. If the subkeys are not received in the specified
     * {@code sRequestTimeoutSeconds}, the {@code delegate} will be notified.
     *
     * @param regionCode The code of the region for which to load the subkeys.
     * @param delegate The object requesting the subkeys.
     */
    public void getRegionSubKeys(String regionCode, GetSubKeysRequestDelegate delegate) {
        ThreadUtils.assertOnUiThread();
        PersonalDataManagerJni.get().startRegionSubKeysRequest(mPersonalDataManagerAndroid,
                PersonalDataManager.this, regionCode, sRequestTimeoutSeconds, delegate);
    }

    /** Cancels the pending subkeys request. */
    public void cancelPendingGetSubKeys() {
        ThreadUtils.assertOnUiThread();
        PersonalDataManagerJni.get().cancelPendingGetSubKeys(mPersonalDataManagerAndroid);
    }

    /**
     * Normalizes the address of the profile associated with the {@code guid} if the rules
     * associated with the profile's region are done loading. Otherwise sets up the callback to
     * start normalizing the address when the rules are loaded. The normalized profile will be sent
     * to the {@code delegate}. If the profile is not normalized in the specified
     * {@code sRequestTimeoutSeconds}, the {@code delegate} will be notified.
     *
     * @param profile The profile to normalize.
     * @param delegate The object requesting the normalization.
     */
    public void normalizeAddress(
            AutofillProfile profile, NormalizedAddressRequestDelegate delegate) {
        ThreadUtils.assertOnUiThread();
        PersonalDataManagerJni.get().startAddressNormalization(mPersonalDataManagerAndroid,
                PersonalDataManager.this, profile, sRequestTimeoutSeconds, delegate);
    }

    /**
     * Checks whether the Autofill PersonalDataManager has profiles.
     *
     * @return True If there are profiles.
     */
    public boolean hasProfiles() {
        return PersonalDataManagerJni.get().hasProfiles(mPersonalDataManagerAndroid);
    }

    /**
     * Checks whether the Autofill PersonalDataManager has credit cards.
     *
     * @return True If there are credit cards.
     */
    public boolean hasCreditCards() {
        return PersonalDataManagerJni.get().hasCreditCards(mPersonalDataManagerAndroid);
    }

    /**
     * @return Whether FIDO authentication is available.
     */
    public boolean isFidoAuthenticationAvailable() {
        return isAutofillCreditCardEnabled()
                && PersonalDataManagerJni.get().isFidoAuthenticationAvailable(
                        mPersonalDataManagerAndroid);
    }

    /**
     * @return Whether the Autofill feature for Profiles (addresses) is enabled.
     */
    public static boolean isAutofillProfileEnabled() {
        return PrefServiceBridge.getInstance().getBoolean(Pref.AUTOFILL_PROFILE_ENABLED);
    }

    /**
     * @return Whether the Autofill feature for Credit Cards is enabled.
     */
    public static boolean isAutofillCreditCardEnabled() {
        return PrefServiceBridge.getInstance().getBoolean(Pref.AUTOFILL_CREDIT_CARD_ENABLED);
    }

    /**
     * Enables or disables the Autofill feature for Profiles.
     * @param enable True to disable profile Autofill, false otherwise.
     */
    public static void setAutofillProfileEnabled(boolean enable) {
        PrefServiceBridge.getInstance().setBoolean(Pref.AUTOFILL_PROFILE_ENABLED, enable);
    }

    /**
     * Enables or disables the Autofill feature for Credit Cards.
     * @param enable True to disable credit card Autofill, false otherwise.
     */
    public static void setAutofillCreditCardEnabled(boolean enable) {
        PrefServiceBridge.getInstance().setBoolean(Pref.AUTOFILL_CREDIT_CARD_ENABLED, enable);
    }

    /**
     * @return Whether the Autofill feature for FIDO authentication is enabled.
     */
    public static boolean isAutofillCreditCardFidoAuthEnabled() {
        return PrefServiceBridge.getInstance().getBoolean(
                Pref.AUTOFILL_CREDIT_CARD_FIDO_AUTH_ENABLED);
    }

    /**
     * Enables or disables the Autofill feature for FIDO authentication.
     * We are trying to align this pref with the server's source of truth, but any mismatches
     * between this pref and the server should imply the user's intention to opt in/out.
     * @param enable True to enable credit card FIDO authentication, false otherwise.
     */
    public static void setAutofillCreditCardFidoAuthEnabled(boolean enable) {
        PrefServiceBridge.getInstance().setBoolean(
                Pref.AUTOFILL_CREDIT_CARD_FIDO_AUTH_ENABLED, enable);
    }

    /**
     * @return Whether the Autofill feature is managed.
     */
    public static boolean isAutofillManaged() {
        return PersonalDataManagerJni.get().isAutofillManaged();
    }

    /**
     * @return Whether the Autofill feature for Profiles (addresses) is managed.
     */
    public static boolean isAutofillProfileManaged() {
        return PersonalDataManagerJni.get().isAutofillProfileManaged();
    }

    /**
     * @return Whether the Autofill feature for Credit Cards is managed.
     */
    public static boolean isAutofillCreditCardManaged() {
        return PersonalDataManagerJni.get().isAutofillCreditCardManaged();
    }

    /**
     * @return Whether the Payments integration feature is enabled.
     */
    public static boolean isPaymentsIntegrationEnabled() {
        return PersonalDataManagerJni.get().isPaymentsIntegrationEnabled();
    }

    /**
     * Enables or disables the Payments integration.
     * @param enable True to enable Payments data import.
     */
    public static void setPaymentsIntegrationEnabled(boolean enable) {
        PersonalDataManagerJni.get().setPaymentsIntegrationEnabled(enable);
    }

    @VisibleForTesting
    public static void setRequestTimeoutForTesting(int timeout) {
        sRequestTimeoutSeconds = timeout;
    }

    @VisibleForTesting
    public void setSyncServiceForTesting() {
        PersonalDataManagerJni.get().setSyncServiceForTesting(mPersonalDataManagerAndroid);
    }

    /**
     * @return The sub-key request timeout in milliseconds.
     */
    public static long getRequestTimeoutMS() {
        return DateUtils.SECOND_IN_MILLIS * sRequestTimeoutSeconds;
    }

    @NativeMethods
    interface Natives {
        long init(PersonalDataManager caller);
        boolean isDataLoaded(long nativePersonalDataManagerAndroid, PersonalDataManager caller);
        String[] getProfileGUIDsForSettings(
                long nativePersonalDataManagerAndroid, PersonalDataManager caller);
        String[] getProfileGUIDsToSuggest(
                long nativePersonalDataManagerAndroid, PersonalDataManager caller);
        String[] getProfileLabelsForSettings(
                long nativePersonalDataManagerAndroid, PersonalDataManager caller);
        String[] getProfileLabelsToSuggest(long nativePersonalDataManagerAndroid,
                PersonalDataManager caller, boolean includeNameInLabel,
                boolean includeOrganizationInLabel, boolean includeCountryInLabel);
        AutofillProfile getProfileByGUID(
                long nativePersonalDataManagerAndroid, PersonalDataManager caller, String guid);
        String setProfile(long nativePersonalDataManagerAndroid, PersonalDataManager caller,
                AutofillProfile profile);
        String setProfileToLocal(long nativePersonalDataManagerAndroid, PersonalDataManager caller,
                AutofillProfile profile);
        String getShippingAddressLabelWithCountryForPaymentRequest(
                long nativePersonalDataManagerAndroid, PersonalDataManager caller,
                AutofillProfile profile);
        String getShippingAddressLabelWithoutCountryForPaymentRequest(
                long nativePersonalDataManagerAndroid, PersonalDataManager caller,
                AutofillProfile profile);
        String getBillingAddressLabelForPaymentRequest(long nativePersonalDataManagerAndroid,
                PersonalDataManager caller, AutofillProfile profile);
        String[] getCreditCardGUIDsForSettings(
                long nativePersonalDataManagerAndroid, PersonalDataManager caller);
        String[] getCreditCardGUIDsToSuggest(long nativePersonalDataManagerAndroid,
                PersonalDataManager caller, boolean includeServerCards);
        CreditCard getCreditCardByGUID(
                long nativePersonalDataManagerAndroid, PersonalDataManager caller, String guid);
        CreditCard getCreditCardForNumber(long nativePersonalDataManagerAndroid,
                PersonalDataManager caller, String cardNumber);
        String setCreditCard(
                long nativePersonalDataManagerAndroid, PersonalDataManager caller, CreditCard card);
        void updateServerCardBillingAddress(
                long nativePersonalDataManagerAndroid, PersonalDataManager caller, CreditCard card);
        String getBasicCardIssuerNetwork(long nativePersonalDataManagerAndroid,
                PersonalDataManager caller, String cardNumber, boolean emptyIfInvalid);
        void addServerCreditCardForTest(
                long nativePersonalDataManagerAndroid, PersonalDataManager caller, CreditCard card);
        void addServerCreditCardForTestWithAdditionalFields(long nativePersonalDataManagerAndroid,
                PersonalDataManager caller, CreditCard card, String nickname, int cardIssuer);
        void removeByGUID(
                long nativePersonalDataManagerAndroid, PersonalDataManager caller, String guid);
        void recordAndLogProfileUse(
                long nativePersonalDataManagerAndroid, PersonalDataManager caller, String guid);
        void setProfileUseStatsForTesting(long nativePersonalDataManagerAndroid,
                PersonalDataManager caller, String guid, int count, long date);
        int getProfileUseCountForTesting(
                long nativePersonalDataManagerAndroid, PersonalDataManager caller, String guid);
        long getProfileUseDateForTesting(
                long nativePersonalDataManagerAndroid, PersonalDataManager caller, String guid);
        void recordAndLogCreditCardUse(
                long nativePersonalDataManagerAndroid, PersonalDataManager caller, String guid);
        void setCreditCardUseStatsForTesting(long nativePersonalDataManagerAndroid,
                PersonalDataManager caller, String guid, int count, long date);
        int getCreditCardUseCountForTesting(
                long nativePersonalDataManagerAndroid, PersonalDataManager caller, String guid);
        long getCreditCardUseDateForTesting(
                long nativePersonalDataManagerAndroid, PersonalDataManager caller, String guid);
        long getCurrentDateForTesting(
                long nativePersonalDataManagerAndroid, PersonalDataManager caller);
        void clearUnmaskedCache(
                long nativePersonalDataManagerAndroid, PersonalDataManager caller, String guid);
        void getFullCardForPaymentRequest(long nativePersonalDataManagerAndroid,
                PersonalDataManager caller, WebContents webContents, CreditCard card,
                FullCardRequestDelegate delegate);
        void loadRulesForAddressNormalization(long nativePersonalDataManagerAndroid,
                PersonalDataManager caller, String regionCode);
        void loadRulesForSubKeys(long nativePersonalDataManagerAndroid, PersonalDataManager caller,
                String regionCode);
        void startAddressNormalization(long nativePersonalDataManagerAndroid,
                PersonalDataManager caller, AutofillProfile profile, int timeoutSeconds,
                NormalizedAddressRequestDelegate delegate);
        void startRegionSubKeysRequest(long nativePersonalDataManagerAndroid,
                PersonalDataManager caller, String regionCode, int timeoutSeconds,
                GetSubKeysRequestDelegate delegate);
        boolean hasProfiles(long nativePersonalDataManagerAndroid);
        boolean hasCreditCards(long nativePersonalDataManagerAndroid);
        boolean isFidoAuthenticationAvailable(long nativePersonalDataManagerAndroid);
        boolean isAutofillManaged();
        boolean isAutofillProfileManaged();
        boolean isAutofillCreditCardManaged();
        boolean isPaymentsIntegrationEnabled();
        void setPaymentsIntegrationEnabled(boolean enable);
        String toCountryCode(String countryName);
        void cancelPendingGetSubKeys(long nativePersonalDataManagerAndroid);
        void setSyncServiceForTesting(long nativePersonalDataManagerAndroid);
    }
}


text:
<?php

class Toro
{
    public static function serve($routes)
    {
        ToroHook::fire('before_request', compact('routes'));

        $request_method = strtolower($_SERVER['REQUEST_METHOD']);
        $path_info = '/';

	    $pos = strpos($_SERVER['REQUEST_URI'], "?");
        if ($pos == false)
            $result = $_SERVER['REQUEST_URI'];
        else
            $result = substr($_SERVER['REQUEST_URI'], 0, $pos);

        if ($result !== $_SERVER['SCRIPT_NAME']){
        } else if (!empty($_SERVER['PATH_INFO'])) {
            $path_info = $_SERVER['PATH_INFO'];
        }
        else if (!empty($_SERVER['ORIG_PATH_INFO']) && $_SERVER['ORIG_PATH_INFO'] !== '/index.php') {
            $path_info = $_SERVER['ORIG_PATH_INFO'];
        }
        else {
            if (!empty($_SERVER['REQUEST_URI'])) {
                $path_info = (strpos($_SERVER['REQUEST_URI'], '?') > 0) ? strstr($_SERVER['REQUEST_URI'], '?', true) : $_SERVER['REQUEST_URI'];
            }
        }

        $discovered_handler = null;
        $regex_matches = array();

        if (isset($routes[$path_info])) {
            $discovered_handler = $routes[$path_info];
        }
        else if ($routes) {
            $tokens = array(
                ':string' => '([a-zA-Z]+)',
                ':number' => '([0-9]+)',
                ':alpha'  => '([a-zA-Z0-9-_]+)'
            );
            foreach ($routes as $pattern => $handler_name) {
                $pattern = strtr($pattern, $tokens);
                if (preg_match('#^/?' . $pattern . '/?$#', $path_info, $matches)) {
                    $discovered_handler = $handler_name;
                    $regex_matches = $matches;
                    break;
                }
            }
        }

        $result = null;

        $handler_instance = null;
        if ($discovered_handler) {
            if (is_string($discovered_handler)) {
                $handler_instance = new $discovered_handler();
            }
            elseif (is_callable($discovered_handler)) {
                $handler_instance = $discovered_handler();
            }
        }

        $notFoundHook = '404';
        if (self::is_xhr_request())
            $notFoundHook .= '_xhr';

        if ($handler_instance) {
            unset($regex_matches[0]);

            if (self::is_xhr_request() && method_exists($handler_instance, $request_method . '_xhr')) {
                header('Content-type: application/json');
                header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
                header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
                header('Cache-Control: no-store, no-cache, must-revalidate');
                header('Cache-Control: post-check=0, pre-check=0', false);
                header('Pragma: no-cache');
                $request_method .= '_xhr';
            }

            if (method_exists($handler_instance, $request_method)) {
                ToroHook::fire('before_handler', compact('routes', 'discovered_handler', 'request_method', 'regex_matches'));
                $result = call_user_func_array(array($handler_instance, $request_method), $regex_matches);
                $ret_code = http_response_code();
                if ($ret_code != 200) {
                    if (self::is_xhr_request())
                        $ret_code .= '_xhr';
                    ToroHook::fire($ret_code . "", compact('routes', 'discovered_handler', 'request_method', 'regex_matches'));
                }
                ToroHook::fire('after_handler', compact('routes', 'discovered_handler', 'request_method', 'regex_matches', 'result'));
            }
            else {
                ToroHook::fire($notFoundHook, compact('routes', 'discovered_handler', 'request_method', 'regex_matches'));
                http_response_code(404);

            }
        }
        else {
            ToroHook::fire($notFoundHook, compact('routes', 'discovered_handler', 'request_method', 'regex_matches'));
            http_response_code(404);
        }

        ToroHook::fire('after_request', compact('routes', 'discovered_handler', 'request_method', 'regex_matches', 'result'));
    }

    private static function is_xhr_request()
    {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
    }
}

class ToroHook
{
    private static $instance;

    private $hooks = array();

    private function __construct() {}
    private function __clone() {}

    public static function add($hook_name, $fn)
    {
        $instance = self::get_instance();
        $instance->hooks[$hook_name][] = $fn;
    }

    public static function fire($hook_name, $params = null)
    {
        $instance = self::get_instance();
        if (isset($instance->hooks[$hook_name])) {
            foreach ($instance->hooks[$hook_name] as $fn) {
                call_user_func_array($fn, array(&$params));
            }
        }
    }

    public static function get_instance()
    {
        if (empty(self::$instance)) {
            self::$instance = new ToroHook();
        }
        return self::$instance;
    }
}


text:
<?php namespace Anomaly\UsersModule\User\Notification;

use Anomaly\Streams\Platform\Notification\Message\MailMessage;
use Anomaly\UsersModule\User\Contract\UserInterface;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notifiable;
use Illuminate\Notifications\Notification;

/**
 * Class UserHasRegistered
 *
 * @link   http://pyrocms.com/
 * @author PyroCMS, Inc. <support@pyrocms.com>
 * @author Ryan Thompson <ryan@pyrocms.com>
 */
class UserHasRegistered extends Notification implements ShouldQueue
{

    use Queueable;

    /**
     * The user who registered.
     *
     * @var UserInterface
     */
    public $user;

    /**
     * Create a new UserHasRegistered instance.
     *
     * @param UserInterface $user
     */
    public function __construct(UserInterface $user)
    {
        $this->user = $user;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  UserInterface $notifiable
     * @return array
     */
    public function via(UserInterface $notifiable)
    {
        return ['mail', 'slack', 'database'];
    }

    /**
     * Return the mail message.
     *
     * @param  UserInterface $notifiable
     * @return MailMessage
     */
    public function toMail(UserInterface $notifiable)
    {
        $data = $this->user->toArray();

        return (new MailMessage())
            ->success()
            ->view('anomaly.module.users::notifications.user_has_registered')
            ->subject(trans('anomaly.module.users::notification.user_has_registered.subject', $data))
            ->line(trans('anomaly.module.users::notification.user_has_registered.instructions', $data))
            ->action(
                trans('anomaly.module.users::notification.user_has_registered.button', $data),
                $this->user->route('view')
            );
    }

    /**
     * Return the slack message.
     *
     * @param UserInterface $notifiable
     *
     * @return SlackMessage
     */
    public function toSlack(UserInterface $notifiable)
    {
        return (new SlackMessage())
            ->success()
            ->content('Hmm.. What\'s Ryan up to?')
            ->attachment(
                function ($attachment) {
                    $attachment
                        ->title('Testing out teh goodies!', 'http://pyrocms.com/')
                        ->fields(
                            [
                                'Username' => $this->user->getUsername(),
                                'Eamil'    => $this->user->getEmail(),
                            ]
                        );
                }
            );;
    }

    /**
     * Return the array storage data.
     *
     * @param Notifiable $notifiable
     *
     * @return array
     */
    public function toDatabase(UserInterface $notifiable)
    {
        return [
            'user' => $this->user,
        ];
    }
}


text:
<?xml version="1.0"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.commonsware.android.dialer">

	<supports-screens
		android:anyDensity="true"
		android:largeScreens="true"
		android:normalScreens="true"
		android:smallScreens="true"/>

	<uses-sdk
		android:minSdkVersion="7"
		android:targetSdkVersion="11"/>

	<application android:icon="@drawable/ic_launcher">
		<activity
			android:name=".DialerDemo"
			android:label="DialerDemo">
			<intent-filter>
				<action android:name="android.intent.action.MAIN"/>

				<category android:name="android.intent.category.LAUNCHER"/>
			</intent-filter>
		</activity>
	</application>

</manifest>


text:
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
        <meta name="keywords" content="{% if page.keywords %}{{ page.keywords | join: ',' }}{% endif %}" />
        <meta name="description" content="{% if page.description %}{{ page.description }}{% endif %}" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>{% if page.title %} {{ page.title }} {% else %} {{ site.title }} {% endif %} </title>
        <link rel="stylesheet" href="{{ site.baseurl }}/css/default.css" type="text/css" />
        <link rel="stylesheet" href="{{ site.baseurl }}/css/small.css" type="text/css" media="(max-width: 720px)"/>
        <link rel="stylesheet" href="{{ site.baseurl }}/css/syntax.css" type="text/css" />
        <link rel="shortcut icon" href="{{ site.baseurl }}/favicon.ico" type="image/x-icon" />
        <!-- Global site tag (gtag.js) - Google Analytics -->
        <script async src="https://www.googletagmanager.com/gtag/js?id=G-DJ678YCF2C"></script>
        <script>
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());

          gtag('config', 'G-DJ678YCF2C');
        </script>
    </head>
    <body>


text:
@interface PodsDummy_Pods_MGImageUtilities : NSObject
{
}

@end


text:
package com.box.androidsdk.content.models;

import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Class representing a box upload session for supporting multiput
 * e.g. {
 "total_parts": 2,
 "part_size": 8388608,
 "session_endpoints": {
 "list_parts": "https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD/parts",
 "commit": "https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD/commit",
 "upload_part": "https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD",
 "status": "https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD",
 "abort": "https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD"
 },
 "session_expires_at": "2017-04-18T01:45:15Z",
 "id": "F971964745A5CD0C001BBE4E58196BFD",
 "type": "upload_session",
 "num_parts_processed": 0
 }
 */

public class BoxUploadSession extends BoxJsonObject {
    private static final long serialVersionUID = -9126113409457878881L;
    public static final String FIELD_TYPE = "upload_session";

    private static final String FIELD_SHA1 = "fileSha1";
    private static final String FIELD_PARTS_SHA1 = "partsSha1";

    public static final String FIELD_TOTAL_PARTS = "total_parts";
    public static final String FIELD_PART_SIZE = "part_size";
    public static final String FIELD_SESSION_ENDPOINTS = "session_endpoints";

    public static final String FIELD_SESSION_EXPIRES_AT = "session_expires_at";
    public static final String FIELD_ID = "id";
    public static final String FIELD_NUM_PARTS_PROCESSED = "num_parts_processed";

    public static final String[] ALL_FIELDS = new String[]{
            FIELD_TYPE,
            FIELD_ID,
            FIELD_TOTAL_PARTS,
            FIELD_NUM_PARTS_PROCESSED,
            FIELD_PART_SIZE,
            FIELD_SESSION_ENDPOINTS,
            FIELD_SESSION_EXPIRES_AT,
            FIELD_SHA1,
            FIELD_PARTS_SHA1
    };

    /**
     * Constructs an empty BoxUploadSession object.
     */
    public BoxUploadSession() {
        super();
    }

    /**
     * Constructs an empty BoxUploadSession object.
     * @param object  jsonObject to use to create an instance of this class.
     */
    public BoxUploadSession(JsonObject object) {
        super(object);
    }

    /**
     * Get total parts for the session
     * @return
     */
    public int getTotalParts() {
        return getPropertyAsInt(FIELD_TOTAL_PARTS);
    }

    /**
     * Get num of parts processed
     * @return
     */
    public int getNumPartsProcessed() {
        return getPropertyAsInt(FIELD_NUM_PARTS_PROCESSED);
    }

    /**
     * Get part size in bytes
     * @return
     */
    public int getPartSize() {
        return getPropertyAsInt(FIELD_PART_SIZE);
    }

    /**
     * Get an endpoints object for the session
     */
    public BoxUploadSessionEndpoints getEndpoints() {
        return getPropertyAsJsonObject(BoxEntity.getBoxJsonObjectCreator(BoxUploadSessionEndpoints.class), FIELD_SESSION_ENDPOINTS);
    }

    /**
     * Get expires at date for the session
     * @return
     */
    public Date getExpiresAt() {
        return getPropertyAsDate(FIELD_SESSION_EXPIRES_AT);
    }

    /**
     * Get the session id
     * @return
     */

    public String getId() {
        return getPropertyAsString(FIELD_ID);
    }

    /**
     * Util method for sha1 for the file.
     */
    public void setSha1(String sha1) {
        set(FIELD_SHA1, sha1);
    }

    public String getSha1() {
        return getPropertyAsString(FIELD_SHA1);
    }

    /**
     * Util method for storing sha1 for parts being uploaded
     */
    public void setPartsSha1(List<String> sha1s) {
        JsonArray jsonArray = new JsonArray();
        for (String s : sha1s) {
            jsonArray.add(s);
        }
        set(FIELD_PARTS_SHA1, jsonArray);
    }

    /**
     * Return stored list of sha1s for parts
     * @return
     */
    public ArrayList<String> getFieldPartsSha1() {
        return getPropertyAsStringArray(FIELD_PARTS_SHA1);
    }

    /**
     * Computes the actual bytes to be sent in a part, which equals the partsize for all parts
     * except the last.
     * @param uploadSession
     * @param partNumber
     * @param fileSize
     * @return
     */
    public static int getChunkSize(BoxUploadSession uploadSession, int partNumber, long fileSize) {
        if (partNumber == uploadSession.getTotalParts() - 1) {
            return (int) (fileSize - partNumber * uploadSession.getPartSize());
        }
        return uploadSession.getPartSize();
    }
}