text:
from itertools import zip_longest, combinations
import json
import os
import warnings

import numpy as np

import tvm
from tvm import relay
from tvm import rpc
from tvm.contrib import graph_executor
from tvm.relay.op.contrib import arm_compute_lib
from tvm.contrib import utils
from tvm.autotvm.measure import request_remote

class Device:
    """
    Configuration for Arm Compute Library tests.

    Check tests/python/contrib/arm_compute_lib/ for the presence of an test_config.json file.
    This file can be used to override the default configuration here which will attempt to run the Arm
    Compute Library runtime tests locally if the runtime is available. Changing the configuration
    will allow these runtime tests to be offloaded to a remote Arm device via a tracker for example.

    Notes
    -----
        The test configuration will be loaded once when the the class is created. If the configuration
        changes between tests, any changes will not be picked up.

    Parameters
    ----------
    device : RPCSession
        Allows tests to connect to and use remote device.

    Attributes
    ----------
    connection_type : str
        Details the type of RPC connection to use. Options:
        local - Use the local device,
        tracker - Connect to a tracker to request a remote device,
        remote - Connect to a remote device directly.
    host : str
        Specify IP address or hostname of remote target.
    port : int
        Specify port number of remote target.
    target : str
        The compilation target.
    device_key : str
        The device key of the remote target. Use when connecting to a remote device via a tracker.
    cross_compile : str
        Specify path to cross compiler to use when connecting a remote device from a non-arm platform.
    """

    connection_type = "local"
    host = "127.0.0.1"
    port = 9090
    target = "llvm -mtriple=aarch64-linux-gnu -mattr=+neon"
    device_key = ""
    cross_compile = ""

    def __init__(self):
        """Keep remote device for lifetime of object."""
        self.device = self._get_remote()

    @classmethod
    def _get_remote(cls):
        """Get a remote (or local) device to use for testing."""
        if cls.connection_type == "tracker":
            device = request_remote(cls.device_key, cls.host, cls.port, timeout=1000)
        elif cls.connection_type == "remote":
            device = rpc.connect(cls.host, cls.port)
        elif cls.connection_type == "local":
            device = rpc.LocalSession()
        else:
            raise ValueError(
                "connection_type in test_config.json should be one of: " "local, tracker, remote."
            )

        return device

    @classmethod
    def load(cls, file_name):
        """Load test config

        Load the test configuration by looking for file_name relative
        to the test_arm_compute_lib directory.
        """
        location = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
        config_file = os.path.join(location, file_name)
        if not os.path.exists(config_file):
            warnings.warn(
                "Config file doesn't exist, resuming Arm Compute Library tests with default config."
            )
            return
        with open(config_file, mode="r") as config:
            test_config = json.load(config)

        cls.connection_type = test_config["connection_type"]
        cls.host = test_config["host"]
        cls.port = test_config["port"]
        cls.target = test_config["target"]
        cls.device_key = test_config.get("device_key") or ""
        cls.cross_compile = test_config.get("cross_compile") or ""

def get_cpu_op_count(mod):
    """Traverse graph counting ops offloaded to TVM."""

    class Counter(tvm.relay.ExprVisitor):
        def __init__(self):
            super().__init__()
            self.count = 0

        def visit_call(self, call):
            if isinstance(call.op, tvm.ir.Op):
                self.count += 1

            super().visit_call(call)

    c = Counter()
    c.visit(mod["main"])
    return c.count

def skip_runtime_test():
    """Skip test if it requires the runtime and it's not present."""
    # ACL codegen not present.
    if not tvm.get_global_func("relay.ext.arm_compute_lib", True):
        print("Skip because Arm Compute Library codegen is not available.")
        return True

    # Remote device is in use or ACL runtime not present
    # Note: Ensure that the device config has been loaded before this check
    if (
        not Device.connection_type != "local"
        and not arm_compute_lib.is_arm_compute_runtime_enabled()
    ):
        print("Skip because runtime isn't present or a remote device isn't being used.")
        return True

def skip_codegen_test():
    """Skip test if it requires the ACL codegen and it's not present."""
    if not tvm.get_global_func("relay.ext.arm_compute_lib", True):
        print("Skip because Arm Compute Library codegen is not available.")
        return True

def build_module(mod, target, params=None, enable_acl=True, tvm_ops=0, acl_partitions=1):
    """Build module with option to build for ACL."""
    if isinstance(mod, tvm.relay.expr.Call):
        mod = tvm.IRModule.from_expr(mod)
    with tvm.transform.PassContext(opt_level=3, disabled_pass=["AlterOpLayout"]):
        if enable_acl:
            mod = arm_compute_lib.partition_for_arm_compute_lib(mod, params)
            tvm_op_count = get_cpu_op_count(mod)
            assert tvm_op_count == tvm_ops, "Got {} TVM operators, expected {}".format(
                tvm_op_count, tvm_ops
            )
            partition_count = 0
            for global_var in mod.get_global_vars():
                if "arm_compute_lib" in global_var.name_hint:
                    partition_count += 1

            assert (
                acl_partitions == partition_count
            ), "Got {} Arm Compute Library partitions, expected {}".format(
                partition_count, acl_partitions
            )
        relay.backend.te_compiler.get().clear()
        return relay.build(mod, target=target, params=params)

def build_and_run(
    mod,
    inputs,
    outputs,
    params,
    device,
    enable_acl=True,
    no_runs=1,
    tvm_ops=0,
    acl_partitions=1,
    config=None,
):
    """Build and run the relay module."""
    if config is None:
        config = {}

    try:
        lib = build_module(mod, device.target, params, enable_acl, tvm_ops, acl_partitions)
    except Exception as e:
        err_msg = "The module could not be built.\n"
        if config:
            err_msg += f"The test failed with the following parameters: {config}\n"
        err_msg += str(e)
        raise Exception(err_msg)

    lib = update_lib(lib, device.device, device.cross_compile)
    gen_module = graph_executor.GraphModule(lib["default"](device.device.cpu(0)))
    gen_module.set_input(**inputs)
    out = []
    for _ in range(no_runs):
        gen_module.run()
        out.append([gen_module.get_output(i) for i in range(outputs)])
    return out

def update_lib(lib, device, cross_compile):
    """Export the library to the remote/local device."""
    lib_name = "mod.so"
    temp = utils.tempdir()
    lib_path = temp.relpath(lib_name)
    if cross_compile:
        lib.export_library(lib_path, cc=cross_compile)
    else:
        lib.export_library(lib_path)
    device.upload(lib_path)
    lib = device.load_module(lib_name)
    return lib

def verify(answers, atol, rtol, verify_saturation=False, config=None):
    """Compare the array of answers. Each entry is a list of outputs."""
    if config is None:
        config = {}

    if len(answers) < 2:
        raise RuntimeError(f"No results to compare: expected at least two, found {len(answers)}")
    for answer in zip_longest(*answers):
        for outs in combinations(answer, 2):
            try:
                if verify_saturation:
                    assert (
                        np.count_nonzero(outs[0].numpy() == 255) < 0.25 * outs[0].numpy().size
                    ), "Output is saturated: {}".format(outs[0])
                    assert (
                        np.count_nonzero(outs[0].numpy() == 0) < 0.25 * outs[0].numpy().size
                    ), "Output is saturated: {}".format(outs[0])
                tvm.testing.assert_allclose(outs[0].numpy(), outs[1].numpy(), rtol=rtol, atol=atol)
            except AssertionError as e:
                err_msg = "Results not within the acceptable tolerance.\n"
                if config:
                    err_msg += f"The test failed with the following parameters: {config}\n"
                err_msg += str(e)
                raise AssertionError(err_msg)

def extract_acl_modules(module):
    """Get the ACL module(s) from llvm module."""
    return list(
        filter(lambda mod: mod.type_key == "arm_compute_lib", module.get_lib().imported_modules)
    )

def verify_codegen(
    module,
    known_good_codegen,
    num_acl_modules=1,
    tvm_ops=0,
    target="llvm -mtriple=aarch64-linux-gnu -mattr=+neon",
):
    """Check acl codegen against a known good output."""
    module = build_module(module, target, tvm_ops=tvm_ops, acl_partitions=num_acl_modules)
    acl_modules = extract_acl_modules(module)

    assert len(acl_modules) == num_acl_modules, (
        f"The number of Arm Compute Library modules produced ({len(acl_modules)}) does not "
        f"match the expected value ({num_acl_modules})."
    )

    for mod in acl_modules:
        source = mod.get_source("json")
        codegen = json.loads(source)["nodes"]
        # remove input and const names as these cannot be predetermined
        for node in range(len(codegen)):
            if codegen[node]["op"] == "input" or codegen[node]["op"] == "const":
                codegen[node]["name"] = ""
        codegen_str = json.dumps(codegen, sort_keys=True, indent=2)
        known_good_codegen_str = json.dumps(known_good_codegen, sort_keys=True, indent=2)

        assert codegen_str == known_good_codegen_str, (
            f"The JSON produced by codegen does not match the expected result. \n"
            f"Actual={codegen_str} \n"
            f"Expected={known_good_codegen_str}"
        )


text:
class cached_property(object):
    def __init__(self, func):
        self.__doc__ = getattr(func, '__doc__')
        self.func = func

    def __get__(self, obj, cls):
        if obj is None:
            return self

        value = obj.__dict__[self.func.__name__] = self.func(obj)
        return value

redpajama_set_name: RedPajamaGithub


text:
package org.apache.harmony.luni.internal.locale;
public class Language_mr extends java.util.ListResourceBundle {
protected Object[][] getContents() {
	Object[][] contents = {
		{"mr","\u092e\u0930\u093e\u0920\u0940",},
	};
return contents;
}
}


text:
import { cloneDeep, first } from "lodash"
import "react-native"
import { graphql, QueryRenderer } from "react-relay"
import { createMockEnvironment, MockPayloadGenerator } from "relay-test-utils"

import { navigate } from "app/navigation/navigate"

import { AuctionResultsRailTestsQuery } from "__generated__/AuctionResultsRailTestsQuery.graphql"
import { SectionTitle } from "app/Components/SectionTitle"
import { renderWithWrappersLEGACY } from "app/tests/renderWithWrappers"
import { AuctionResultsRailFragmentContainer } from "./AuctionResultsRail"

jest.unmock("react-relay")

describe("AuctionResultsRailFragmentContainer", () => {
  let env: ReturnType<typeof createMockEnvironment>

  const TestRenderer = () => (
    <QueryRenderer<AuctionResultsRailTestsQuery>
      environment={env}
      query={graphql`
        query AuctionResultsRailTestsQuery @raw_response_type {
          me {
            ...AuctionResultsRail_me
          }
        }
      `}
      variables={{}}
      render={({ props, error }) => {
        if (props) {
          return <AuctionResultsRailFragmentContainer title="Auction Results" me={props.me!} />
        } else if (error) {
          console.log(error)
        }
      }}
    />
  )

  beforeEach(() => {
    env = createMockEnvironment()
  })

  it("doesn't throw when rendered", () => {
    renderWithWrappersLEGACY(<TestRenderer />)
    env.mock.resolveMostRecentOperation((operation) =>
      MockPayloadGenerator.generate(operation, {
        Query: () => ({
          me: meResponseMock,
        }),
      })
    )
  })

  it("looks correct when rendered with sales missing auctionResultsByFollowedArtists", () => {
    const auctionResultsCopy = cloneDeep(meResponseMock)
    auctionResultsCopy.results.forEach((result) => {
      result.auctionResultsByFollowedArtists.edges = []
    })

    renderWithWrappersLEGACY(<TestRenderer />)
    env.mock.resolveMostRecentOperation((operation) =>
      MockPayloadGenerator.generate(operation, {
        Query: () => ({
          me: auctionResultsCopy,
        }),
      })
    )
  })

  it("routes to auction-results-for-artists-you-follow URL", () => {
    const tree = renderWithWrappersLEGACY(<TestRenderer />)
    env.mock.resolveMostRecentOperation((operation) =>
      MockPayloadGenerator.generate(operation, {
        Query: () => ({
          me: meResponseMock,
        }),
      })
    )

    first(tree.root.findAllByType(SectionTitle))?.props.onPress()
    expect(navigate).toHaveBeenCalledWith("/auction-results-for-artists-you-follow")
  })
})

const auctionResultEdge = {
  cursor: "YXJyYXljb25uZWN0aW9uOjA=",
  node: {
    id: "QXVjdGlvblJlc3VsdDozMzM5NTI=",
    artistID: "4d8b92bb4eb68a1b2c000452",
    artist: {
      name: "Takashi Murakami",
    },
    internalID: "333952",
    title: "Enso: The Sound of the Bell of Paired Sal Trees",
    currency: "HKD",
    dateText: "2015",
    mediumText: "acrylic on canvas mounted on aluminum frame",
    saleDate: "2021-06-01T03:00:00+03:00",
    organization: "Phillips",
    boughtIn: false,
    priceRealized: {
      cents: 315000000,
      display: "HK$3,150,000",
      displayUSD: "$30,000",
    },
    performance: {
      mid: "70%",
    },
    images: {
      thumbnail: {
        url: "https://d2v80f5yrouhh2.cloudfront.net/OTJxNHuhGDnPi8wQcvXvxA/thumbnail.jpg",
      },
    },
  },
}
const meResponseMock = {
  results: [
    {
      auctionResultsByFollowedArtists: {
        totalCount: 1510,
        edges: [auctionResultEdge, auctionResultEdge, auctionResultEdge],
      },
    },
  ],
}


text:
package joshie.harvest.npcs.greeting;

import joshie.harvest.api.npc.IInfoButton;
import joshie.harvest.api.npc.NPC;
import joshie.harvest.core.helpers.TextHelper;
import joshie.harvest.quests.Quests;
import joshie.harvest.town.TownHelper;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.EntityAgeable;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

import static joshie.harvest.core.lib.HFModInfo.ICONS;

public class GreetingSupermarket implements IInfoButton {
    private final String text;
    private final String text2;

    public GreetingSupermarket(NPC npc) {
        ResourceLocation resourceLocation = npc.getResource();
        this.text = resourceLocation.getResourceDomain() + ".npc." + resourceLocation.getResourcePath() + ".shop";
        this.text2 = resourceLocation.getResourceDomain() + ".npc." + resourceLocation.getResourcePath() + ".shop.wednesday";
    }

    @Override
    public String getLocalizedText(EntityPlayer player, EntityAgeable ageable, NPC npc) {
        return TownHelper.getClosestTownToEntity(ageable, false).getQuests().getFinished().contains(Quests.OPEN_WEDNESDAYS) ? TextHelper.localize(text2) : TextHelper.localize(text);
    }

    @Override
    public void drawIcon(GuiScreen gui, int x, int y) {
        gui.mc.renderEngine.bindTexture(ICONS);
        gui.drawTexturedModalRect(x, y, 16, 0, 16, 16);
    }

    @SideOnly(Side.CLIENT)
    public String getTooltip() {
        return "harvestfestival.npc.tooltip.clock";
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<ldswebml type="image" uri="/media-library/images/conference-events/pageants#nauvoo-pageant-768135" xml:lang="eng" locale="eng" status="publish">
  <search-meta>
      <uri-title its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">nauvoo-pageant-768135</uri-title>
      <source>nauvoo-pageant-768135</source>
      <publication-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</publication-type>
      <media-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</media-type>
      <publication value="ldsorg">LDS.org</publication>
      <publication-date value="2012-04-09">2012-04-09</publication-date>
      <title/>
      <description/>
      <collections>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">global-search</collection>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">media</collection>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">images</collection>
      </collections>
      <subjects>
          <subject>Nauvoo</subject>
          <subject>Illinois</subject>
          <subject>Pageant</subject>
          <subject>Actors</subject>
          <subject>Dancing</subject>
          <subject>Costumes</subject>
          <subject>Performances</subject>
          <subject>Stage</subject>
      </subjects>
  </search-meta>
  <no-search>
      <path>http://media.ldscdn.org/images/media-library/conference-events/pageants/nauvoo-pageant-768135-gallery.jpg</path>
      <images>
          http://media.ldscdn.org/images/media-library/conference-events/pageants/nauvoo-pageant-768135-thumbnail.jpg
      </images>
          <download-urls>
              <download-url>
                  Mobile
                  <size>174 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/conference-events/pageants/nauvoo-pageant-768135-mobile.jpg</path>
              </download-url>
              <download-url>
                  Tablet
                  <size>237 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/conference-events/pageants/nauvoo-pageant-768135-tablet.jpg</path>
              </download-url>
              <download-url>
                  Print
                  <size>416 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/conference-events/pageants/nauvoo-pageant-768135-print.jpg</path>
              </download-url>
          </download-urls>
  </no-search>
<ldse-meta its:translate="no" xmlns="http://lds.org/code/lds-edit" xmlns:its="http://www.w3.org/2005/11/its"><document id="nauvoo-pageant-768135" locale="eng" uri="/media-library/images/conference-events/pageants#nauvoo-pageant-768135" status="publish" site="ldsorg" source="chq" words="109" tgp="0.3811"/><created username="lds-edit" userid=""/><last-modified date="2012-05-10T12:26:12.550235-06:00" username="lds-edit" userid=""/></ldse-meta></ldswebml>


text:
package edu.javacourse.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import java.util.List;

/**
 * Простой пример работы с программно загружаемой конфигурацией и мапингом в виде аннотаций
 *
 * @author ASaburov
 */
public class HibernateSimple {

    public static void main(String[] args) {
        HibernateSimple hs = new HibernateSimple();

        Session s = hs.getSessionFactory().getCurrentSession();
        s.beginTransaction();
        List<Region> regionList = s.createQuery("from Region").list();
        s.getTransaction().commit();

        for (Region r : regionList) {
            System.out.println("Region name:" + r.getRegionName());
        }
    }

    private SessionFactory getSessionFactory() {

        Configuration cfg = new Configuration()
                .addAnnotatedClass(edu.javacourse.hibernate.Region.class)
                .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect")
                .setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver")
                .setProperty("hibernate.connection.url", "jdbc:mysql://127.0.0.1:3306/java_backend")
                .setProperty("hibernate.connection.username", "root")
                .setProperty("hibernate.connection.password", "root")
                .setProperty("hibernate.connection.pool_size", "1")
                .setProperty("hibernate.show_sql", "true")
                .setProperty("hibernate.cache.provider_class", "org.hibernate.cache.NoCacheProvider")
                .setProperty("hibernate.current_session_context_class", "thread");
        return cfg.buildSessionFactory();
    }
}


text:
import { expect } from 'chai';
import { once } from 'events';
import * as sinon from 'sinon';

import {
  CommandFailedEvent,
  CommandStartedEvent,
  CommandSucceededEvent,
  MongoClient,
  MongoNotConnectedError,
  MongoServerSelectionError,
  ReadPreference
} from '../../../src';
import { Connection } from '../../../src/cmap/connection';
import { Db } from '../../../src/db';
import { ServerDescription } from '../../../src/sdam/server_description';
import { Topology } from '../../../src/sdam/topology';
import { getTopology, isHello } from '../../../src/utils';
import { runLater } from '../../tools/utils';
import { setupDatabase } from '../shared';

describe('class MongoClient', function () {
  before(function () {
    return setupDatabase(this.configuration);
  });

  it('should correctly pass through extra db options', {
    metadata: { requires: { topology: ['single'] } },
    test: function (done) {
      const configuration = this.configuration;
      const client = configuration.newClient(
        {},
        {
          writeConcern: { w: 1, wtimeoutMS: 1000, fsync: true, j: true },
          readPreference: 'nearest',
          readPreferenceTags: { loc: 'ny' },
          forceServerObjectId: true,
          pkFactory: {
            createPk() {
              return 1;
            }
          },
          serializeFunctions: true
        }
      );

      client.connect(function (err, client) {
        expect(err).to.be.undefined;

        const db = client.db(configuration.db);

        expect(db).to.have.property('writeConcern');
        expect(db.writeConcern).to.have.property('w', 1);
        expect(db.writeConcern).to.have.property('wtimeout', 1000);
        expect(db.writeConcern).to.have.property('fsync', true);
        expect(db.writeConcern).to.have.property('j', true);

        expect(db).to.have.property('s');
        expect(db.s).to.have.property('readPreference');
        expect(db.s.readPreference).to.have.property('mode', 'nearest');
        expect(db.s.readPreference)
          .to.have.property('tags')
          .that.deep.equals([{ loc: 'ny' }]);

        expect(db.s).to.have.nested.property('options.forceServerObjectId');
        expect(db.s.options).to.have.property('forceServerObjectId', true);
        expect(db.s).to.have.nested.property('pkFactory.createPk').that.is.a('function');
        expect(db.s.pkFactory.createPk()).to.equal(1);
        expect(db).to.have.nested.property('bsonOptions.serializeFunctions');

        client.close(done);
      });
    }
  });

  it('Should fail due to wrong uri user:password@localhost', {
    metadata: {
      requires: { topology: ['single', 'replicaset', 'sharded'] }
    },
    test() {
      expect(() => this.configuration.newClient('user:password@localhost:27017/test')).to.throw(
        'Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"'
      );
    }
  });

  it('correctly error out when no socket available on MongoClient `connect`', {
    metadata: {
      requires: { topology: ['single', 'replicaset', 'sharded'] }
    },

    test: function (done) {
      const configuration = this.configuration;
      const client = configuration.newClient('mongodb://localhost:27088/test', {
        serverSelectionTimeoutMS: 10
      });

      client.connect(function (err) {
        expect(err).to.exist;

        done();
      });
    }
  });

  it('should correctly connect to mongodb using domain socket', {
    metadata: { requires: { topology: ['single'], os: '!win32' } },

    test: function (done) {
      const configuration = this.configuration;
      const client = configuration.newClient('mongodb://%2Ftmp%2Fmongodb-27017.sock/test');
      client.connect(function (err) {
        expect(err).to.not.exist;
        client.close(done);
      });
    }
  });

  it('should fail to connect due to unknown host in connection string', async function () {
    const configuration = this.configuration;
    const client = configuration.newClient('mongodb://iLoveJavascript:36363/ddddd', {
      serverSelectionTimeoutMS: 10
    });

    const error = await client.connect().catch(error => error);
    expect(error).to.be.instanceOf(MongoServerSelectionError);
  });

  it('Should correctly pass through appname', {
    metadata: {
      requires: {
        topology: ['single', 'replicaset', 'sharded']
      }
    },

    test: function (done) {
      const configuration = this.configuration;
      const options = {
        appName: 'hello world'
      };
      const client = configuration.newClient(options);

      client.connect(function (err, client) {
        expect(err).to.not.exist;
        expect(client)
          .to.have.nested.property('topology.clientMetadata.application.name')
          .to.equal('hello world');

        client.close(done);
      });
    }
  });

  it('Should correctly pass through appname in options', {
    metadata: {
      requires: {
        topology: ['single', 'replicaset', 'sharded']
      }
    },

    test: function (done) {
      const configuration = this.configuration;
      const url = configuration.url();

      const client = configuration.newClient(url, { appname: 'hello world' });
      client.connect(err => {
        expect(err).to.not.exist;
        expect(client)
          .to.have.nested.property('topology.clientMetadata.application.name')
          .to.equal('hello world');

        client.close(done);
      });
    }
  });

  it('Should correctly pass through socketTimeoutMS and connectTimeoutMS', {
    metadata: {
      requires: {
        topology: ['single', 'replicaset', 'sharded']
      }
    },

    test: function (done) {
      const configuration = this.configuration;
      const client = configuration.newClient(
        {},
        {
          socketTimeoutMS: 0,
          connectTimeoutMS: 0
        }
      );

      client.connect(function (err, client) {
        expect(err).to.not.exist;
        const topology = getTopology(client.db(configuration.db));
        expect(topology).nested.property('s.options.connectTimeoutMS').to.equal(0);
        expect(topology).nested.property('s.options.socketTimeoutMS').to.equal(0);

        client.close(done);
      });
    }
  });

  it('should open a new MongoClient connection', {
    metadata: {
      requires: {
        topology: ['single']
      }
    },

    test: function (done) {
      const configuration = this.configuration;
      const client = configuration.newClient();
      client.connect(function (err, mongoclient) {
        expect(err).to.not.exist;

        mongoclient
          .db('integration_tests')
          .collection('new_mongo_client_collection')
          .insertOne({ a: 1 }, function (err, r) {
            expect(err).to.not.exist;
            expect(r).to.be.an('object');

            mongoclient.close(done);
          });
      });
    }
  });

  it('should correctly connect with MongoClient `connect` using Promise', function () {
    const configuration = this.configuration;
    let url = configuration.url();
    url = url.indexOf('?') !== -1 ? `${url}&maxPoolSize=100` : `${url}?maxPoolSize=100`;

    const client = configuration.newClient(url);
    return client.connect().then(() => client.close());
  });

  it('should open a new MongoClient connection using promise', {
    metadata: {
      requires: {
        topology: ['single']
      }
    },

    test: function (done) {
      const configuration = this.configuration;
      const client = configuration.newClient();
      client.connect().then(function (mongoclient) {
        mongoclient
          .db('integration_tests')
          .collection('new_mongo_client_collection')
          .insertOne({ a: 1 })
          .then(function (r) {
            expect(r).to.exist;

            mongoclient.close(done);
          });
      });
    }
  });

  it('should be able to access a database named "constructor"', function () {
    const client = this.configuration.newClient();
    let err;
    return client
      .connect()
      .then(() => {
        const db = client.db('constructor');
        expect(db).to.not.be.a('function');
        expect(db).to.be.an.instanceOf(Db);
      })
      .catch(_err => (err = _err))
      .then(() => client.close())
      .catch(() => {
        // ignore
      })
      .then(() => {
        if (err) {
          throw err;
        }
      });
  });

  it('should cache a resolved readPreference from options', function () {
    const client = this.configuration.newClient({}, { readPreference: ReadPreference.SECONDARY });
    expect(client.readPreference).to.be.instanceOf(ReadPreference);
    expect(client.readPreference).to.have.property('mode', ReadPreference.SECONDARY);
  });

  it('should error on unexpected options', {
    metadata: { requires: { topology: 'single' } },

    test: function (done) {
      const configuration = this.configuration;
      MongoClient.connect(
        configuration.url(),
        {
          maxPoolSize: 4,
          // @ts-expect-error: unexpected option test
          notlegal: {},
          validateOptions: true
        },
        function (err, client) {
          expect(err)
            .property('message')
            .to.match(/options notlegal, validateoptions are not supported/);
          expect(client).to.not.exist;
          done();
        }
      );
    }
  });

  it('should error on unexpected options (promise)', {
    metadata: { requires: { topology: 'single' } },

    test() {
      const options = {
        maxPoolSize: 4,
        notlegal: {},
        validateOptions: true
      };
      MongoClient.connect(this.configuration.url(), options)
        .then(() => expect.fail())
        .catch(err => {
          expect(err)
            .property('message')
            .to.match(/options notlegal, validateoptions are not supported/);
        });
    }
  });

  it('must respect an infinite connectTimeoutMS for the streaming protocol', {
    metadata: { requires: { topology: 'replicaset', mongodb: '>= 4.4' } },
    test: function (done) {
      const client = this.configuration.newClient({
        connectTimeoutMS: 0,
        heartbeatFrequencyMS: 500
      });
      client.connect(err => {
        expect(err).to.not.exist;
        const stub = sinon.stub(Connection.prototype, 'command').callsFake(function (...args) {
          const ns = args[0];
          const command = args[1];
          const options = args[2] || {};

          // @ts-expect-error: exhaustAllowed is a protocol option
          if (ns.toString() === 'admin.$cmd' && isHello(command) && options.exhaustAllowed) {
            expect(options).property('socketTimeoutMS').to.equal(0);
            stub.restore();
            client.close(done);
          }
          stub.wrappedMethod.apply(this, args);
        });
      });
    }
  });

  it('must respect a finite connectTimeoutMS for the streaming protocol', {
    metadata: { requires: { topology: 'replicaset', mongodb: '>= 4.4' } },
    test: function (done) {
      const client = this.configuration.newClient({
        connectTimeoutMS: 10,
        heartbeatFrequencyMS: 500
      });
      client.connect(err => {
        expect(err).to.not.exist;
        const stub = sinon.stub(Connection.prototype, 'command').callsFake(function (...args) {
          const ns = args[0];
          const command = args[1];
          const options = args[2] || {};

          // @ts-expect-error: exhaustAllowed is a protocol option
          if (ns.toString() === 'admin.$cmd' && isHello(command) && options.exhaustAllowed) {
            expect(options).property('socketTimeoutMS').to.equal(510);
            stub.restore();
            client.close(done);
          }
          stub.wrappedMethod.apply(this, args);
        });
      });
    }
  });

  context('explict #connect()', () => {
    let client: MongoClient;
    beforeEach(function () {
      client = this.configuration.newClient(this.configuration.url(), {
        monitorCommands: true
      });
    });

    afterEach(async function () {
      await client.close();
    });

    it(
      'creates topology and send ping when auth is enabled',
      { requires: { auth: 'enabled' } },
      async function () {
        const commandToBeStarted = once(client, 'commandStarted');
        await client.connect();
        const [pingOnConnect] = await commandToBeStarted;
        expect(pingOnConnect).to.have.property('commandName', 'ping');
        expect(client).to.have.property('topology').that.is.instanceOf(Topology);
      }
    );

    it(
      'does not send ping when authentication is disabled',
      { requires: { auth: 'disabled' } },
      async function () {
        const commandToBeStarted = once(client, 'commandStarted');
        await client.connect();
        const delayedFind = runLater(async () => {
          await client.db().collection('test').findOne();
        }, 300);
        const [findOneOperation] = await commandToBeStarted;
        // Proves that the first command started event that is emitted is a find and not a ping
        expect(findOneOperation).to.have.property('commandName', 'find');
        await delayedFind;
        expect(client).to.have.property('topology').that.is.instanceOf(Topology);
      }
    );

    it(
      'permits operations to be run after connect is called',
      { requires: { auth: 'enabled' } },
      async function () {
        const pingCommandToBeStarted = once(client, 'commandStarted');
        await client.connect();
        const [pingOnConnect] = await pingCommandToBeStarted;

        const findCommandToBeStarted = once(client, 'commandStarted');
        await client.db('test').collection('test').findOne();
        const [findCommandStarted] = await findCommandToBeStarted;

        expect(pingOnConnect).to.have.property('commandName', 'ping');
        expect(findCommandStarted).to.have.property('commandName', 'find');
        expect(client).to.have.property('topology').that.is.instanceOf(Topology);
      }
    );
  });

  context('implicit #connect()', () => {
    let client: MongoClient;
    beforeEach(function () {
      client = this.configuration.newClient(this.configuration.url(), {
        monitorCommands: true
      });
    });

    afterEach(async function () {
      await client.close();
    });

    it(
      'automatically connects upon first operation (find)',
      { requires: { auth: 'enabled' } },
      async function () {
        const findCommandToBeStarted = once(client, 'commandStarted');
        await client.db().collection('test').findOne();
        const [findCommandStarted] = await findCommandToBeStarted;

        expect(findCommandStarted).to.have.property('commandName', 'find');
        expect(client.options).to.not.have.property(Symbol.for('@@mdb.skipPingOnConnect'));
        expect(client.s.options).to.not.have.property(Symbol.for('@@mdb.skipPingOnConnect'));

        // Assertion is redundant but it shows that no initial ping is run
        expect(findCommandStarted.commandName).to.not.equal('ping');

        expect(client).to.have.property('topology').that.is.instanceOf(Topology);
      }
    );

    it(
      'automatically connects upon first operation (insertOne)',
      { requires: { auth: 'enabled' } },
      async function () {
        const insertOneCommandToBeStarted = once(client, 'commandStarted');
        await client.db().collection('test').insertOne({ a: 1 });
        const [insertCommandStarted] = await insertOneCommandToBeStarted;

        expect(insertCommandStarted).to.have.property('commandName', 'insert');
        expect(client.options).to.not.have.property(Symbol.for('@@mdb.skipPingOnConnect'));
        expect(client.s.options).to.not.have.property(Symbol.for('@@mdb.skipPingOnConnect'));

        // Assertion is redundant but it shows that no initial ping is run
        expect(insertCommandStarted.commandName).to.not.equal('ping');

        expect(client).to.have.property('topology').that.is.instanceOf(Topology);
      }
    );

    it(
      'passes connection errors to the user through the first operation',
      { requires: { auth: 'enabled' } },
      async function () {
        const client = this.configuration.newClient(
          'mongodb://iLoveJavascript?serverSelectionTimeoutMS=100',
          { monitorCommands: true }
        );

        const result = await client
          .db('test')
          .collection('test')
          .findOne()
          .catch(error => error);

        expect(result).to.be.instanceOf(MongoServerSelectionError);
        expect(client).to.be.instanceOf(MongoClient);
        expect(client).to.have.property('topology').that.is.instanceOf(Topology);
      }
    );
  });

  context('#close()', () => {
    let client: MongoClient;
    let db: Db;

    const RD_ONLY_HAS_BEEN_CLOSED = {
      value: true,
      enumerable: true,
      configurable: false,
      writable: false
    };

    const INIT_HAS_BEEN_CLOSED = {
      value: false,
      enumerable: true,
      configurable: true,
      writable: true
    };

    beforeEach(function () {
      client = this.configuration.newClient({ monitorCommands: true });
      db = client.db();
    });

    afterEach(async function () {
      await client.close();
      db = null;
    });

    it('prevents automatic connection on a closed non-connected client', async () => {
      expect(client.s).to.have.ownPropertyDescriptor('hasBeenClosed', INIT_HAS_BEEN_CLOSED);
      await client.close();
      expect(client.s).to.have.ownPropertyDescriptor('hasBeenClosed', RD_ONLY_HAS_BEEN_CLOSED);
      const error = await db.command({ ping: 1 }).catch(error => error);
      expect(error).to.be.instanceOf(MongoNotConnectedError);
    });

    it('allows explicit connection on a closed non-connected client', async () => {
      expect(client.s).to.have.ownPropertyDescriptor('hasBeenClosed', INIT_HAS_BEEN_CLOSED);
      await client.close();
      expect(client.s).to.have.ownPropertyDescriptor('hasBeenClosed', RD_ONLY_HAS_BEEN_CLOSED);
      await client.connect();
      const result = await db.command({ ping: 1 }).catch(error => error);
      expect(result).to.not.be.instanceOf(MongoNotConnectedError);
      expect(result).to.have.property('ok', 1);
    });

    it('prevents automatic reconnect on a closed previously explicitly connected client', async () => {
      await client.connect();
      expect(client.s).to.have.ownPropertyDescriptor('hasBeenClosed', INIT_HAS_BEEN_CLOSED);
      await client.close();
      expect(client.s).to.have.ownPropertyDescriptor('hasBeenClosed', RD_ONLY_HAS_BEEN_CLOSED);
      const error = await db.command({ ping: 1 }).catch(error => error);
      expect(error).to.be.instanceOf(MongoNotConnectedError);
    });

    it('allows explicit reconnect on a closed previously explicitly connected client', async () => {
      await client.connect();
      expect(client.s).to.have.ownPropertyDescriptor('hasBeenClosed', INIT_HAS_BEEN_CLOSED);
      await client.close();
      expect(client.s).to.have.ownPropertyDescriptor('hasBeenClosed', RD_ONLY_HAS_BEEN_CLOSED);
      await client.connect();
      const result = await db.command({ ping: 1 }).catch(error => error);
      expect(result).to.not.be.instanceOf(MongoNotConnectedError);
      expect(result).to.have.property('ok', 1);
    });

    it('prevents auto reconnect on closed previously implicitly connected client', async () => {
      expect(client.s).to.have.ownPropertyDescriptor('hasBeenClosed', INIT_HAS_BEEN_CLOSED);
      const result = await db.command({ ping: 1 }).catch(error => error); // auto connect
      expect(result).to.not.be.instanceOf(MongoNotConnectedError);
      expect(result).to.have.property('ok', 1);
      await client.close();
      expect(client.s).to.have.ownPropertyDescriptor('hasBeenClosed', RD_ONLY_HAS_BEEN_CLOSED);
      const error = await db.command({ ping: 1 }).catch(error => error);
      expect(error).to.be.instanceOf(MongoNotConnectedError);
    });

    it('allows explicit reconnect on closed previously implicitly connected client', async () => {
      expect(client.s).to.have.ownPropertyDescriptor('hasBeenClosed', INIT_HAS_BEEN_CLOSED);
      const result = await db.command({ ping: 1 }).catch(error => error); // auto connect
      expect(result).to.not.be.instanceOf(MongoNotConnectedError);
      expect(result).to.have.property('ok', 1);
      await client.close();
      await client.connect();
      expect(client.s).to.have.ownPropertyDescriptor('hasBeenClosed', RD_ONLY_HAS_BEEN_CLOSED);
      const result2 = await db.command({ ping: 1 }).catch(error => error);
      expect(result2).to.not.be.instanceOf(MongoNotConnectedError);
      expect(result2).to.have.property('ok', 1);
    });

    it('prevents auto reconnect on closed explicitly connected client after an operation', async () => {
      expect(client.s).to.have.ownPropertyDescriptor('hasBeenClosed', INIT_HAS_BEEN_CLOSED);
      await client.connect();
      const result = await db.command({ ping: 1 }).catch(error => error);
      expect(result).to.not.be.instanceOf(MongoNotConnectedError);
      expect(result).to.have.property('ok', 1);
      await client.close();
      expect(client.s).to.have.ownPropertyDescriptor('hasBeenClosed', RD_ONLY_HAS_BEEN_CLOSED);
      const error = await db.command({ ping: 1 }).catch(error => error);
      expect(error).to.be.instanceOf(MongoNotConnectedError);
    });

    it('allows explicit reconnect on closed explicitly connected client after an operation', async () => {
      expect(client.s).to.have.ownPropertyDescriptor('hasBeenClosed', INIT_HAS_BEEN_CLOSED);
      await client.connect();
      const result = await db.command({ ping: 1 }).catch(error => error);
      expect(result).to.not.be.instanceOf(MongoNotConnectedError);
      expect(result).to.have.property('ok', 1);
      await client.close();
      await client.connect();
      expect(client.s).to.have.ownPropertyDescriptor('hasBeenClosed', RD_ONLY_HAS_BEEN_CLOSED);
      const result2 = await db.command({ ping: 1 }).catch(error => error);
      expect(result2).to.not.be.instanceOf(MongoNotConnectedError);
      expect(result2).to.have.property('ok', 1);
    });

    it('sends endSessions with noResponse set', async () => {
      const session = client.startSession(); // make a session to be ended
      await client.db('test').command({ ping: 1 }, { session });
      await session.endSession();

      const startedEvents: CommandStartedEvent[] = [];
      const endEvents: Array<CommandFailedEvent | CommandSucceededEvent> = [];
      client.on('commandStarted', event => startedEvents.push(event));
      client.on('commandSucceeded', event => endEvents.push(event));
      client.on('commandFailed', event => endEvents.push(event));

      await client.close();

      expect(startedEvents).to.have.lengthOf(1);
      expect(startedEvents[0]).to.have.property('commandName', 'endSessions');
      expect(endEvents).to.have.lengthOf(1);
      expect(endEvents[0]).to.have.property('reply', undefined); // noReponse: true
    });

    context('when server selection would return no servers', () => {
      const serverDescription = new ServerDescription('a:1');

      it('short circuits and does not end sessions', async () => {
        const session = client.startSession(); // make a session to be ended
        await client.db('test').command({ ping: 1 }, { session });
        await session.endSession();

        const startedEvents: CommandStartedEvent[] = [];
        client.on('commandStarted', event => startedEvents.push(event));

        const servers = new Map<string, ServerDescription>();
        servers.set(serverDescription.address, serverDescription);
        client.topology.description.servers = servers;
        await client.close();

        expect(startedEvents).to.be.empty;
        expect(client.s.sessionPool.sessions).to.have.lengthOf(1);
      });
    });
  });
});


text:
"""
discord.ext.commands
~~~~~~~~~~~~~~~~~~~~~

An extension module to facilitate creation of bot commands.

:copyright: (c) 2015-present Rapptz
:license: MIT, see LICENSE for more details.
"""

from .bot import *
from .cog import *
from .context import *
from .converter import *
from .cooldowns import *
from .core import *
from .errors import *
from .flags import *
from .help import *
from .parameters import *
from .hybrid import *


text:
package org.javarosa.core.model.utils.test;

import org.javarosa.core.services.locale.Localizer;
import org.javarosa.core.services.locale.TableLocaleSource;
import org.javarosa.core.util.UnregisteredLocaleException;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import org.javarosa.core.util.test.ExternalizableTest;
import org.junit.Test;

import java.util.Hashtable;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

public class LocalizerTest {
    private void testSerialize(Localizer l, String msg) {
        PrototypeFactory pf = new PrototypeFactory();
        pf.addClass(TableLocaleSource.class);
        ExternalizableTest.testExternalizable(l, pf, "Localizer [" + msg + "]");
    }

    @Test
    public void testEmpty() {
        Localizer l = new Localizer();

        String[] locales = l.getAvailableLocales();
        if (locales == null || locales.length > 0) {
            fail("New localizer not empty");
        }
        String currentLocale = l.getLocale();
        if (currentLocale != null) {
            fail("New localizer has locale set");
        }
        String defaultLocale = l.getDefaultLocale();
        if (defaultLocale != null) {
            fail("New localizer has default locale set");
        }
    }

    @Test
    public void testAddLocale() {
        Localizer l = new Localizer();
        final String TEST_LOCALE = "test";

        if (l.hasLocale(TEST_LOCALE)) {
            fail("Localizer reports it contains non-existent locale");
        }
        boolean result = l.addAvailableLocale(TEST_LOCALE);
        if (!result) {
            fail("Localizer failed to add new locale");
        }
        if (!l.hasLocale(TEST_LOCALE)) {
            fail("Localizer reports it does not contain newly added locale");
        }
        Hashtable<String, String> localeData = l.getLocaleData(TEST_LOCALE);
        if (localeData == null || localeData.size() != 0) {
            fail("Newly created locale not empty (or undefined)");
        }
    }

    @Test
    public void testAddLocaleWithData() {
        Localizer l = new Localizer();
        final String TEST_LOCALE = "test";
        TableLocaleSource localeData = new TableLocaleSource();
        localeData.setLocaleMapping("textID", "text");

        if (l.hasLocale(TEST_LOCALE)) {
            fail("Localizer reports it contains non-existent locale");
        }

        l.addAvailableLocale(TEST_LOCALE);
        l.registerLocaleResource(TEST_LOCALE, localeData);

        if (!l.hasLocale(TEST_LOCALE)) {
            fail("Localizer reports it does not contain newly added locale");
        }
        if (!localeData.getLocalizedText().equals(l.getLocaleData(TEST_LOCALE))) {
            fail("Newly stored locale does not match source");
        }
    }

    @Test
    public void testAddExistingLocale() {
        Localizer l = new Localizer();
        final String TEST_LOCALE = "test";

        l.addAvailableLocale(TEST_LOCALE);
        TableLocaleSource table = new TableLocaleSource();
        table.setLocaleMapping("textID", "text");
        l.registerLocaleResource(TEST_LOCALE, table);

        Hashtable<String, String> localeData = l.getLocaleData(TEST_LOCALE);

        boolean result = l.addAvailableLocale(TEST_LOCALE);
        if (result) {
            fail("Localizer overwrote existing locale");
        }

        Hashtable newLocaleData = l.getLocaleData(TEST_LOCALE);
        if (!localeData.equals(newLocaleData)) {
            fail("Localizer overwrote existing locale");
        }
    }

    @Test
    public void testSetCurrentLocaleExists() {
        Localizer l = new Localizer();
        final String TEST_LOCALE = "test";
        l.addAvailableLocale(TEST_LOCALE);

        l.setLocale(TEST_LOCALE);
        if (!TEST_LOCALE.equals(l.getLocale())) {
            fail("Did not properly set current locale");
        }
    }

    @Test
    public void testSetCurrentLocaleNotExists() {
        Localizer l = new Localizer();
        final String TEST_LOCALE = "test";

        try {
            l.setLocale(TEST_LOCALE);

            fail("Set current locale to a non-existent locale");
        } catch (UnregisteredLocaleException nsee) {
            //expected
        }
    }

    @Test
    public void testUnsetCurrentLocale() {
        Localizer l = new Localizer();
        final String TEST_LOCALE = "test";
        l.addAvailableLocale(TEST_LOCALE);
        l.setLocale(TEST_LOCALE);

        try {
            l.setLocale(null);

            fail("Able to unset current locale");
        } catch (UnregisteredLocaleException nsee) {
            //expected
        }
    }

    @Test
    public void testSetDefaultLocaleExists() {
        Localizer l = new Localizer();
        final String TEST_LOCALE = "test";
        l.addAvailableLocale(TEST_LOCALE);

        l.setDefaultLocale(TEST_LOCALE);
        if (!TEST_LOCALE.equals(l.getDefaultLocale())) {
            fail("Did not properly set default locale");
        }
    }

    @Test
    public void testSetDefaultLocaleNotExists() {
        Localizer l = new Localizer();
        final String TEST_LOCALE = "test";

        try {
            l.setDefaultLocale(TEST_LOCALE);

            fail("Set current locale to a non-existent locale");
        } catch (UnregisteredLocaleException nsee) {
            //expected
        }
    }

    @Test
    public void testUnsetDefaultLocale() {
        Localizer l = new Localizer();
        final String TEST_LOCALE = "test";
        l.addAvailableLocale(TEST_LOCALE);
        l.setDefaultLocale(TEST_LOCALE);

        try {
            l.setDefaultLocale(null);

            if (l.getDefaultLocale() != null) {
                fail("Could not unset default locale");
            }
        } catch (UnregisteredLocaleException nsee) {
            fail("Exception unsetting default locale");
        }
    }

    @Test
    public void testSetToDefault() {
        Localizer l = new Localizer();
        final String TEST_LOCALE = "test";
        l.addAvailableLocale(TEST_LOCALE);
        l.setDefaultLocale(TEST_LOCALE);

        l.setToDefault();
        if (!TEST_LOCALE.equals(l.getLocale())) {
            fail("Could not set current locale to default");
        }
    }

    @Test
    public void testSetToDefaultNoDefault() {
        Localizer l = new Localizer();
        final String TEST_LOCALE = "test";
        l.addAvailableLocale(TEST_LOCALE);

        try {
            l.setToDefault();

            fail("Set current locale to default when no default set");
        } catch (IllegalStateException ise) {
            //expected
        }
    }

    @Test
    public void testAvailableLocales() {
        Localizer l = new Localizer();
        String[] locales;

        l.addAvailableLocale("test1");
        locales = l.getAvailableLocales();
        if (locales.length != 1 || !locales[0].equals("test1")) {
            fail("Available locales not as expected");
        }

        l.addAvailableLocale("test2");
        locales = l.getAvailableLocales();
        if (locales.length != 2 || !locales[0].equals("test1") || !locales[1].equals("test2")) {
            fail("Available locales not as expected");
        }

        l.addAvailableLocale("test3");
        locales = l.getAvailableLocales();
        if (locales.length != 3 || !locales[0].equals("test1") || !locales[1].equals("test2") || !locales[2].equals("test3")) {
            fail("Available locales not as expected");
        }
    }

    @Test
    public void testGetLocaleMap() {
        Localizer l = new Localizer();
        final String TEST_LOCALE = "test";
        l.addAvailableLocale(TEST_LOCALE);

        if (!l.getLocaleMap(TEST_LOCALE).equals(l.getLocaleData(TEST_LOCALE))) {
            fail();
        }
    }

    @Test
    public void testGetLocaleMapNotExist() {
        Localizer l = new Localizer();
        final String TEST_LOCALE = "test";

        try {
            l.getLocaleMap(TEST_LOCALE);

            fail("Did not throw exception when getting locale mapping for non-existent locale");
        } catch (UnregisteredLocaleException nsee) {
            //expected
        }
    }

    @Test
    public void testTextMapping() {
        Localizer l = new Localizer();
        final String TEST_LOCALE = "test";
        l.addAvailableLocale(TEST_LOCALE);

        if (l.hasMapping(TEST_LOCALE, "textID")) {
            fail("Localizer contains text mapping that was not defined");
        }
        TableLocaleSource table = new TableLocaleSource();
        table.setLocaleMapping("textID", "text");
        l.registerLocaleResource(TEST_LOCALE, table);

        if (!l.hasMapping(TEST_LOCALE, "textID")) {
            fail("Localizer does not contain newly added text mapping");
        }
        if (!"text".equals(l.getLocaleData(TEST_LOCALE).get("textID"))) {
            fail("Newly added text mapping does not match source");
        }
    }

    @Test
    public void testTextMappingOverwrite() {
        Localizer l = new Localizer();
        final String TEST_LOCALE = "test";

        l.addAvailableLocale(TEST_LOCALE);
        TableLocaleSource table = new TableLocaleSource();

        table.setLocaleMapping("textID", "oldText");

        table.setLocaleMapping("textID", "newText");

        l.registerLocaleResource(TEST_LOCALE, table);

        if (!l.hasMapping(TEST_LOCALE, "textID")) {
            fail("Localizer does not contain overwritten text mapping");
        }
        if (!"newText".equals(l.getLocaleData(TEST_LOCALE).get("textID"))) {
            fail("Newly overwritten text mapping does not match source");
        }
    }

    @Test
    public void testGetText() {
        for (int localeCase = 1; localeCase <= 3; localeCase++) {
            for (int formCase = 1; formCase <= 2; formCase++) {
                testGetText(localeCase, formCase);
            }
        }
    }

    private static final int DEFAULT_LOCALE = 1;
    private static final int NON_DEFAULT_LOCALE = 2;
    private static final int NEUTRAL_LOCALE = 3;

    //private static final int BASE_FORM = 1;
    private static final int CUSTOM_FORM = 2;

    public void testGetText(int localeCase, int formCase) {
        String ourLocale = null;
        String otherLocale = null;

        switch (localeCase) {
            case DEFAULT_LOCALE:
                ourLocale = "default";
                otherLocale = null;
                break;
            case NON_DEFAULT_LOCALE:
                ourLocale = "other";
                otherLocale = "default";
                break;
            case NEUTRAL_LOCALE:
                ourLocale = "neutral";
                otherLocale = null;
                break;
        }

        String textID = "textID" + (formCase == CUSTOM_FORM ? ";form" : "");

        for (int i = 0; i < 4; i++) { //iterate through 4 possible fallback modes
            for (int j = 0; j < 4; j++) {
                if (otherLocale == null) {
                    testGetText(i, j, -1, ourLocale, otherLocale, textID, localeCase, formCase);
                } else {
                    for (int k = 0; k < 4; k++) {
                        testGetText(i, j, k, ourLocale, otherLocale, textID, localeCase, formCase);
                    }
                }
            }
        }
    }

    public void testGetText(int i, int j, int k, String ourLocale, String otherLocale, String textID, int localeCase, int formCase) {
        //System.out.println("testing getText: "+localeCase+","+formCase+","+i+","+j+","+k);

        Localizer l = buildLocalizer(i, j, k, ourLocale, otherLocale);
        String expected = expectedText(textID, l);
        String text, text2;

        text = l.getText(textID, ourLocale);
        if (expected == null ? text != null : !expected.equals(text)) {
            fail("Did not retrieve expected text from localizer [" + localeCase + "," + formCase + "," + i + "," + j + "," + k + "]");
        }

        text2 = l.getText(textID);

        if (expected == null && text2 != null) {
            fail("Localization shouldn't have returned a result");
        } else if (expected != null && !expected.equals(text2)) {
            fail("Did not retrieve expected text");
        }
    }

    private Localizer buildLocalizer(int i, int j, int k, String ourLocale, String otherLocale) {
        Localizer l = new Localizer(i / 2 == 0, i % 2 == 0);

        TableLocaleSource firstLocale = new TableLocaleSource();
        TableLocaleSource secondLocale = new TableLocaleSource();

        if (j / 2 == 0 || "default".equals(ourLocale))
            firstLocale.setLocaleMapping("textID", "text:" + ourLocale + ":base");
        if (j % 2 == 0 || "default".equals(ourLocale))
            firstLocale.setLocaleMapping("textID;form", "text:" + ourLocale + ":form");

        if (otherLocale != null) {
            if (k / 2 == 0 || "default".equals(otherLocale))
                secondLocale.setLocaleMapping("textID", "text:" + otherLocale + ":base");
            if (k % 2 == 0 || "default".equals(otherLocale))
                secondLocale.setLocaleMapping("textID;form", "text:" + otherLocale + ":form");
        }

        l.addAvailableLocale(ourLocale);
        l.registerLocaleResource(ourLocale, firstLocale);

        if (otherLocale != null) {
            l.addAvailableLocale(otherLocale);
            l.registerLocaleResource(otherLocale, secondLocale);
        }
        if (l.hasLocale("default")) {
            l.setDefaultLocale("default");
        }

        l.setLocale(ourLocale);

        return l;
    }

    private String expectedText(String textID, Localizer l) {
        boolean[] searchOrder = new boolean[4];
        boolean fallbackLocale = l.getFallbackLocale();
        boolean fallbackForm = l.getFallbackForm();
        boolean hasForm = (textID.contains(";"));
        boolean hasDefault = (l.getDefaultLocale() != null && !l.getDefaultLocale().equals(l.getLocale()));
        String baseTextID = (hasForm ? textID.substring(0, textID.indexOf(";")) : textID);

        searchOrder[0] = hasForm;
        searchOrder[1] = !hasForm || fallbackForm;
        searchOrder[2] = hasForm && (hasDefault && fallbackLocale);
        searchOrder[3] = (!hasForm || fallbackForm) && (hasDefault && fallbackLocale);

        String text = null;
        for (int i = 0; text == null && i < 4; i++) {
            if (!searchOrder[i])
                continue;

            switch (i + 1) {
                case 1:
                    text = l.getRawText(l.getLocale(), textID);
                    break;
                case 2:
                    text = l.getRawText(l.getLocale(), baseTextID);
                    break;
                case 3:
                    text = l.getRawText(l.getDefaultLocale(), textID);
                    break;
                case 4:
                    text = l.getRawText(l.getDefaultLocale(), baseTextID);
                    break;
            }
        }

        return text;
    }

    @Test
    public void testGetTextNoCurrentLocale() {
        Localizer l = new Localizer();
        TableLocaleSource table = new TableLocaleSource();
        l.addAvailableLocale("test");
        l.setDefaultLocale("test");

        table.setLocaleMapping("textID", "text");
        l.registerLocaleResource("test", table);

        try {
            l.getText("textID");

            fail("Retrieved current locale text when current locale not set");
        } catch (UnregisteredLocaleException nsee) {
            //expected
        }
    }

    @Test
    public void testNullArgs() {
        Localizer l = new Localizer();
        l.addAvailableLocale("test");

        TableLocaleSource table = new TableLocaleSource();

        try {
            l.addAvailableLocale(null);

            fail("addAvailableLocale: Did not get expected null pointer exception");
        } catch (NullPointerException npe) {
            //expected
        }

        if (l.hasLocale(null)) {
            fail("Localizer reports it contains null locale");
        }

        try {
            l.registerLocaleResource(null, new TableLocaleSource());

            fail("setLocaleData: Did not get expected null pointer exception");
        } catch (NullPointerException npe) {
            //expected
        }

        try {
            l.registerLocaleResource("test", null);

            fail("setLocaleData: Did not get expected null pointer exception");
        } catch (NullPointerException npe) {
            //expected
        }

        if (l.getLocaleData(null) != null) {
            fail("getLocaleData: Localizer returns mappings for null locale");
        }

        try {
            l.getLocaleMap(null);

            fail("getLocaleMap: Did not get expected exception");
        } catch (UnregisteredLocaleException nsee) {
            //expected
        }

        try {
            table.setLocaleMapping(null, "text");

            fail("setLocaleMapping: Did not get expected null pointer exception");
        } catch (NullPointerException npe) {
            //expected
        }

        try {
            table.setLocaleMapping(null, null);

            fail("setLocaleMapping: Did not get expected null pointer exception");
        } catch (NullPointerException npe) {
            //expected
        }

        try {
            l.hasMapping(null, "textID");

            fail("hasMapping: Did not get expected exception");
        } catch (UnregisteredLocaleException nsee) {
            //expected
        }

        if (l.hasMapping("test", null)) {
            fail("Localization reports it contains null mapping");
        }

        try {
            l.getText("textID", (String)null);

            fail("getText: Did not get expected exception");
        } catch (UnregisteredLocaleException nsee) {
            //expected
        }

        try {
            l.getText(null, "test");

            fail("getText: Did not get expected null pointer exception");
        } catch (NullPointerException npe) {
            //expected
        }
    }

    @Test
    public void testSerialization() {
        Localizer l = new Localizer(true, true);
        TableLocaleSource firstLocale = new TableLocaleSource();
        TableLocaleSource secondLocale = new TableLocaleSource();
        TableLocaleSource finalLocale = new TableLocaleSource();

        testSerialize(l, "empty 1");
        testSerialize(new Localizer(false, false), "empty 2");
        testSerialize(new Localizer(true, false), "empty 3");
        testSerialize(new Localizer(false, true), "empty 4");

        l.addAvailableLocale("locale1");
        testSerialize(l, "one empty locale");

        l.addAvailableLocale("locale2");
        testSerialize(l, "two empty locales");

        l.setDefaultLocale("locale2");
        testSerialize(l, "two empty locales + default");

        l.setToDefault();
        testSerialize(l, "two empty locales + default/current");

        l.setLocale("locale1");
        testSerialize(l, "two empty locales + default/current 2");

        l.setDefaultLocale(null);
        testSerialize(l, "two empty locales + current");

        l.registerLocaleResource("locale1", firstLocale);
        l.registerLocaleResource("locale2", secondLocale);
        firstLocale.setLocaleMapping("id1", "text1");
        testSerialize(l, "locales with data 1");
        firstLocale.setLocaleMapping("id2", "text2");
        testSerialize(l, "locales with data 2");

        secondLocale.setLocaleMapping("id1", "text1");
        secondLocale.setLocaleMapping("id2", "text2");
        secondLocale.setLocaleMapping("id3", "text3");
        testSerialize(l, "locales with data 3");

        secondLocale.setLocaleMapping("id2", null);
        testSerialize(l, "locales with data 4");

        finalLocale.setLocaleMapping("id1", "text1");
        finalLocale.setLocaleMapping("id4", "text4");
        l.registerLocaleResource("locale3", finalLocale);
        testSerialize(l, "locales with data 5");

        testSerialize(l, "locales with data 6");
    }

    @Test
    public void testLinearSub() {
        final String F = "first";
        final String S = "second";

        final String C = "${0}";

        final String D = "${1}${0}";

        final String[] res = new String[]{"One", "Two"};

        assertEquals(Localizer.processArguments("${0}", new String[]{F}), F);
        assertEquals(Localizer.processArguments("${0},${1}", new String[]{F, S}), F + "," + S);
        assertEquals(Localizer.processArguments("testing ${0}", new String[]{F}), "testing " + F);

        assertEquals(Localizer.processArguments("1${arbitrary}2", new String[]{F}), "1" + F + "2");

        final String[] holder = new String[1];

        runAsync(() -> holder[0] = Localizer.processArguments("${0}", new String[]{C}), "Argument processing: " + C);

        assertEquals(holder[0], C);

        runAsync(() -> holder[0] = Localizer.processArguments("${0}", new String[]{D}), "Argument processing: " + D);

        assertEquals(holder[0], D);

        runAsync(() -> holder[0] = Localizer.processArguments(holder[0], res), "Argument processing: " + res[1] + res[0]);

        assertEquals(holder[0], res[1] + res[0]);

        runAsync(() -> holder[0] = Localizer.processArguments("$ {0} ${1}", res), "Argument processing: " + "$ {0} " + res[1]);

        assertEquals(holder[0], "$ {0} " + res[1]);

    }

    private void runAsync(Runnable test, String label) {
        Thread t = new Thread(test);
        t.start();
        int attempts = 4;

        for(int i = 0 ; i < attempts ; ++i) {
            try {
                t.join(500);
                break;
            } catch (InterruptedException e) {

            }
        }
        if (t.isAlive()) {
            t.stop();
            throw new RuntimeException("Failed to return from recursive argument processing: "+  label);
        }
    }

    @Test
    public void testHashSub() {
        final String F = "first";
        final String S = "second";
        Hashtable h = new Hashtable();
        h.put("fir", F);
        h.put("also first", F);
        h.put("sec", S);

        assertEquals(Localizer.processArguments("${fir}", h), F);
        assertEquals(Localizer.processArguments("${fir},${sec}", h), F + "," + S);
        assertEquals(Localizer.processArguments("${sec},${fir}", h), S + "," + F);
        assertEquals(Localizer.processArguments("${empty}", h), "${empty}");
        assertEquals(Localizer.processArguments("${fir},${fir},${also first}", h), F + "," + F + "," + F);
    }

    @Test
    public void testFallbacks() {
        Localizer localizer = new Localizer(true, true);

        localizer.addAvailableLocale("one");
        localizer.addAvailableLocale("two");

        TableLocaleSource firstLocale = new TableLocaleSource();
        firstLocale.setLocaleMapping("data", "val");
        firstLocale.setLocaleMapping("data2", "vald2");
        localizer.registerLocaleResource("one", firstLocale);

        TableLocaleSource secondLocale = new TableLocaleSource();
        firstLocale.setLocaleMapping("data", "val2");
        localizer.registerLocaleResource("two", secondLocale);
        localizer.setDefaultLocale("one");

        localizer.setLocale("two");

        String text = localizer.getText("data2");
        assertEquals("fallback", text, "vald2");
        String shouldBeNull = localizer.getText("noexist");
        assertNull("Localizer didn't return null value", shouldBeNull);

        localizer.setToDefault();

        shouldBeNull = localizer.getText("noexist");
        assertNull("Localizer didn't return null value", shouldBeNull);
        assertNull("Localizer didn't return null value", shouldBeNull);
    }
}


text:
import { makeIconComponent } from './utils/icon-wrapper'
import { Moon } from '@clair/icons'
export const IconMoon = /*@__PURE__*/ makeIconComponent({
  name: 'CIconMoon',
  template: Moon
})


text:
package org.inaturalist.android;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

//import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class INaturalistMapActivity extends com.google.android.maps.MapActivity {
    public final static String TAG = "INaturalistMapActivity";
    private MapView mMapView;
    private List<Overlay> mOverlays;
    private ObservationItemizedOverlay mObservationsOverlay;
    private PositionItemizedOverlay mPositionOverlay;
    private LocationManager mLocationManager;
    private LocationListener mLocationListener;
    private boolean mLocationEnabled = false;
    private Location mCurrentLocation;
    private NearbyObservationsReceiver mNearbyReceiver;
    private ActivityHelper mHelper;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map);
        mMapView = (MapView) findViewById(R.id.mapview);
        mMapView.setBuiltInZoomControls(true);
        mOverlays = mMapView.getOverlays();

        // this might need to happen in reloadObservations
        mObservationsOverlay = new ObservationItemizedOverlay(
                this.getResources().getDrawable(R.drawable.mm_34_dodger_blue),
                this);
        mOverlays.add(mObservationsOverlay);
        mPositionOverlay = new PositionItemizedOverlay(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        mHelper = new ActivityHelper(this);
        reloadObservations();
        startLocation();
    }

    @Override
    public void onPause() {
        super.onPause();
        stopLocation();
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem layersItem = menu.findItem(R.id.layers);
        if (mMapView.isSatellite()) {
            layersItem.setTitle("Street");
        } else {
            layersItem.setTitle("Satellite");
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.map_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.add:
            // Launch activity to insert a new item
            startActivity(new Intent(Intent.ACTION_INSERT, Observation.CONTENT_URI, this, ObservationEditor.class));
            return true;
        case R.id.layers:
            if (mMapView.isSatellite()) {
                mMapView.setSatellite(false);
                item.setTitle("Satellite");
            } else {
                mMapView.setSatellite(true);
                item.setTitle("Street");
            }
            return true;
        case R.id.location:
            zoomToLocation(mCurrentLocation);
            return true;
        case R.id.menu:
            startActivity(new Intent(this, MenuActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP));
            finish();
            return true;
        case R.id.nearby:
            reloadNearbyObservations();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    private void reloadObservations() {
        Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION,
                null, // selection
                null, // selectionArgs
                Observation.DEFAULT_SORT_ORDER);
        c.moveToFirst();
        while (c.isAfterLast() == false) {
            mObservationsOverlay.addObservation(new Observation(c));
            c.moveToNext();
        }
    }

    private void reloadNearbyObservations() {
       mHelper.loading();
       // register a broadcast receiver to handle observations when complete
       mNearbyReceiver = new NearbyObservationsReceiver(mObservationsOverlay);
       IntentFilter filter = new IntentFilter(INaturalistService.ACTION_NEARBY);
       registerReceiver(mNearbyReceiver, filter);

       Intent serviceIntent = new Intent(INaturalistService.ACTION_NEARBY, null, this, INaturalistService.class);
       GeoPoint center = mMapView.getMapCenter();
       int span = Math.max(mMapView.getLatitudeSpan(),mMapView.getLongitudeSpan());
       Double miny = (center.getLatitudeE6() - (span / 2)) / 1e6;
       Double maxy = (center.getLatitudeE6() + (span / 2)) / 1e6;
       Double minx = (center.getLongitudeE6() - (span / 2)) / 1e6;
       Double maxx = (center.getLongitudeE6() + (span / 2)) / 1e6;
       serviceIntent.putExtra("minx", minx);
       serviceIntent.putExtra("maxx", maxx);
       serviceIntent.putExtra("miny", miny);
       serviceIntent.putExtra("maxy", maxy);
       startService(serviceIntent);
    }

    private boolean locationEnabled() {
        return mLocationEnabled;
    }

    private void startLocation() {
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        }

        if (mLocationListener == null) {
            // Define a listener that responds to location updates
            mLocationListener = new LocationListener() {
                public void onLocationChanged(Location location) {
                    // Called when a new location is found by the network location provider.
                    handleNewLocation(location);
                }

                public void onStatusChanged(String provider, int status, Bundle extras) {}
                public void onProviderEnabled(String provider) {}
                public void onProviderDisabled(String provider) {}
            };
        }

        // Register the listener with the Location Manager to receive location updates
        if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener);
        }
        if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
        }

        mOverlays.add(mPositionOverlay);
        mPositionOverlay.updateLocation(mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
        mLocationEnabled = true;
    }

    private void stopLocation() {
        if (mLocationManager != null && mLocationListener != null) {
            // Log.d(TAG, "removing location updates");
            mLocationManager.removeUpdates(mLocationListener);
            mOverlays.remove(mPositionOverlay);
            mLocationEnabled = false;
        }
        mMapView.postInvalidate();
    }

    private void handleNewLocation(Location location) {
        mCurrentLocation = location;
        mPositionOverlay.updateLocation(location);
        this.runOnUiThread(new Runnable() {
            public void run() {
                mMapView.postInvalidate();
            }
        });
    }

    private void zoomToLocation(Location location) {
        if (location == null) return;
        int lat = ((Double) (location.getLatitude() * 1e6)).intValue();
        int lon = ((Double) (location.getLongitude() * 1e6)).intValue();
        GeoPoint point = new GeoPoint(lat, lon);
        mMapView.getController().animateTo(point);
    }

    private class NearbyObservationsReceiver extends BroadcastReceiver {
        private ObservationItemizedOverlay mOverlay;

        public NearbyObservationsReceiver(ObservationItemizedOverlay overlay) {
            super();
            mOverlay = overlay;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            mHelper.stopLoading();
            Bundle extras = intent.getExtras();
            String error = extras.getString("error");
            if (error != null) {
                mHelper.alert("Couldn't load nearby observations: " + error);
                return;
            }
            Double minx = extras.getDouble("minx");
            Double maxx = extras.getDouble("maxx");
            Double miny = extras.getDouble("miny");
            Double maxy = extras.getDouble("maxy");
            Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION,
                    "(latitude BETWEEN "+miny+" AND "+maxy+") AND (longitude BETWEEN "+minx+" AND "+maxx+")", // selection
                    null,
                    Observation.DEFAULT_SORT_ORDER);
            c.moveToFirst();
            while (c.isAfterLast() == false) {
                mOverlay.addObservation(new Observation(c));
                c.moveToNext();
            }
            Toast.makeText(getApplicationContext(), "Found " + c.getCount() + " observations", Toast.LENGTH_SHORT).show();
            unregisterReceiver(mNearbyReceiver);
        }
    }
}


text:
  <link rel="stylesheet" type="text/css" href="css/tips.css">

To open any particular method or field in the editor quickly, press &shortcut:GotoSymbol; (Navigate | Symbol) and start typing its name.

Choose the symbol from a drop-down list that appears.

 <icon src="consulo.platform.base.tips.TipsIconGroup@goto_symbol" width="311" height="95"></icon>


text:
.class public Landroid/net/wifi/ScanResult$InformationElement;
.super Ljava/lang/Object;
.source "ScanResult.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/net/wifi/ScanResult;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "InformationElement"
.end annotation

# static fields
.field public static final EID_BSS_LOAD:I = 0xb

.field public static final EID_ERP:I = 0x2a

.field public static final EID_EXTENDED_CAPS:I = 0x7f

.field public static final EID_EXTENDED_SUPPORTED_RATES:I = 0x32

.field public static final EID_HT_OPERATION:I = 0x3d

.field public static final EID_INTERWORKING:I = 0x6b

.field public static final EID_ROAMING_CONSORTIUM:I = 0x6f

.field public static final EID_RSN:I = 0x30

.field public static final EID_SSID:I = 0x0

.field public static final EID_SUPPORTED_RATES:I = 0x1

.field public static final EID_TIM:I = 0x5

.field public static final EID_VHT_OPERATION:I = 0xc0

.field public static final EID_VSA:I = 0xdd

.field public static final EID_WAPI:I = 0x44

# instance fields
.field public bytes:[B

.field public id:I

# direct methods
.method public constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method public constructor <init>(Landroid/net/wifi/ScanResult$InformationElement;)V
    .locals 1

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    iget v0, p1, Landroid/net/wifi/ScanResult$InformationElement;->id:I

    iput v0, p0, Landroid/net/wifi/ScanResult$InformationElement;->id:I

    iget-object v0, p1, Landroid/net/wifi/ScanResult$InformationElement;->bytes:[B

    invoke-virtual {v0}, Ljava/lang/Object;->clone()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, [B

    iput-object v0, p0, Landroid/net/wifi/ScanResult$InformationElement;->bytes:[B

    return-void
.end method


text:
const fs = require('fs');
const execSync = require('child_process').execSync;
const path = require('path');
const temp = require('temp').track();

const webpack_json = path.resolve(path.dirname(__filename), './webpack_json.py');

module.exports = function({ pluginFile, plugins, pluginPaths }) {
  // the temporary path where the webpack_json json is stored
  const webpack_json_tempfile = temp.openSync({ suffix: '.json' }).path;

  // Extract the relevant information about the plugin configuration from the Python code.

  // For reasons unknown, there is an extra /usr/bin injected into PATH while running
  // execSync, which by-passes the virtualenv!

  // Refs: https://github.com/yarnpkg/yarn/issues/5874
  // See PR: https://github.com/learningequality/kolibri/pull/3777

  // You can debug it like this:
  //     execSync("PATH=$(echo $PATH | sed 's/\\/usr\\/bin://g')\":/usr/bin\" which python >&2 && exit 1", {env: process.env});
  // ..hence, we have manipulated the path in the shell command to remove Node's
  // unwanted manipulation
  let command = `python ${webpack_json} --output_file ${webpack_json_tempfile} `;
  // The plugin file takes precedence here.
  if (pluginFile) {
    command += `--plugin_file ${pluginFile}`;
  } else if (plugins.length) {
    const allPlugins = plugins.join(' ');
    command += `--plugins ${allPlugins}`;
    if (pluginPaths.length && pluginPaths.length === plugins.length) {
      const allPaths = pluginPaths.map(p => path.resolve(process.cwd(), p)).join(' ');
      command += ` --plugin_paths ${allPaths}`;
    } else if (pluginPaths.length && pluginPaths.length !== plugins.length) {
      throw ReferenceError('Plugin paths and plugins must be of equal length');
    }
  }
  if (process.platform !== 'win32') {
    execSync(`PATH=$(echo $PATH | sed 's/\\/usr\\/bin://g')":/usr/bin" ${command}`);
  } else {
    execSync(command);
  }

  const result = fs.readFileSync(webpack_json_tempfile);

  temp.cleanupSync(); // cleanup the tempfile immediately!

  if (result.length > 0) {
    // The above script prints JSON to stdout, here we parse that JSON and use it
    // as input to our webpack configuration builder.
    return JSON.parse(result);
  }

  return [];
};


text:
<?php

namespace Zephir\Types;

use Zephir\Call;
use Zephir\CompilationContext;
use Zephir\Expression;
use Zephir\Builder\FunctionCallBuilder;
use Zephir\FunctionCall;

/**
 * ArrayType
 *
 * Defines methods of the built-in array type
 */
class ArrayType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public $methodMap = array(
        'join' => 'join',
        'reversed' => 'array_reverse',
        'rev' => 'array_reverse',
        'diff' => 'array_diff',
        'flip' => 'array_flip',
        'walk' => 'array_walk',
        'haskey' => 'array_key_exists',
        'keys' => 'array_keys',
        'values' => 'array_values',
        'split' => 'array_chunk',
        'combine' => 'array_combine',
        'intersect' => 'array_intersect',
        'merge' => 'array_merge',
        'mergerecursive' => 'array_merge_recursive',
        'pad' => 'array_pad',
        'pop' => 'array_pop',
        'push' => 'array_push',
        'rand' => 'array_rand',
        'replace' => 'array_replace',
        'map' => 'array_map',
        'replacerecursive' => 'array_replace_recursive',
        'shift' => 'array_shift',
        'slice' => 'array_slice',
        'splice' => 'array_splice',
        'sum' => 'array_sum',
        'unique' => 'array_unique',
        'prepend' => 'array_unshift',
        'count' => 'count',
        'current' => 'current',
        'each' => 'each',
        'end' => 'end',
        'key' => 'key',
        'next' => 'next',
        'prev' => 'prev',
        'reset' => 'reset',
        'sort' => 'sort',
        'sortbykey' => 'ksort',
        'reversesort' => 'rsort',
        'reversesortbykey' => 'krsort',
        'shuffle' => 'shuffle',
        'tojson' => 'json_encode',
        'reduce' => 'array_reduce',
    );

    /**
     * {@inheritdoc}
     */
    public function getTypeName()
    {
        return 'array';
    }

    /**
     * {@inheritdoc}
     */
    protected function getNumberParam($methodName)
    {
        if ($methodName == "map") {
            return 1;
        }

        return 0;
    }

    /**
     * Transforms calls to method "join" to function calls to "join"
     *
     * @param object $caller
     * @param CompilationContext $compilationContext
     * @param Call $call
     * @param array $expression
     * @return bool|\Zephir\CompiledExpression
     */
    public function join($caller, CompilationContext $compilationContext, Call $call, array $expression)
    {
        $builder = new FunctionCallBuilder(
            'join',
            array_merge($expression['parameters'], array(array('parameter' => $caller))),
            FunctionCall::CALL_NORMAL,
            $expression['file'],
            $expression['line'],
            $expression['char']
        );

        $expression = new Expression($builder->get());

        return $expression->compile($compilationContext);
    }
}


text:
title: PlON (Python)
keywords: spherical harmonics software package, spherical harmonic transform, legendre functions, multitaper spectral analysis, fortran, Python, gravity, magnetic field
sidebar: mydoc_sidebar
permalink: pyplon.html
summary:
tags: [python]
toc: false
editdoc: pydoc
---

Compute all the orthonormalized Legendre polynomials.

## Usage

`p` = PlON (`lmax`, `z`)

## Returns

`p` : float, dimension (`lmax`+1)
:   An array of orthonormalized Legendre polynomials up to degree `lmax`. Degree `l` corresponds to array index `l`.

## Parameters

`lmax` : integer
:   The maximum degree of the Legendre polynomials to be computed.

`z` : float
:   The argument of the Legendre polynomial.

## Description

`PlON` will calculate all of the orthonormalized Legendre polynomials up to degree `lmax` for a given argument. These are calculated using a standard three-term recursion formula. The integral of the orthonormalized normalized Legendre polynomials over the interval [-1, 1] is 2/(4pi).

## See also

[plbar](pyplbar.html), [plbar_d1](pyplbar_d1.html), [plmbar](pyplmbar.html), [plmbar_d1](pyplmbar_d1.html), [plon_d1](pyplon_d1.html), [plmon](pyplmon.html), [plmon_d1](pyplmon_d1.html), [plschmidt](pyplschmidt.html), [plschmidt_d1](pyplschmidt_d1.html), [plmschmidt](pyplmschmidt.html), [plmschmidt_d1](pyplmschmidt_d1.html), [plegendre](pyplegendre.html), [plegendre_d1](pyplegendre_d1.html), [plegendrea](pyplegendrea.html), [plegendrea_d1](pyplegendrea_d1.html)


text:
<?php

/**
 * Template Name: Quote Success Page
 * Description: Plantilla para la página de cotizaciones
 */

?>

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
	<?php get_template_part('templates/head'); ?>

	<body <?php body_class('fuelux'); ?> >
		<?php get_template_part('templates/menu'); ?>

        <?php get_template_part('templates/header');?>
		<?php get_template_part('templates/page'); ?>
		<?php
		$args = array(
				'post_type' => 'footer_section',
			);

		$loop = new WP_Query( $args );

	    while ( $loop->have_posts() ) :
			$loop->the_post();

	 	?>
	 		<?php get_template_part('templates/footer'); ?>
	 	<?php endwhile; ?>


text:
<?php

declare(strict_types=1);

namespace OAuth2Framework\Component\Server\TokenEndpointAuthMethod;

use Assert\Assertion;
use OAuth2Framework\Component\Server\Model\Client\Client;
use OAuth2Framework\Component\Server\Model\Client\ClientId;
use OAuth2Framework\Component\Server\Model\DataBag\DataBag;
use Psr\Http\Message\ServerRequestInterface;

abstract class ClientSecretPost implements TokenEndpointAuthMethodInterface
{
    /**
     * @var int
     */
    private $secretLifetime;

    public function __construct(int $secretLifetime = 0)
    {
        Assertion::greaterOrEqualThan($secretLifetime, 0);

        $this->secretLifetime = $secretLifetime;
    }

    /**
     * {@inheritdoc}
     */
    public function getSchemesParameters(): array
    {
        return [];
    }

    /**
     * {@inheritdoc}
     */
    public function findClientId(ServerRequestInterface $request, &$clientCredentials = null): ? ClientId
    {
        $parameters = $request->getParsedBody() ?? [];
        if (array_key_exists('client_id', $parameters) && array_key_exists('client_secret', $parameters)) {
            $clientCredentials = $parameters['client_secret'];

            return ClientId::create($parameters['client_id']);
        }

        return null;
    }

    /**
     * {@inheritdoc}
     */
    public function checkClientConfiguration(DataBag $command_parameters, DataBag $validated_parameters): DataBag
    {
        $validated_parameters = $validated_parameters->with('client_secret', $this->createClientSecret());
        $validated_parameters = $validated_parameters->with('client_secret_expires_at', (0 === $this->secretLifetime ? 0 : time() + $this->secretLifetime));

        return $validated_parameters;
    }

    /**
     * {@inheritdoc}
     */
    public function isClientAuthenticated(Client $client, $clientCredentials, ServerRequestInterface $request): bool
    {
        return hash_equals($client->get('client_secret'), $clientCredentials);
    }

    /**
     * {@inheritdoc}
     */
    public function getSupportedAuthenticationMethods(): array
    {
        return ['client_secret_post'];
    }

    /**
     * @return string
     */
    abstract protected function createClientSecret(): string;
}


text:
from leaf_recognition.features import BasicGeometricFeatures

#fea = BasicGeometricFeatures('/home/xudshen/workspace/dataset/Anhui Barberry/1553.jpg')
fea = BasicGeometricFeatures.BasicGeometricFeatures('/home/xudshen/workspace/dataset/camphortree/2166.jpg', 'camphortree')
#fea = BasicGeometricFeatures.BasicGeometricFeatures('/home/xudshen/workspace/dataset/apple.jpg')
fea.process()


text:
<?php

namespace FoodCoopBundle\Controller;

use FoodCoopBundle\Actions\OrderActivateAction;
use FoodCoopBundle\Actions\OrderCreateAction;
use FoodCoopBundle\Actions\OrderIndexAction;
use FoodCoopBundle\Actions\OrderIndexCurrentAction;
use FoodCoopBundle\Actions\OrderRemoveAction;
use FoodCoopBundle\Actions\OrderUpdateAction;
use FoodCoopBundle\Entity\Order;
use FoodCoopBundle\Request\Criteria;
use FOS\RestBundle\Util\Codes;

class OrderController
{
    use RestTrait;

    /**
     * @var OrderCreateAction
     */
    private $create;

    /**
     * @var OrderUpdateAction
     */
    private $update;

    /**
     * @var OrderIndexAction
     */
    private $index;

    /**
     * @var OrderRemoveAction
     */
    private $remove;

    /**
     * @var OrderActivateAction
     */
    private $activate;

    /**
     * @var OrderIndexCurrentAction
     */
    private $current;

    public function __construct(
        OrderCreateAction $create,
        OrderUpdateAction $update,
        OrderIndexAction $index,
        OrderRemoveAction $remove,
        OrderActivateAction $activate,
        OrderIndexCurrentAction $current
    )
    {
        $this->create = $create;
        $this->update = $update;
        $this->index = $index;
        $this->remove = $remove;
        $this->activate = $activate;
        $this->current = $current;
    }

    /**
     * @param Criteria $criteria
     *
     * @return \FOS\RestBundle\View\View
     */
    public function indexAction(Criteria $criteria)
    {
        return $this->renderRestView(
            $this->index->setCriteria($criteria)->execute(),
            Codes::HTTP_OK,
            [],
            ['orders_index']
        );
    }

    /**
     * @return \FOS\RestBundle\View\View
     */
    public function createAction()
    {
        return $this->renderRestView(
            $this->create->execute(),
            Codes::HTTP_CREATED,
            [],
            ['orders_create']
        );
    }

    /**
     * @param Order $order
     * @return \FOS\RestBundle\View\View|null
     */
    public function editAction(Order $order)
    {
        return $this->renderRestView(
            $this->update->setOrder($order)->execute(),
            Codes::HTTP_OK,
            [],
            ['orders_update']
        );
    }

    /**
     * @param Order $order
     */
    public function removeAction(Order $order)
    {
        $this->remove->setOrder($order)->execute();
    }

    /**
     * @param Order $order
     *
     * @return \FOS\RestBundle\View\View
     */
    public function viewAction(Order $order)
    {
        return $this->renderRestView($order, Codes::HTTP_OK, [], ['orders_view']);
    }

    /**
     * @param Order $order
     * @return \FOS\RestBundle\View\View
     */
    public function activateAction(Order $order)
    {
        $this->activate->setOrder($order)->execute();
    }

    /**
     * @param Criteria $criteria
     *
     * @return \FOS\RestBundle\View\View
     */
    public function currentAction(Criteria $criteria)
    {
        return $this->renderRestView(
            $this->current->setCriteria($criteria)->execute(),
            Codes::HTTP_OK,
            [],
            ['order_list']
        );
    }
}


text:
sidebar_label: Mouse.click
---

# Mouse.click() method

Shortcut for `mouse.move`, `mouse.down` and `mouse.up`.

#### Signature:

```typescript
class Mouse {
  click(
    x: number,
    y: number,
    options?: MouseOptions & {
      delay?: number;
    }
  ): Promise<void>;
}
```

## Parameters

| Parameter | Type                                                                  | Description                                           |
| --------- | --------------------------------------------------------------------- | ----------------------------------------------------- |
| x         | number                                                                | Horizontal position of the mouse.                     |
| y         | number                                                                | Vertical position of the mouse.                       |
| options   | [MouseOptions](./puppeteer.mouseoptions.md) & { delay?: number; } | (Optional) Optional MouseOptions. |

**Returns:**

Promise<void>