text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>python.sparknlp.internal.extended_java_wrapper — Spark NLP 4.2.3 documentation</title>

  <link href="../../../../static/styles/theme.css?digest=1e1de1a1873e13ef5536" rel="stylesheet">
<link href="../../../../static/styles/pydata-sphinx-theme.css?digest=1e1de1a1873e13ef5536" rel="stylesheet">

  <link rel="stylesheet"
    href="../../../../static/vendor/fontawesome/6.1.2/css/all.min.css">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../../../static/vendor/fontawesome/6.1.2/webfonts/fa-solid-900.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../../../static/vendor/fontawesome/6.1.2/webfonts/fa-brands-400.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../../../static/vendor/fontawesome/6.1.2/webfonts/fa-regular-400.woff2">

    <link rel="stylesheet" type="text/css" href="../../../../static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../../../../static/graphviz.css" />
    <link rel="stylesheet" type="text/css" href="../../../../static/css/custom.css" />

  <link rel="preload" as="script" href="../../../../static/scripts/pydata-sphinx-theme.js?digest=1e1de1a1873e13ef5536">

    <link rel="shortcut icon" href="../../../../static/fav.ico"/>
    <link rel="index" title="Index" href="../../../../genindex.html" />
    <link rel="search" title="Search" href="../../../../search.html" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="docsearch:language" content="en">

  <input type="checkbox" class="sidebar-toggle" name="__primary" id="__primary">

  <input type="checkbox" class="sidebar-toggle" name="__secondary" id="__secondary">

<form class="bd-search d-flex align-items-center" action="../../../../search.html" method="get">

  <input type="search" class="form-control" name="q" id="search-input" placeholder="Search the docs ..." aria-label="Search the docs ..." autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
  Ctrl+K
</form>

        Site Navigation

                        Getting Started

                        User Guide

                        Third Party Projects

                        API Reference

<button class="btn btn-sm navbar-btn search-button search-button__button" title="Search" data-toggle="tooltip">

</button>

<button class="btn btn-sm navbar-btn search-button search-button__button" title="Search" data-toggle="tooltip">

</button>

        Site Navigation

                        Getting Started

                        User Guide

                        Third Party Projects

                        API Reference

Source code for python.sparknlp.internal.extended_java_wrapper

#  Copyright 2017-2022 John Snow Labs
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
"""Contains classes for extensions of the PySpark JavaWrapper."""

from pyspark import SparkContext
from pyspark.ml.wrapper import JavaWrapper
from pyspark.sql import DataFrame
from distutils.version import LooseVersion

[docs]class ExtendedJavaWrapper(JavaWrapper):

    def __init__(self, java_obj, *args):
        super(ExtendedJavaWrapper, self).__init__(java_obj)
        self.sc = SparkContext._active_spark_context
        self._java_obj = self.new_java_obj(java_obj, *args)
        self.java_obj = self._java_obj

    def __del__(self):
        pass

    def apply(self):
        return self._java_obj

    def new_java_obj(self, java_class, *args):
        return self._new_java_obj(java_class, *args)

[docs]    def new_java_array(self, pylist, java_class):
        """
        ToDo: Inspired from spark 2.0. Review if spark changes
        """
        java_array = self.sc._gateway.new_array(java_class, len(pylist))
        for i in range(len(pylist)):
            java_array[i] = pylist[i]
        return java_array

    def new_java_array_string(self, pylist):
        java_array = self._new_java_array(pylist, self.sc._gateway.jvm.java.lang.String)
        return java_array

    def new_java_array_integer(self, pylist):
        java_array = self._new_java_array(pylist, self.sc._gateway.jvm.java.lang.Integer)
        return java_array

    def spark_version(self):
        return self.sc.version

    def getDataFrame(self, spark, jdf):
        if LooseVersion(self.spark_version()) >= LooseVersion("3.3.0"):
            return DataFrame(jdf, spark._getActiveSessionOrCreate())
        else:
            return DataFrame(jdf, spark._wrapped)

    © Copyright 2022, John Snow Labs.

Created using Sphinx 5.3.0.


text:
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace SP.Test.Files
{

	[TestClass]
	[DeploymentItem("TestProject")]
	public class StreamProcessorFiles_Src_Tests
	{

		#region Additional class to hold metadata for Tests with generic methods

		private class FileMetadata
		{
			public string AdditionalInfo1;
			public int AdditionalInfo2;
		}

		#endregion

		#region Test fields and properties

		/// The stream processor.
		private StreamProcessor<dynamic> sp;

		/// Gets or sets the test context.
		/// <value>The test context.</value>
		public TestContext TestContext { get; set; }

		#endregion

		#region Test initializing method

		/// Setups the test method environment.
		[TestInitialize()]
		public void SetupTestMethodEnvironment()
		{
			sp = new StreamProcessor<dynamic>();
		}

		#endregion

		#region Test procedures

		/// Tests  Src  urces the name of the test with simple file.
		[TestMethod]
		public void SrcTestWithSimpleFileName()
		{
			Assert.IsNotNull(sp.Streams, "There is no instance of the list of files before the test procedure has been started.");
			Assert.AreEqual(0, sp.Streams.Count, "The list of files already contains files before the test procedure has been started.");

			var fluentStreamProcessorInstance = sp.Src("/index.html");

			Assert.IsNotNull(fluentStreamProcessorInstance);
			Assert.AreSame(sp, fluentStreamProcessorInstance, "The return value of Src is not the same stream processor instance as the original stream processor instance.");
			Assert.IsNotNull(sp.Streams, "There is no instance of the list of files after the test procedure is completed.");
			Assert.AreEqual(1, sp.Streams.Count, "The list of files does not contain the expected amount of files.");
			Assert.AreEqual("index.html", sp.Streams[0].SourceFileName, "This is not the expected file name.");
		}

		[TestMethod]
		public void SrcTestWithSingleStarFileName()
		{
			Assert.IsNotNull(sp.Streams, "There is no instance of the list of files before the test procedure has been started.");
			Assert.AreEqual(0, sp.Streams.Count, "The list of files already contains files before the test procedure has been started.");

			var fluentStreamProcessorInstance = sp.Src("*.html");

			Assert.IsNotNull(fluentStreamProcessorInstance);
			Assert.AreSame(sp, fluentStreamProcessorInstance, "The return value of Src is not the same stream processor instance as the original stream processor instance.");
			Assert.IsNotNull(sp.Streams, "There is no instance of the list of files after the test procedure is completed.");
			Assert.AreEqual(1, sp.Streams.Count, "The list of files does not contain the expected amount of files.");
			Assert.AreEqual("index.html", sp.Streams[0].SourceFileName, "This is not the expected file name.");
		}

		[TestMethod]
		public void SrcTestWithGenericMetadataType()
		{
			Assert.IsNotNull(sp.Streams, "There is no instance of the list of files before the test procedure has been started.");
			Assert.AreEqual(0, sp.Streams.Count, "The list of files already contains files before the test procedure has been started.");

			var fluentStreamProcessorInstance = sp.Src(filename => new FileMetadata { AdditionalInfo1 = filename, AdditionalInfo2 = 42 }, "index.html");

			Assert.IsNotNull(fluentStreamProcessorInstance);
			Assert.AreSame(sp, fluentStreamProcessorInstance, "The return value of Src is not the same stream processor instance as the original stream processor instance.");
			Assert.IsNotNull(sp.Streams, "There is no instance of the list of files after the test procedure is completed.");
			Assert.AreEqual(1, sp.Streams.Count, "The list of files does not contain the expected amount of files.");
			var file = sp.Streams[0];
			Assert.IsInstanceOfType(file, typeof(SPStream<FileMetadata>));
		}

		#endregion

	}

}

redpajama_set_name: RedPajamaGithub


text:
package net.ypresto.miniguava.collect.immutables;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.testing.NullPointerTester;

import junit.framework.TestCase;

import java.util.Arrays;

/**
 * Unit test for {@code ObjectArrays}.
 *
 * @author Kevin Bourrillion
 */
// miniguava: Picked only necessary tests.
public class ObjectArraysTest extends TestCase {

  public void testNullPointerExceptions() {
    NullPointerTester tester = new NullPointerTester();
    tester.testAllPublicStaticMethods(ObjectArrays.class);
  }

  public void testNewArray_fromArray_Empty() {
    String[] in = new String[0];
    String[] empty = ObjectArrays.newArray(in, 0);
    assertThat(empty).isEmpty();
  }

  public void testNewArray_fromArray_Nonempty() {
    String[] array = ObjectArrays.newArray(new String[0], 2);
    assertEquals(String[].class, array.getClass());
    assertThat(array).hasLength(2);
    assertNull(array[0]);
  }

  public void testNewArray_fromArray_OfArray() {
    String[][] array = ObjectArrays.newArray(new String[0][0], 1);
    assertEquals(String[][].class, array.getClass());
    assertThat(array).hasLength(1);
    assertNull(array[0]);
  }

  public void testEmptyArrayToEmpty() {
    doTestNewArrayEquals(new Object[0], 0);
  }

  public void testEmptyArrayToNonEmpty() {
    checkArrayEquals(new Long[5], ObjectArrays.newArray(new Long[0], 5));
  }

  public void testNonEmptyToShorter() {
    checkArrayEquals(new String[9], ObjectArrays.newArray(new String[10], 9));
  }

  public void testNonEmptyToSameLength() {
    doTestNewArrayEquals(new String[10], 10);
  }

  public void testNonEmptyToLonger() {
    checkArrayEquals(new String[10],
        ObjectArrays.newArray(new String[] { "a", "b", "c", "d", "e" }, 10));
  }

  private static void checkArrayEquals(Object[] expected, Object[] actual) {
    assertTrue("expected(" + expected.getClass() + "): " + Arrays.toString(expected)
        + " actual(" + actual.getClass() + "): " + Arrays.toString(actual),
        arrayEquals(expected, actual));
  }

  private static boolean arrayEquals(Object[] array1, Object[] array2) {
    assertSame(array1.getClass(), array2.getClass());
    return Arrays.equals(array1, array2);
  }

  private static void doTestNewArrayEquals(Object[] expected, int length) {
    checkArrayEquals(expected, ObjectArrays.newArray(expected, length));
  }
}


text:
package org.jboss.resteasy.test.providers.jaxb.resource;

import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "childType")
public class JaxbCacheChild {
    private String name;

    @XmlTransient
    private JaxbCacheParent parent;

    public JaxbCacheChild() {

    }

    public JaxbCacheChild(final String name) {
        this.name = name;
    }

    /**
     * Get the name.
     *
     * @return the name.
     */
    public String getName() {
        return name;
    }

    /**
     * Set the name.
     *
     * @param name The name to set.
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * Get the parent.
     *
     * @return the parent.
     */
    public JaxbCacheParent getParent() {
        return parent;
    }

    /**
     * Set the parent.
     *
     * @param parent The parent to set.
     */
    public void setParent(JaxbCacheParent parent) {
        this.parent = parent;
    }

    /**
     * Set parent after unmarshalling
     *
     * @param unmarshaller
     * @param JaxbCacheParent
     */
    public void afterUnmarshal(Unmarshaller unmarshaller, Object object) {
        this.parent = (JaxbCacheParent) object;
    }
}


text:
module Rakudax
  class Settings < Settingslogic
    source Rakudax::Base.settings_path
    namespace Rakudax::Base.env
    suppress_errors true
  end
end


text:
<?php
define('INCLUDE_CHECK',true);
session_start();
include 'connect.php';

if(isset($_POST['time']) && isset($_POST['firstload'])) {
    if(empty($_SESSION['sessiontime'])) {
        $_SESSION['sessiontime'] = 1;
        echo $_SESSION['sessiontime'];
    } else {
        if($_POST['firstload'] == 'true') {
            echo $_SESSION['sessiontime'];
        } else {
            $_SESSION['sessiontime'] = $_POST['time'];
            echo $_SESSION['sessiontime'];
        }
    }
    $sql = "UPDATE tbl_visit set timespent = " . $_SESSION['sessiontime'] . " WHERE visitid = " . $_SESSION['visitid'];
    mysqli_query($GLOBALS['sqllink'], $sql);
}

?>


text:
package com.alipay.api.domain;

import java.util.List;

import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;

/**
 * 手艺人作品信息批量查询接口
 *
 * @author auto create
 * @since 1.0, 2017-10-11 20:35:17
 */
public class KoubeiCraftsmanDataWorkBatchqueryModel extends AlipayObject {

	private static final long serialVersionUID = 7424494735647227957L;

	/**
	 * 服务商、服务商员工、商户、商户员工等口碑角色操作时必填,对应为《koubei.member.data.oauth.query》中的auth_code,默认有效期24小时;isv自身角色操作的时候,无需传该参数
	 */
	@ApiField("auth_code")
	private String authCode;

	/**
	 * 口碑手艺人id。是创建手艺人接口koubei.craftsman.data.provider.create返回的craftsman_id,或通过查询手艺人信息接口koubei.craftsman.data.provider查询craftsman_id
	 */
	@ApiField("craftsman_id")
	private String craftsmanId;

	/**
	 * 页码,大于0,最大为int的最大值
	 */
	@ApiField("page_no")
	private String pageNo;

	/**
	 * 每页的条数,大于0,最大不超过100条
	 */
	@ApiField("page_size")
	private String pageSize;

	/**
	 * 手艺人作品id列表,全局唯一,是创建手艺人作品接口koubei.craftsman.data.work.create返回的work_id
	 */
	@ApiListField("work_ids")
	@ApiField("string")
	private List<String> workIds;

	public String getAuthCode() {
		return this.authCode;
	}
	public void setAuthCode(String authCode) {
		this.authCode = authCode;
	}

	public String getCraftsmanId() {
		return this.craftsmanId;
	}
	public void setCraftsmanId(String craftsmanId) {
		this.craftsmanId = craftsmanId;
	}

	public String getPageNo() {
		return this.pageNo;
	}
	public void setPageNo(String pageNo) {
		this.pageNo = pageNo;
	}

	public String getPageSize() {
		return this.pageSize;
	}
	public void setPageSize(String pageSize) {
		this.pageSize = pageSize;
	}

	public List<String> getWorkIds() {
		return this.workIds;
	}
	public void setWorkIds(List<String> workIds) {
		this.workIds = workIds;
	}

}


text:
"""Service Address Resource formatter."""

from aquilon.worker.formats.formatters import ObjectFormatter
from aquilon.worker.formats.resource import ResourceFormatter
from aquilon.aqdb.model import ServiceAddress

class ServiceAddressFormatter(ResourceFormatter):
    def extra_details(self, srv, indent=""):
        details = []
        details.append(indent + "  Address: {0:a}".format(srv.dns_record))
        if srv.interfaces:
            details.append(indent + "  Interfaces: %s" %
                           ", ".join(sorted(iface.name for iface in
                                            srv.interfaces)))
        return details

    def fill_proto(self, srv, skeleton, embedded=True, indirect_attrs=True):
        if hasattr(skeleton, 'service_address'):
            # When working on a Resource and not directly on a ServiceAddress
            super(ServiceAddressFormatter, self).fill_proto(srv, skeleton)
            skeleton = skeleton.service_address

        skeleton.ip = str(srv.ip)
        skeleton.fqdn = str(srv.dns_record)
        skeleton.interfaces.extend(iface.name for iface in
                                   srv.interfaces)

        if srv.dns_record.alias_cnt:
            skeleton.aliases.extend(str(a.fqdn) for a in
                                    srv.dns_record.all_aliases)

        self.redirect_proto(srv.network_environment,
                            skeleton.network_environment)

ObjectFormatter.handlers[ServiceAddress] = ServiceAddressFormatter()


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_notify_default"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="DefaultNotify" />

    <Button
        android:id="@+id/btn_test"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Test" />

    <include layout="@layout/view_remote" />
</LinearLayout>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>GBD.Build.Blackjack: D:/SourceControl/GitRepos/GBD.Build.BlackJack/blackjack/contrib/x_pexpect/pexpect/replwrap.py File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

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

GBD.Build.Blackjack

A Module allowing for the automatic generation of CMakeLists.txt files from within python

Main Page

Related Pages

Packages

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

Classes |
Namespaces |
Functions |
Variables

replwrap.py File Reference

Go to the source code of this file.

Classes

class  	pexpect.replwrap.REPLWrapper

 	Wrapper for a REPL.  More...

Namespaces

  	pexpect.replwrap

Functions

def 	pexpect.replwrap.u (s)

def 	pexpect.replwrap.python

 	Start a Python shell and return a :class:REPLWrapper object.  More...

def 	pexpect.replwrap.bash

 	Start a bash shell and return a :class:REPLWrapper object.  More...

Variables

tuple 	pexpect.replwrap.PY3 = (sys.version_info[0] >= 3)

 	pexpect.replwrap.basestring = str

tuple 	pexpect.replwrap.PEXPECT_PROMPT = u('[PEXPECT_PROMPT>')

tuple 	pexpect.replwrap.PEXPECT_CONTINUATION_PROMPT = u('[PEXPECT_PROMPT+')

blackjack

contrib

x_pexpect

pexpect

replwrap.py

Generated by

     1.8.10


text:
package org.apache.catalina.valves;

import java.io.IOException;
import java.util.concurrent.Semaphore;

import javax.servlet.ServletException;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleState;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;

/**
 *
Implementation of a Valve that limits concurrency.

 *
 *
This Valve may be attached to any Container, depending on the granularity
 * of the concurrency control you wish to perform. Note that internally, some
 * async requests may require multiple serial requests to complete what - to the
 * user - appears as a single request.

 *
 * @author Remy Maucherat
 */
public class SemaphoreValve extends ValveBase {

    //------------------------------------------------------ Constructor
    public SemaphoreValve() {
        super(true);
    }

    // ----------------------------------------------------- Instance Variables

    /**
     * Semaphore.
     */
    protected Semaphore semaphore = null;

    // ------------------------------------------------------------- Properties

    /**
     * Concurrency level of the semaphore.
     */
    protected int concurrency = 10;
    public int getConcurrency() { return concurrency; }
    public void setConcurrency(int concurrency) { this.concurrency = concurrency; }

    /**
     * Fairness of the semaphore.
     */
    protected boolean fairness = false;
    public boolean getFairness() { return fairness; }
    public void setFairness(boolean fairness) { this.fairness = fairness; }

    /**
     * Block until a permit is available.
     */
    protected boolean block = true;
    public boolean getBlock() { return block; }
    public void setBlock(boolean block) { this.block = block; }

    /**
     * Block interruptibly until a permit is available.
     */
    protected boolean interruptible = false;
    public boolean getInterruptible() { return interruptible; }
    public void setInterruptible(boolean interruptible) { this.interruptible = interruptible; }

    /**
     * Start this component and implement the requirements
     * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
     *
     * @exception LifecycleException if this component detects a fatal error
     *  that prevents this component from being used
     */
    @Override
    protected synchronized void startInternal() throws LifecycleException {

        semaphore = new Semaphore(concurrency, fairness);

        setState(LifecycleState.STARTING);
    }

    /**
     * Stop this component and implement the requirements
     * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
     *
     * @exception LifecycleException if this component detects a fatal error
     *  that prevents this component from being used
     */
    @Override
    protected synchronized void stopInternal() throws LifecycleException {

        setState(LifecycleState.STOPPING);

        semaphore = null;
    }

    // --------------------------------------------------------- Public Methods

    /**
     * Do concurrency control on the request using the semaphore.
     *
     * @param request The servlet request to be processed
     * @param response The servlet response to be created
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    @Override
    public void invoke(Request request, Response response)
        throws IOException, ServletException {

        if (controlConcurrency(request, response)) {
            boolean shouldRelease = true;
            try {
                if (block) {
                    if (interruptible) {
                        try {
                            semaphore.acquire();
                        } catch (InterruptedException e) {
                            shouldRelease = false;
                            permitDenied(request, response);
                            return;
                        }
                    } else {
                        semaphore.acquireUninterruptibly();
                    }
                } else {
                    if (!semaphore.tryAcquire()) {
                        shouldRelease = false;
                        permitDenied(request, response);
                        return;
                    }
                }
                getNext().invoke(request, response);
            } finally {
                if (shouldRelease) {
                    semaphore.release();
                }
            }
        } else {
            getNext().invoke(request, response);
        }

    }

    /**
     * Subclass friendly method to add conditions.
     * @param request The Servlet request
     * @param response The Servlet response
     * @return true if the concurrency control should occur
     *  on this request
     */
    public boolean controlConcurrency(Request request, Response response) {
        return true;
    }

    /**
     * Subclass friendly method to add error handling when a permit isn't
     * granted.
     * @param request The Servlet request
     * @param response The Servlet response
     * @throws IOException Error writing output
     * @throws ServletException Other error
     */
    public void permitDenied(Request request, Response response)
        throws IOException, ServletException {
        // NO-OP by default
    }

}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
    <link rel="icon" href="favicon.ico" type="image/x-icon">
    <title>Resume</title>

    <link href="%%VERSION%%/css/resume.css" rel="stylesheet">

    %%BASE_SCRIPT%%

Please switch on JavaScript

                Copyright © 2015 Lukasz Sitnik

    You are using old browser.
 Please install a newer version of Internet Explorer, Firefox or Chrome.


text:
/*
 * QEMU/MIPS pseudo-board
 *
 * emulates a simple machine with ISA-like bus.
 * ISA IO space mapped to the 0x14000000 (PHYS) and
 * ISA memory at the 0x10000000 (PHYS, 16Mb in size).
 * All peripherial devices are attached to this "bus" with
 * the standard PC ISA addresses.
*/
#include "hw/hw.h"
#include "hw/mips/mips.h"
#include "hw/mips/cpudevs.h"
#include "hw/i386/pc.h"
#include "hw/char/serial.h"
#include "hw/isa/isa.h"
#include "net/net.h"
#include "sysemu/sysemu.h"
#include "hw/boards.h"
#include "hw/block/flash.h"
#include "qemu/log.h"
#include "hw/mips/bios.h"
#include "hw/ide.h"
#include "hw/loader.h"
#include "elf.h"
#include "hw/timer/mc146818rtc.h"
#include "hw/timer/i8254.h"
#include "sysemu/blockdev.h"
#include "exec/address-spaces.h"
#include "sysemu/qtest.h"

#define MAX_IDE_BUS 2

static const int ide_iobase[2] = { 0x1f0, 0x170 };
static const int ide_iobase2[2] = { 0x3f6, 0x376 };
static const int ide_irq[2] = { 14, 15 };

static ISADevice *pit; /* PIT i8254 */

/* i8254 PIT is attached to the IRQ0 at PIC i8259 */

static struct _loaderparams {
    int ram_size;
    const char *kernel_filename;
    const char *kernel_cmdline;
    const char *initrd_filename;
} loaderparams;

static void mips_qemu_write (void *opaque, hwaddr addr,
                             uint64_t val, unsigned size)
{
    if ((addr & 0xffff) == 0 && val == 42)
        qemu_system_reset_request ();
    else if ((addr & 0xffff) == 4 && val == 42)
        qemu_system_shutdown_request ();
}

static uint64_t mips_qemu_read (void *opaque, hwaddr addr,
                                unsigned size)
{
    return 0;
}

static const MemoryRegionOps mips_qemu_ops = {
    .read = mips_qemu_read,
    .write = mips_qemu_write,
    .endianness = DEVICE_NATIVE_ENDIAN,
};

typedef struct ResetData {
    MIPSCPU *cpu;
    uint64_t vector;
} ResetData;

static int64_t load_kernel(void)
{
    int64_t entry, kernel_high;
    long kernel_size, initrd_size, params_size;
    ram_addr_t initrd_offset;
    uint32_t *params_buf;
    int big_endian;

#ifdef TARGET_WORDS_BIGENDIAN
    big_endian = 1;
#else
    big_endian = 0;
#endif
    kernel_size = load_elf(loaderparams.kernel_filename, cpu_mips_kseg0_to_phys,
                           NULL, (uint64_t *)&entry, NULL,
                           (uint64_t *)&kernel_high, big_endian,
                           ELF_MACHINE, 1);
    if (kernel_size >= 0) {
        if ((entry & ~0x7fffffffULL) == 0x80000000)
            entry = (int32_t)entry;
    } else {
        fprintf(stderr, "qemu: could not load kernel '%s'\n",
                loaderparams.kernel_filename);
        exit(1);
    }

    /* load initrd */
    initrd_size = 0;
    initrd_offset = 0;
    if (loaderparams.initrd_filename) {
        initrd_size = get_image_size (loaderparams.initrd_filename);
        if (initrd_size > 0) {
            initrd_offset = (kernel_high + ~INITRD_PAGE_MASK) & INITRD_PAGE_MASK;
            if (initrd_offset + initrd_size > ram_size) {
                fprintf(stderr,
                        "qemu: memory too small for initial ram disk '%s'\n",
                        loaderparams.initrd_filename);
                exit(1);
            }
            initrd_size = load_image_targphys(loaderparams.initrd_filename,
                                              initrd_offset,
                                              ram_size - initrd_offset);
        }
        if (initrd_size == (target_ulong) -1) {
            fprintf(stderr, "qemu: could not load initial ram disk '%s'\n",
                    loaderparams.initrd_filename);
            exit(1);
        }
    }

    /* Store command line.  */
    params_size = 264;
    params_buf = g_malloc(params_size);

    params_buf[0] = tswap32(ram_size);
    params_buf[1] = tswap32(0x12345678);

    if (initrd_size > 0) {
        snprintf((char *)params_buf + 8, 256, "rd_start=0x%" PRIx64 " rd_size=%li %s",
                 cpu_mips_phys_to_kseg0(NULL, initrd_offset),
                 initrd_size, loaderparams.kernel_cmdline);
    } else {
        snprintf((char *)params_buf + 8, 256, "%s", loaderparams.kernel_cmdline);
    }

    rom_add_blob_fixed("params", params_buf, params_size,
                       (16 << 20) - 264);

    return entry;
}

static void main_cpu_reset(void *opaque)
{
    ResetData *s = (ResetData *)opaque;
    CPUMIPSState *env = &s->cpu->env;

    cpu_reset(CPU(s->cpu));
    env->active_tc.PC = s->vector;
}

static const int sector_len = 32 * 1024;
static
void mips_r4k_init(MachineState *machine)
{
    ram_addr_t ram_size = machine->ram_size;
    const char *cpu_model = machine->cpu_model;
    const char *kernel_filename = machine->kernel_filename;
    const char *kernel_cmdline = machine->kernel_cmdline;
    const char *initrd_filename = machine->initrd_filename;
    char *filename;
    MemoryRegion *address_space_mem = get_system_memory();
    MemoryRegion *ram = g_new(MemoryRegion, 1);
    MemoryRegion *bios;
    MemoryRegion *iomem = g_new(MemoryRegion, 1);
    MemoryRegion *isa = g_new(MemoryRegion, 1);
    int bios_size;
    MIPSCPU *cpu;
    CPUMIPSState *env;
    ResetData *reset_info;
    int i;
    qemu_irq *i8259;
    ISABus *isa_bus;
    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];
    DriveInfo *dinfo;
    int be;

    /* init CPUs */
    if (cpu_model == NULL) {
#ifdef TARGET_MIPS64
        cpu_model = "R4000";
#else
        cpu_model = "24Kf";
#endif
    }
    cpu = cpu_mips_init(cpu_model);
    if (cpu == NULL) {
        fprintf(stderr, "Unable to find CPU definition\n");
        exit(1);
    }
    env = &cpu->env;

    reset_info = g_malloc0(sizeof(ResetData));
    reset_info->cpu = cpu;
    reset_info->vector = env->active_tc.PC;
    qemu_register_reset(main_cpu_reset, reset_info);

    /* allocate RAM */
    if (ram_size > (256 << 20)) {
        fprintf(stderr,
                "qemu: Too much memory for this machine: %d MB, maximum 256 MB\n",
                ((unsigned int)ram_size / (1 << 20)));
        exit(1);
    }
    memory_region_init_ram(ram, NULL, "mips_r4k.ram", ram_size);
    vmstate_register_ram_global(ram);

    memory_region_add_subregion(address_space_mem, 0, ram);

    memory_region_init_io(iomem, NULL, &mips_qemu_ops, NULL, "mips-qemu", 0x10000);
    memory_region_add_subregion(address_space_mem, 0x1fbf0000, iomem);

    /* Try to load a BIOS image. If this fails, we continue regardless,
       but initialize the hardware ourselves. When a kernel gets
       preloaded we also initialize the hardware, since the BIOS wasn't
       run. */
    if (bios_name == NULL)
        bios_name = BIOS_FILENAME;
    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);
    if (filename) {
        bios_size = get_image_size(filename);
    } else {
        bios_size = -1;
    }
#ifdef TARGET_WORDS_BIGENDIAN
    be = 1;
#else
    be = 0;
#endif
    if ((bios_size > 0) && (bios_size <= BIOS_SIZE)) {
        bios = g_new(MemoryRegion, 1);
        memory_region_init_ram(bios, NULL, "mips_r4k.bios", BIOS_SIZE);
        vmstate_register_ram_global(bios);
        memory_region_set_readonly(bios, true);
        memory_region_add_subregion(get_system_memory(), 0x1fc00000, bios);

        load_image_targphys(filename, 0x1fc00000, BIOS_SIZE);
    } else if ((dinfo = drive_get(IF_PFLASH, 0, 0)) != NULL) {
        uint32_t mips_rom = 0x00400000;
        if (!pflash_cfi01_register(0x1fc00000, NULL, "mips_r4k.bios", mips_rom,
                                   dinfo->bdrv, sector_len,
                                   mips_rom / sector_len,
                                   4, 0, 0, 0, 0, be)) {
            fprintf(stderr, "qemu: Error registering flash memory.\n");
	}
    } else if (!qtest_enabled()) {
	/* not fatal */
        fprintf(stderr, "qemu: Warning, could not load MIPS bios '%s'\n",
		bios_name);
    }
    if (filename) {
        g_free(filename);
    }

    if (kernel_filename) {
        loaderparams.ram_size = ram_size;
        loaderparams.kernel_filename = kernel_filename;
        loaderparams.kernel_cmdline = kernel_cmdline;
        loaderparams.initrd_filename = initrd_filename;
        reset_info->vector = load_kernel();
    }

    /* Init CPU internal devices */
    cpu_mips_irq_init_cpu(env);
    cpu_mips_clock_init(env);

    /* The PIC is attached to the MIPS CPU INT0 pin */
    isa_bus = isa_bus_new(NULL, get_system_io());
    i8259 = i8259_init(isa_bus, env->irq[2]);
    isa_bus_irqs(isa_bus, i8259);

    rtc_init(isa_bus, 2000, NULL);

    /* Register 64 KB of ISA IO space at 0x14000000 */
    memory_region_init_alias(isa, NULL, "isa_mmio",
                             get_system_io(), 0, 0x00010000);
    memory_region_add_subregion(get_system_memory(), 0x14000000, isa);

    isa_mem_base = 0x10000000;

    pit = pit_init(isa_bus, 0x40, 0, NULL);

    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
        if (serial_hds[i]) {
            serial_isa_init(isa_bus, i, serial_hds[i]);
        }
    }

    isa_vga_init(isa_bus);

    if (nd_table[0].used)
        isa_ne2000_init(isa_bus, 0x300, 9, &nd_table[0]);

    ide_drive_get(hd, MAX_IDE_BUS);
    for(i = 0; i < MAX_IDE_BUS; i++)
        isa_ide_init(isa_bus, ide_iobase[i], ide_iobase2[i], ide_irq[i],
                     hd[MAX_IDE_DEVS * i],
		     hd[MAX_IDE_DEVS * i + 1]);

    isa_create_simple(isa_bus, "i8042");
}

static QEMUMachine mips_machine = {
    .name = "mips",
    .desc = "mips r4k platform",
    .init = mips_r4k_init,
};

static void mips_machine_init(void)
{
    qemu_register_machine(&mips_machine);
}

machine_init(mips_machine_init);


text:
@implementation SALoggedInViewController

- (void)viewDidLoad {
	[super viewDidLoad];

	self.usernameLabel.text = self.text;

	self.findFriendsButton.enabled = [ADNLogin sharedInstance].findFriendsAvailable;
	self.inviteFriendsButton.enabled = [ADNLogin sharedInstance].inviteFriendsAvailable;
	self.recommendedUsersButton.enabled = [ADNLogin sharedInstance].recommendedUsersAvailable;
}

- (IBAction)findFriendsClicked:(id)sender {
	[[ADNLogin sharedInstance] launchFindFriends];
}

- (IBAction)inviteFriendsClicked:(id)sender {
	[[ADNLogin sharedInstance] launchInviteFriends];
}

- (IBAction)recommendedUsersClicked:(id)sender {
	[[ADNLogin sharedInstance] launchRecommendedUsers];
}

@end


text:
'''
Management of addresses and names in hosts file.
================================================

The /etc/hosts file can be managed to contain definitions for specific hosts:

.. code-block:: yaml

    salt-master:
      host.present:
        - ip: 192.168.0.42

Or using the "names:" directive, you can put several names for the same IP.
(Do not try one name with space-separated values).

.. code-block:: yaml

    server1:
      host.present:
        - ip: 192.168.0.42
        - names:
          - server1
          - florida

NOTE: changing the name(s) in the present() function does not cause an
update to remove the old entry.
'''

def present(name, ip):  # pylint: disable=C0103
    '''
    Ensures that the named host is present with the given ip

    name
        The host to assign an ip to

    ip
        The ip addr to apply to the host
    '''
    ret = {'name': name,
           'changes': {},
           'result': None,
           'comment': ''}
    if __salt__['hosts.has_pair'](ip, name):
        ret['result'] = True
        ret['comment'] = 'Host {0} already present'.format(name)
        return ret
    if __opts__['test']:
        ret['comment'] = 'Host {0} needs to be added/updated'.format(name)
        return ret
    current_ip = __salt__['hosts.get_ip'](name)
    if current_ip and current_ip != ip:
        __salt__['hosts.rm_host'](current_ip, name)
    if __salt__['hosts.add_host'](ip, name):
        ret['changes'] = {'host': name}
        ret['result'] = True
        ret['comment'] = 'Added host {0}'.format(name)
        return ret
    else:
        ret['result'] = False
        ret['comment'] = 'Failed to set host'
        return ret

def absent(name, ip):  # pylint: disable=C0103
    '''
    Ensure that the named host is absent

    name
        The host to remove

    ip
        The ip addr of the host to remove
    '''
    ret = {'name': name,
           'changes': {},
           'result': None,
           'comment': ''}
    if not __salt__['hosts.has_pair'](ip, name):
        ret['result'] = True
        ret['comment'] = 'Host {0} already absent'.format(name)
        return ret
    if __opts__['test']:
        ret['comment'] = 'Host {0} needs to be removed'.format(name)
        return ret
    if __salt__['hosts.rm_host'](ip, name):
        ret['changes'] = {'host': name}
        ret['result'] = True
        ret['comment'] = 'Removed host {0}'.format(name)
        return ret
    else:
        ret['result'] = False
        ret['comment'] = 'Failed to remove host'
        return ret


text:
using System;
using PCExpert.Core.Domain;
using PCExpert.Core.Tests.Utils;

namespace PCExpert.Core.DataAccess.Tests.Utils
{
	internal abstract class CharacteristicHandler
	{
		protected readonly Random Random = new Random();

		protected CharacteristicHandler(Type characteristicType, Type valueType)
		{
			CharacteristicType = characteristicType;
			CharacteristicValueType = valueType;
		}

		public Type CharacteristicType { get; private set; }
		private Type CharacteristicValueType { get; set; }

		public ComponentCharacteristic CreateRandomCharacteristic(int index)
		{
			return CreateCharacteristic(
				NamesGenerator.CharacteristicName(index),
				ComponentType.PowerSupply)
				.WithPattern("bool pattern");
		}

		public bool CompareValues(CharacteristicValue valueA, CharacteristicValue valueB)
		{
			if (CharacteristicValueType.IsInstanceOfType(valueA)
			    && CharacteristicValueType.IsInstanceOfType(valueB))
				return DoCompareValues(valueA, valueB);
			return false;
		}

		public abstract CharacteristicValue CreateRandomValue(ComponentCharacteristic characteristic);
		protected abstract bool DoCompareValues(CharacteristicValue valueA, CharacteristicValue valueB);
		protected abstract ComponentCharacteristic CreateCharacteristic(string name, ComponentType compType);
	}
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />

  <title>
      Photographs, Landscape and Memory—The Appendix
    </title>
  <meta name="description" content="Appendix co-editor Ben Breen explains the thought process that went into choosing the cover of Issue Two, "Illusions," and shares other photographs-within-ph...">

  <link rel="stylesheet" href="/scripts/fancybox/jquery.fancybox.css">

  <link rel="stylesheet" href="/css/main.css">

  <link rel="canonical" href="http://theappendix.net/posts/2013/04/photographs-landscape-and-memory">
  <link rel="alternate" type="application/rss+xml" title="The Appendix" href="http://theappendix.net/feed.xml">

Issues

Blog

Contributors

About

Photographs, Landscape and Memory

        By Benjamin Breen –

    Published April 15, 2013

"Landscape," British historian Simon Schama writes, "is the work of the mind. Its scenery is built up as much from the strata of memory as from layers of rock."

Living in an old quarter of Lisbon for much of the previous year, I often reflected on this relationship between landscape and memory. The castle I saw on my daily walk to the metro had been seen from the same vantage point by the eyes of Vasco de Gama, Lord Byron and Mussolini. In the earth beneath the castle, visitors can gaze down archeological shafts through the collapsed roofs of the partially excavated Roman city of Olisipo. Deeper still, the bricks, bones, and amphora of the Carthaginians who first built the city, and below that, Neolithic remnants: shards of antler and flint. All testaments to the forgotten lives of individual humans. They had seen the same periwinkle blue estuary of the River Tagus, walked the same granite-strewn hills.

But as the famously cryptic Greek philosopher Heraclitus put it, "We both step and do not step in the same rivers. We are and are not." Landscapes offer an impression of permanence, but they are as much in flux as the contents of our own memories. Regenerated each spring, continually reshaped by earthquakes, exposure, sedimentation, and human activity, a landscape is both constant and constantly changing – just as our own bodies recreate themselves, sloughing off molecules and generating new ones at such a rapid clip that it is estimated that we replace most of our cells every decade or so.

When we at The Appendix started thinking about the theme of "Illusions" for our second issue, we decided to construe the term as broadly as possible. We wanted it to encompass magic tricks, deceit, forgery and lies, but also deeper illusions: illusions of permanence; illusions created by our own memories. For the cover of The Appendix Issue Two, we settled on a photograph-within-a-photograph depicting the same spot of ground in 2012 and circa 1960. The hand in the photo is mine as an adult; the photograph I'm holding shows my father and his sisters as children. Photographs are famously susceptible to trickery and hoaxes. Photography is also, as Susan Sontag noted, a process of metamorphosis that turns a moment in time into a frozen object, transforming "an event or person into something that can be possessed."

In other words, photographs, like landscapes, create an illusion of permanence. The images below are others in the series that gave rise to our Issue Two cover. I took them with an iPhone camera in the summer of 2012 while visiting my deceased grandmother's old house in Scituate, a largely Irish-American seacoast town south of Boston. While going through her family photo albums, I realized that many had been taken in locations that I still recognized decades later. But in contrasting these old photos with their present-day correlates, it was the differences between the two scenes that struck me. The juxtaposition reminded me of the novelist L.P. Hartley's oft-quoted observation that "the past is a foreign country."

Photographs are passports.

    The shingles of my grandmother's house juxtaposed with a photo of it from the 1950s, when it belonged to her mother-in-law, visible in the photo.

      Benjamin Breen, 2012

    This was the only photo I found which had a reliable date: September, 1957.

      Benjamin Breen, 2012

    My grandmother on her way to Mass. The stop sign and boulder offer points of reference bridging the two scenes across time.

      Benjamin Breen, 2012

    The same porch in 2012 and 1990.

      Benjamin Breen, 2012

    My older cousins circa 1982.

      Benjamin Breen, 2012

    A new boat in the 1960s.

      Benjamin Breen, 2012

    A 1940s family photo, with a note on the back: "Get a load of the gams. Boy now I know I'm skinny."

      Benjamin Breen, 2012

      Benjamin Breen, 2012

    I couldn't identify the people in this photo, but another from the same series shows my grandfather, evidently fresh out of the Navy. The post-World War 2 feeling here reminds me a bit of the recent P.T. Anderson film The Master. Note the crumpled beer cans piled in the sand behind them.

      Benjamin Breen, 2012

    This photo, unlike the others, is a mystery. I wasn't able to locate where it was taken, by whom, or why. It could conceivably be a relic of my grandfather's time in Japan immediately after WW2.

      Benjamin Breen, 2012

Recommended Links

The Kinks, "Picture Book"

Simon Schama, _Landscape and Memory_ (Vintage Books, 1996)

**Benjamin Breen** is the editor-in-chief of _The Appendix_ and a PhD candidate in history at the University of Texas at Austin.

      Home

      Issues

      Blog

      Contributors

      Index

      About

      The Appendix was published between 2012 and 2015, released under the CC-BY license, and hosted on GitHub.

      Publication details are available on the colophon.


text:
#if !defined(PSNIP_DEBUG_TRAP_H)
#define PSNIP_DEBUG_TRAP_H

#if !defined(PSNIP_NDEBUG) && defined(NDEBUG) && !defined(PSNIP_DEBUG)
#  define PSNIP_NDEBUG 1
#endif

#if defined(HEDLEY_ALWAYS_INLINE)
#  define PSNIP_DBG__ALWAYS_INLINE HEDLEY_ALWAYS_INLINE
#elif defined(__GNUC__) && (__GNUC__ >= 4)
#  define PSNIP_DBG__ALWAYS_INLINE __attribute__((__always_inline__))
#elif defined(_MSC_VER) && (_MSC_VER >= 1200)
#  define  PSNIP_DBG__ALWAYS_INLINE __forceinline
#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#  define PSNIP_DBG__ALWAYS_INLINE inline
#else
#  define PSNIP_DBG__ALWAYS_INLINE
#endif

#define PSNIP_DBG__FUNCTION static PSNIP_DBG__ALWAYS_INLINE

#if defined(__has_builtin) && !defined(__ibmxl__)
#  if __has_builtin(__builtin_debugtrap)
#    define psnip_trap() __builtin_debugtrap()
#  elif __has_builtin(__debugbreak)
#    define psnip_trap() __debugbreak()
#  endif
#endif
#if !defined(psnip_trap)
#  if defined(_MSC_VER) || defined(__INTEL_COMPILER)
#    define psnip_trap() __debugbreak()
#  elif defined(__ARMCC_VERSION)
#    define psnip_trap() __breakpoint(42)
#  elif defined(__ibmxl__) || defined(__xlC__)
#    include <builtins.h>
#    define psnip_trap() __trap(42)
#  elif defined(__DMC__) && defined(_M_IX86)
     PSNIP_DBG__FUNCTION void psnip_trap(void) { __asm int 3h; }
#  elif defined(__i386__) || defined(__x86_64__)
     PSNIP_DBG__FUNCTION void psnip_trap(void) { __asm__ __volatile__("int $03"); }
#  elif defined(__thumb__)
     PSNIP_DBG__FUNCTION void psnip_trap(void) { __asm__ __volatile__(".inst 0xde01"); }
#  elif defined(__aarch64__)
     PSNIP_DBG__FUNCTION void psnip_trap(void) { __asm__ __volatile__(".inst 0xd4200000"); }
#  elif defined(__arm__)
     PSNIP_DBG__FUNCTION void psnip_trap(void) { __asm__ __volatile__(".inst 0xe7f001f0"); }
#  elif defined (__alpha__) && !defined(__osf__)
     PSNIP_DBG__FUNCTION void psnip_trap(void) { __asm__ __volatile__("bpt"); }
#  elif defined(__STDC_HOSTED__) && (__STDC_HOSTED__ == 0) && defined(__GNUC__)
#    define psnip_trap() __builtin_trap()
#  else
#    include <signal.h>
#    if defined(SIGTRAP)
#      define psnip_trap() raise(SIGTRAP)
#    else
#      define psnip_trap() raise(SIGABRT)
#    endif
#  endif
#endif

#if defined(HEDLEY_LIKELY)
#  define PSNIP_DBG_LIKELY(expr) HEDLEY_LIKELY(expr)
#elif defined(__GNUC__) && (__GNUC__ >= 3)
#  define PSNIP_DBG_LIKELY(expr) __builtin_expect(!!(expr), 1)
#else
#  define PSNIP_DBG_LIKELY(expr) (!!(expr))
#endif

#if !defined(PSNIP_NDEBUG) || (PSNIP_NDEBUG == 0)
#  define psnip_dbg_assert(expr) do { \
    if (!PSNIP_DBG_LIKELY(expr)) { \
      psnip_trap(); \
    } \
  } while (0)
#else
#  define psnip_dbg_assert(expr)
#endif

#endif /* !defined(PSNIP_DEBUG_TRAP_H) */


text:
package com.siyeh.ig.fixes.performance;

import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.IGQuickFixesTestCase;
import com.siyeh.ig.performance.SetReplaceableByEnumSetInspection;

public class SetReplaceableByEnumSetFixTest extends IGQuickFixesTestCase {

  @Override
  protected void setUp() throws Exception {
    super.setUp();
    myFixture.enableInspections(new SetReplaceableByEnumSetInspection());
    myRelativePath = "performance/set_replaceable_with_enum_set";
    myDefaultHint = InspectionGadgetsBundle.message("set.replaceable.by.enum.set.fix.name");
    myFixture.addClass("package java.util;\n" +
                       "\n" +
                       "public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E>\n" +
                       "  implements Cloneable, java.io.Serializable\n" +
                       "{\n" +
                       "  EnumSet(Class<E>elementType, Enum<?>[] universe) {\n" +
                       "    \n" +
                       "  }\n" +
                       "}");
    myFixture.addClass("import java.util.AbstractSet;\n" +
                       "import java.util.Set;\n" +
                       "\n" +
                       "public class HashSet<E>\n" +
                       "  extends AbstractSet<E>\n" +
                       "  implements Set<E>, Cloneable, java.io.Serializable {\n" +
                       "  public HashSet() {\n" +
                       "  }\n" +
                       "}");

  }

  public void testSimple() {
    doTest();
  }

}


text:
cfg_repo="$HOME/Dropbox/git/cfg-$HOST.git"
gcfg_repo="$HOME/Dropbox/git/gcfg.git"
scfg_repo="$HOME/Dropbox/git/scfg-$HOST.git"

function cfg-init() {
  local cfg_gitignore="$HOME/.gitignore"
  (
    set -ex
    test -d "$cfg_repo" || git init --bare "$cfg_repo"
    test -f "$cfg_gitignore" || echo '*' | tee "$cfg_gitignore"
  )
}

function gcfg-init() {
  local gcfg_gitignore="$HOME/.gitignore"
  (
    set -ex
    test -d "$gcfg_repo" || git init --bare "$gcfg_repo"
    test -f "$gcfg_gitignore" || echo '*' | sudo tee "$gcfg_gitignore"
  )
}

function scfg-init() {
  local scfg_gitignore="/.gitignore"
  (
    set -ex
    test -d "$scfg_repo" || git init --bare "$scfg_repo"
    test -f "$scfg_gitignore" || echo '*' | sudo tee "$scfg_gitignore"
  )
}

alias cfg="git --git-dir=$cfg_repo --work-tree=$HOME"
alias gcfg="git --git-dir=$gcfg_repo --work-tree=$HOME"
alias scfg="git --git-dir=$scfg_repo --work-tree=/"
alias dcom='docker-compose'
alias g='git'
alias grep='grep --color=auto'
alias here='xdg-open . 2>/dev/null'
alias ls='ls --color=auto'
alias rmt='find . -type d -empty -exec rmdir "{}" \;'
alias winning='source ~/.zsh/winning.zsh'

for bin in pry rails rake spring rspec zat sidekiq; do
  alias $bin="best-ruby-bin ${bin}"
done

# NeoVim a lot
for vi in v vi vim mvim gvim; do
  eval "alias $vi=nvim"
done


text:
/*! HTML5 Boilerplate v5.0.0 | MIT License | http://h5bp.com/ */

/*
 * What follows is the result of much research on cross-browser styling.
 * Credit left inline and big thanks to Nicolas Gallagher, Jonathan Neal,
 * Kroc Camen, and the H5BP dev community and team.
 */

/* ==========================================================================
   Base styles: opinionated defaults
   ========================================================================== */

html {
    color: #222;
    font-size: 1em;
    line-height: 1.4;
}

/*
 * Remove text-shadow in selection highlight:
 * https://twitter.com/miketaylr/status/12228805301
 *
 * These selection rule sets have to be separate.
 * Customize the background color to match your design.
 */

::-moz-selection {
    background: #b3d4fc;
    text-shadow: none;
}

::selection {
    background: #b3d4fc;
    text-shadow: none;
}

/*
 * A better looking default horizontal rule
 */

hr {
    display: block;
    height: 1px;
    border: 0;
    border-top: 1px solid #ccc;
    margin: 1em 0;
    padding: 0;
}

/*
 * Remove the gap between audio, canvas, iframes,
 * images, videos and the bottom of their containers:
 * https://github.com/h5bp/html5-boilerplate/issues/440
 */

audio,
canvas,
iframe,
img,
svg,
video {
    vertical-align: middle;
}

/*
 * Remove default fieldset styles.
 */

fieldset {
    border: 0;
    margin: 0;
    padding: 0;
}

/*
 * Allow only vertical resizing of textareas.
 */

textarea {
    resize: vertical;
}

/* ==========================================================================
   Browser Upgrade Prompt
   ========================================================================== */

.browserupgrade {
    margin: 0.2em 0;
    background: #ccc;
    color: #000;
    padding: 0.2em 0;
}

/* ==========================================================================
   Author's custom styles
   ========================================================================== */

/*
* Skeleton V2.0.4
* Copyright 2014, Dave Gamache
* www.getskeleton.com
* Free to use under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
* 12/29/2014
*/

/* Table of contents
––––––––––––––––––––––––––––––––––––––––––––––––––
- Grid
- Base Styles
- Typography
- Links
- Buttons
- Spacing
- Utilities
- Clearing
- Custom Classes & IDs
- Media Queries
*/

/* Grid
–––––––––––––––––––––––––––––––––––––––––––––––––– */
.container {
  position: relative;
  width: 100%;
  max-width: 960px;
  margin: 0 auto;
  padding: 0 20px;
  box-sizing: border-box; }
.column,
.columns {
  width: 100%;
  float: left;
  box-sizing: border-box; }

/* For devices larger than 400px */
@media (min-width: 400px) {
  .container {
    width: 85%;
    padding: 0; }
}

/* For devices larger than 550px */
@media (min-width: 550px) {
  .container {
    width: 80%; }
  .column,
  .columns {
    margin-left: 4%; }
  .column:first-child,
  .columns:first-child {
    margin-left: 0; }

  .one.column,
  .one.columns                    { width: 4.66666666667%; }
  .two.columns                    { width: 13.3333333333%; }
  .three.columns                  { width: 22%;            }
  .four.columns                   { width: 30.6666666667%; }
  .five.columns                   { width: 39.3333333333%; }
  .six.columns                    { width: 48%;            }
  .seven.columns                  { width: 56.6666666667%; }
  .eight.columns                  { width: 65.3333333333%; }
  .nine.columns                   { width: 74.0%;          }
  .ten.columns                    { width: 82.6666666667%; }
  .eleven.columns                 { width: 91.3333333333%; }
  .twelve.columns                 { width: 100%; margin-left: 0; }

  .one-third.column               { width: 30.6666666667%; }
  .two-thirds.column              { width: 65.3333333333%; }

  .one-half.column                { width: 48%; }

  /* Offsets */
  .offset-by-one.column,
  .offset-by-one.columns          { margin-left: 8.66666666667%; }
  .offset-by-two.column,
  .offset-by-two.columns          { margin-left: 17.3333333333%; }
  .offset-by-three.column,
  .offset-by-three.columns        { margin-left: 26%;            }
  .offset-by-four.column,
  .offset-by-four.columns         { margin-left: 34.6666666667%; }
  .offset-by-five.column,
  .offset-by-five.columns         { margin-left: 43.3333333333%; }
  .offset-by-six.column,
  .offset-by-six.columns          { margin-left: 52%;            }
  .offset-by-seven.column,
  .offset-by-seven.columns        { margin-left: 60.6666666667%; }
  .offset-by-eight.column,
  .offset-by-eight.columns        { margin-left: 69.3333333333%; }
  .offset-by-nine.column,
  .offset-by-nine.columns         { margin-left: 78.0%;          }
  .offset-by-ten.column,
  .offset-by-ten.columns          { margin-left: 86.6666666667%; }
  .offset-by-eleven.column,
  .offset-by-eleven.columns       { margin-left: 95.3333333333%; }

  .offset-by-one-third.column,
  .offset-by-one-third.columns    { margin-left: 34.6666666667%; }
  .offset-by-two-thirds.column,
  .offset-by-two-thirds.columns   { margin-left: 69.3333333333%; }

  .offset-by-one-half.column,
  .offset-by-one-half.columns     { margin-left: 52%; }

}

/* Base Styles
–––––––––––––––––––––––––––––––––––––––––––––––––– */
/* NOTE
html is set to 62.5% so that all the REM measurements throughout Skeleton
are based on 10px sizing. So basically 1.5rem = 15px :) */
html {
  font-size: 62.5%; }
body {
  background-color:#D2EBE9;
  font-size: 1.5em; /* currently ems cause chrome bug misinterpreting rems on body element */
  line-height: 1.6;
  font-weight: 400;
  font-family: "Raleway", "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif;
  color: #58646D; }

  dt {

  }
  dd {

  }

/* Typography
–––––––––––––––––––––––––––––––––––––––––––––––––– */
h1, h2, h3, h4, h5, h6 {
  margin-top: 0;
  margin-bottom: 2rem;
  font-weight: 300; }
h1 { font-size: 4.0rem; line-height: 1.2;  letter-spacing: -.1rem;}
h2 { font-size: 3.6rem; line-height: 1.25; letter-spacing: -.1rem; }
h3 { font-size: 3.0rem; line-height: 1.3;  letter-spacing: -.1rem; }
h4 { font-size: 2.4rem; line-height: 1.35; letter-spacing: -.08rem; }
h5 { font-size: 1.8rem; line-height: 1.5;  letter-spacing: -.05rem; }
h6 { font-size: 1.5rem; line-height: 1.6;  letter-spacing: 0; }

/* Larger than phablet */
@media (min-width: 550px) {
  h1 { font-size: 5.0rem; }
  h2 { font-size: 4.2rem; }
  h3 { font-size: 3.6rem; }
  h4 { font-size: 3.0rem; }
  h5 { font-size: 2.4rem; }
  h6 { font-size: 1.5rem; }
}

p {
  margin-top: 0; }

/* Links
–––––––––––––––––––––––––––––––––––––––––––––––––– */
a:link, a:visited, a:hover, a:active {
    color:#955351;
    text-decoration: none;
}

/* Buttons
–––––––––––––––––––––––––––––––––––––––––––––––––– */
.button,
button,
input[type="submit"],
input[type="reset"],
input[type="button"] {
  display: inline-block;
  height: 38px;
  padding: 0 30px;
  color: #555;
  text-align: center;
  font-size: 11px;
  font-weight: 600;
  line-height: 38px;
  letter-spacing: .1rem;
  text-transform: uppercase;
  text-decoration: none;
  white-space: nowrap;
  background-color: transparent;
  border-radius: 4px;
  border: 1px solid #bbb;
  cursor: pointer;
  box-sizing: border-box; }
.button:hover,
button:hover,
input[type="submit"]:hover,
input[type="reset"]:hover,
input[type="button"]:hover,
.button:focus,
button:focus,
input[type="submit"]:focus,
input[type="reset"]:focus,
input[type="button"]:focus {
  color: #333;
  border-color: #888;
  outline: 0; }
.button.button-primary,
button.button-primary,
input[type="submit"].button-primary,
input[type="reset"].button-primary,
input[type="button"].button-primary {
  color: #FFF;
  background-color: #007784;
  border-color: #007784; }
.button.button-primary:hover,
button.button-primary:hover,
input[type="submit"].button-primary:hover,
input[type="reset"].button-primary:hover,
input[type="button"].button-primary:hover,
.button.button-primary:focus,
button.button-primary:focus,
input[type="submit"].button-primary:focus,
input[type="reset"].button-primary:focus,
input[type="button"].button-primary:focus {
  color: #FFF;
  background-color: #00B5C8;
  border-color: #00B5C8; }

/* Spacing
–––––––––––––––––––––––––––––––––––––––––––––––––– */
button,
.button {
  margin-bottom: 1rem; }
input,
textarea,
select,
fieldset {
  margin-bottom: 1.5rem; }
pre,
blockquote,
dl,
figure,
table,
p,
ul,
ol,
form {
  margin-bottom: 2.5rem; }

/* Utilities
–––––––––––––––––––––––––––––––––––––––––––––––––– */
.u-full-width {
  width: 100%;
  box-sizing: border-box; }
.u-max-full-width {
  max-width: 100%;
  box-sizing: border-box; }
.u-pull-right {
  float: right; }
.u-pull-left {
  float: left; }

/* Misc
–––––––––––––––––––––––––––––––––––––––––––––––––– */
hr {
  margin-top: 3rem;
  margin-bottom: 3.5rem;
  border-width: 0;
  border-top: 1px solid #E1E1E1; }

/* Clearing
–––––––––––––––––––––––––––––––––––––––––––––––––– */

/* Self Clearing Goodness */
.container:after,
.row:after,
.u-cf {
  content: "";
  display: table;
  clear: both; }

/* Custom Classes & IDs
–––––––––––––––––––––––––––––––––––––––––––––––––– */
.container {margin-top:2.5em;}

.id img {
    max-width:100%;
    border-radius:6em;
    -webkit-box-shadow: 0px 0px 5px 2px rgba(0, 0, 0, 0.25);
    -moz-box-shadow:    0px 0px 5px 2px rgba(0, 0, 0, 0.25);
    box-shadow:         0px 0px 5px 2px rgba(0, 0, 0, 0.25);
    visibility: hidden;
}

dt {margin-top:1.5em;}
dd {margin-bottom:2.5em;}

.display {
    background-color:#FFF;
    margin: 2em auto;
    padding:5em;
    max-width:75em;
    text-align: center;
}

.display img {
    max-width:100%;
}

.display ul {
    list-style-type: none;
    padding-left:0;
}

.display li {
    border-bottom:1px dotted #A3AC99;
    margin-top:1.5em;
}

.display li:last-child {
    border-bottom: none;
}

/* responsive images with Flickr iframe
by Gregory Cazillo cazillo.com/374-responsive-images-with-flickr-iframe.html */
.flickrwrap {position:relative;padding-bottom:56.25%;padding-top:30px;height:0;overflow:hidden;}
.flickrwrap iframe {position:absolute;top:0;left:0;width:100%;height:100%;}

/*
==============================================
CSS3 ANIMATION CHEAT SHEET
==============================================

Made by Justin Aguilar

www.justinaguilar.com/animations/

Questions, comments, concerns, love letters:
justin@justinaguilar.com
==============================================
*/
/*
==============================================
fadeIn
==============================================
*/

.fadeIn{
    animation-name: fadeIn;
    -webkit-animation-name: fadeIn;

    animation-duration: 0.85s;
    -webkit-animation-duration: 0.85s;

    animation-timing-function: ease-in-out;
    -webkit-animation-timing-function: ease-in-out;

    visibility: visible !important;
}

@keyframes fadeIn {
    0% {
        transform: scale(0);
        opacity: 0.0;
    }
    60% {
        transform: scale(1.1);
    }
    80% {
        transform: scale(0.9);
        opacity: 1;
    }
    100% {
        transform: scale(1);
        opacity: 1;
    }
}

@-webkit-keyframes fadeIn {
    0% {
        -webkit-transform: scale(0);
        opacity: 0.0;
    }
    60% {
        -webkit-transform: scale(1.1);
    }
    80% {
        -webkit-transform: scale(0.9);
        opacity: 1;
    }
    100% {
        -webkit-transform: scale(1);
        opacity: 1;
    }
}

/* Media Queries
–––––––––––––––––––––––––––––––––––––––––––––––––– */
/*
Note: The best way to structure the use of media queries is to create the queries
near the relevant code. For example, if you wanted to change the styles for buttons
on small devices, paste the mobile query code up in the buttons section and style it
there.
*/

/* Larger than mobile */
@media (min-width: 400px) {}

/* Larger than phablet (also point when grid becomes active) */
@media (min-width: 550px) {}

/* Larger than tablet */
@media (min-width: 750px) {}

/* Larger than desktop */
@media (min-width: 1000px) {}

/* Larger than Desktop HD */
@media (min-width: 1200px) {}

/* ==========================================================================
   Helper classes
   ========================================================================== */

/*
 * Hide visually and from screen readers:
 * http://juicystudio.com/article/screen-readers-display-none.php
 */

.hidden {
    display: none !important;
    visibility: hidden;
}

/*
 * Hide only visually, but have it available for screen readers:
 * http://snook.ca/archives/html_and_css/hiding-content-for-accessibility
 */

.visuallyhidden {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

/*
 * Extends the .visuallyhidden class to allow the element
 * to be focusable when navigated to via the keyboard:
 * https://www.drupal.org/node/897638
 */

.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
    clip: auto;
    height: auto;
    margin: 0;
    overflow: visible;
    position: static;
    width: auto;
}

/*
 * Hide visually and from screen readers, but maintain layout
 */

.invisible {
    visibility: hidden;
}

/*
 * Clearfix: contain floats
 *
 * For modern browsers
 * 1. The space content is one way to avoid an Opera bug when the
 *    `contenteditable` attribute is included anywhere else in the document.
 *    Otherwise it causes space to appear at the top and bottom of elements
 *    that receive the `clearfix` class.
 * 2. The use of `table` rather than `block` is only necessary if using
 *    `:before` to contain the top-margins of child elements.
 */

.clearfix:before,
.clearfix:after {
    content: " "; /* 1 */
    display: table; /* 2 */
}

.clearfix:after {
    clear: both;
}

/* ==========================================================================
   EXAMPLE Media Queries for Responsive Design.
   These examples override the primary ('mobile first') styles.
   Modify as content requires.
   ========================================================================== */

@media only screen and (min-width: 35em) {
    /* Style adjustments for viewports that meet the condition */
}

@media print,
       (-o-min-device-pixel-ratio: 5/4),
       (-webkit-min-device-pixel-ratio: 1.25),
       (min-resolution: 120dpi) {
    /* Style adjustments for high resolution devices */
}

/* ==========================================================================
   Print styles.
   Inlined to avoid the additional HTTP request:
   http://www.phpied.com/delay-loading-your-print-css/
   ========================================================================== */

@media print {
    *,
    *:before,
    *:after {
        background: transparent !important;
        color: #000 !important; /* Black prints faster:
                                   http://www.sanbeiji.com/archives/953 */
        box-shadow: none !important;
        text-shadow: none !important;
    }

    a,
    a:visited {
        text-decoration: underline;
    }

    a[href]:after {
        content: " (" attr(href) ")";
    }

    abbr[title]:after {
        content: " (" attr(title) ")";
    }

    /*
     * Don't show links that are fragment identifiers,
     * or use the `javascript:` pseudo protocol
     */

    a[href^="#"]:after,
    a[href^="javascript:"]:after {
        content: "";
    }

    pre,
    blockquote {
        border: 1px solid #999;
        page-break-inside: avoid;
    }

    /*
     * Printing Tables:
     * http://css-discuss.incutio.com/wiki/Printing_Tables
     */

    thead {
        display: table-header-group;
    }

    tr,
    img {
        page-break-inside: avoid;
    }

    img {
        max-width: 100% !important;
    }

    p,
    h2,
    h3 {
        orphans: 3;
        widows: 3;
    }

    h2,
    h3 {
        page-break-after: avoid;
    }
}


text:
'use strict';

var app = angular.module('liftApp', [
  'ngCookies',
  'ngResource',
  'ngSanitize',
  'ngRoute',
  'ngProgress',
  'ui.calendar',
  'ui.bootstrap',
]);

app.constant('API_BASE_URL', 'api/v1');

app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
  $routeProvider
      .when('/home', {
        templateUrl: 'views/home.html',
        controller: 'HomeCtrl'
      })
      .when('/medicine', {
        templateUrl: 'views/medicine.html',
        controller: 'MedicineCtrl'
      })
      .when('/testResults', {
        templateUrl: 'views/testResults.html',
        controller: 'TestResultsCtrl'
      })
      .when('/history', {
        templateUrl: 'views/history.html',
        controller: 'HistoryCtrl'
      })
      .when('/meters', {
        templateUrl: 'views/meters.html',
        controller: 'MetersCtrl'
      })
      .when('/clinician', {
        templateUrl: 'views/clinician.html',
        controller: 'ClinicianCtrl'
      })
      .when('/', {
        templateUrl: 'views/login.html',
        controller: 'LoginCtrl'
      })
      .when('/physician', {
        templateUrl: 'views/physician.html',
        controller: 'PhysicianCtrl'
      })
      .when('/supervisor', {
        templateUrl: 'views/physician.html',
        controller: 'SupervisorCtrl'
      })
      .when('/patients/:patient_id', {
        templateUrl: 'views/patients.html',
        controller: 'PatientsCtrl',
        resolve: {
          selectedPatient: ['$route', 'PatientService', function ($route, PatientService) {
            var patientId = $route.current.params.patient_id
            return PatientService.getPatientById(patientId);
          }]
        }
      })
      .when('/patients/:patient_id/charts', {
        templateUrl: 'views/charts.html',
        controller: 'ChartsCtrl',
        resolve: {
          selectedPatient: ['$route', 'PatientService', function ($route, PatientService) {
            var patientId = $route.current.params.patient_id;
            return PatientService.getPatientById(patientId);
          }]
        }
      })
      .otherwise({
        redirectTo: '/'
      });

//  $locationProvider.html5Mode(true);
}]);


text:
<?php
define('lang_Select','Выбрать');
define('lang_Erase','Удалить');
define('lang_Open','Открыть');
define('lang_Confirm_del','Уверены, что хотите удалить этот файл?');
define('lang_All','Все');
define('lang_Files','Файлы');
define('lang_Images','Изображения');
define('lang_Archives','Архивы');
define('lang_Error_Upload','Загружаемый файл превышает допустимый размер.');
define('lang_Error_extension','Недопустимый формат файла.');
define('lang_Upload_file','Загрузить файл');
define('lang_Filters','Фильтр');
define('lang_Videos','Видео');
define('lang_Music','Музыка');
define('lang_New_Folder','New folder');
define('lang_Folder_Created','Папка успешно создана');
define('lang_Existing_Folder','Существующая папка');
define('lang_Confirm_Folder_del','Уверены, что хотите удалить эту папку и все файлы в ней?');
define('lang_Return_Files_List','Вернуться к списку файлов');
define('lang_Preview','Просмотр');
define('lang_Download','Загрузить');
define('lang_Insert_Folder_Name','Введите имя папки:');
define('lang_Root','Корневая папка');
define('lang_Rename','Переименовать');
define('lang_Back','назад');
define('lang_View','Вид');
define('lang_View_list','Список');
define('lang_View_columns_list','Столбцы');
define('lang_View_boxes','Плитка');
define('lang_Toolbar','Панель');
define('lang_Actions','Действия');
define('lang_Rename_existing_file','Файл уже существует');
define('lang_Rename_existing_folder','Папка уже существует');
define('lang_Empty_name','Не заполнено имя');
define('lang_Text_filter','фильтр');
define('lang_Swipe_help','Наведите на имя файла/папки, чтобы увидеть опции');
define('lang_Upload_base','Основная загрузка');
define('lang_Upload_java','JAVA загрузка (для файлов больших размеров)');
define('lang_Upload_java_help',"Если Java-апплет не загружается: 1. Убедитесь, что установлена Java, в противном случае [скачайте] 2. Убедитесь, что фаервол ничего не блокирует");
define('lang_Upload_base_help',"Перетащите файлы в область выше или щелкните по ней мышкой (для современных браузеров) и выберите файл(ы). После завершения загрузки нажмите кнопку «Вернуться к списку файлов».");
define('lang_Type_dir','папка');
define('lang_Type','Тип');
define('lang_Dimension','Разрешение');
define('lang_Size','Размер');
define('lang_Date','Дата');
define('lang_Filename','Имя файла');
define('lang_Operations','Действие');
define('lang_Date_type','y-m-d');
define('lang_OK','OK');
define('lang_Cancel','Отмена');
define('lang_Sorting','Сортировка');
define('lang_Show_url','Показать URL');
define('lang_Extract','Распаковать здесь');
define('lang_File_info','Свойства файла');
define('lang_Edit_image','Редактировать');
define('lang_Duplicate','Duplicate');
?>


text:
salt.modules.nilrt_ip
=====================

.. automodule:: salt.modules.nilrt_ip
    :members:
    :undoc-members:


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

namespace Translator\Tests\Unit\Framework;

use PHPUnit\Framework\TestCase;

class HelperTest extends TestCase
{
    private string $testDir;

    protected function setUp(): void
    {
        $this->testDir = realpath(__DIR__ . '/../..') ?? '';
    }

    public function testGlobRecursive(): void
    {
        $fixturesDir = realpath("{$this->testDir}/Fixtures/Glob");

        $files = glob_recursive("{$fixturesDir}/*.txt", GLOB_BRACE);

        $this->assertEquals([
            '/Fixtures/Glob/file1.txt',
            '/Fixtures/Glob/file2.txt',
            '/Fixtures/Glob/SubDir/SubDirFile1.txt',
            '/Fixtures/Glob/SubDir/SubDirFile2.txt',
            '/Fixtures/Glob/SubDir/SubDir2/SubDir2file1.txt',
            '/Fixtures/Glob/SubDir/SubDir2/SubDir2file2.txt',
        ], $this->replaceDirectorySeparators($this->removeRelativePath($files)));
    }

    /**
     * @param string[] $files
     * @return string[]
     */
    private function removeRelativePath(array $files): array
    {
        return array_map(function (string $file): string {
            return str_replace($this->testDir, '', $file);
        }, $files);
    }

    /**
     * @param string[] $files
     * @return string[]
     */
    private function replaceDirectorySeparators(array $files): array
    {
        return array_map(function (string $file): string {
            return str_replace('\\', '/', $file);
        }, $files);
    }
}


text:
import mapValues from 'lodash/fp/mapValues'
import { browser } from 'webextension-polyfill-ts'
import { RemoteFunctionImplementations } from 'src/util/remote-functions-background'
import TypedEventEmitter from 'typed-emitter'
import { EventEmitter } from 'events'
import { AuthRemoteEvents } from 'src/authentication/background/types'
import { InitialSyncEvents } from '@worldbrain/storex-sync/lib/integration/initial-sync'
import { ContentSharingEvents } from 'src/content-sharing/background/types'
import { PortBasedRPCManager } from 'src/util/rpc/rpc'

export class RpcError extends Error {
    constructor(message) {
        super(message)
        this.name = this.constructor.name
    }
}

export class RemoteError extends Error {
    constructor(message) {
        super(message)
        this.name = this.constructor.name
    }
}

export type RemoteFunctionRole = 'provider' | 'caller'
export type RemoteFunction<
    Role extends RemoteFunctionRole,
    Params,
    Returns = void
> = Role extends 'provider'
    ? (info: { tab: { id: number } }, params: Params) => Promise<Returns>
    : (params: Params) => Promise<Returns>
export type RemotePositionalFunction<
    Role extends RemoteFunctionRole,
    Params extends Array<any>,
    Returns = void
> = Role extends 'provider'
    ? (info: { tab: { id: number } }, ...params: Params) => Promise<Returns>
    : (...params: Params) => Promise<Returns>
export type RemoteFunctionWithExtraArgs<
    Role extends RemoteFunctionRole,
    Params,
    Returns = void
> = Role extends 'provider'
    ? {
          withExtraArgs: true
          function: RemoteFunction<Role, Params, Returns>
      }
    : RemoteFunction<Role, Params, Returns>
export type RemoteFunctionWithoutExtraArgs<
    Role extends RemoteFunctionRole,
    Params,
    Returns = void
> = Role extends 'provider'
    ? {
          withExtraArgs: false
          function: (params: Params) => Promise<Returns>
      }
    : (params: Params) => Promise<Returns>
export function remoteFunctionWithExtraArgs<Params, Returns = void>(
    f: RemoteFunction<'provider', Params, Returns>,
): RemoteFunctionWithExtraArgs<'provider', Params, Returns> {
    return { withExtraArgs: true, function: f }
}
export function remoteFunctionWithoutExtraArgs<Params, Returns = void>(
    f: (params: Params) => Promise<Returns>,
): RemoteFunctionWithoutExtraArgs<'provider', Params, Returns> {
    return { withExtraArgs: false, function: f }
}
export function registerRemoteFunctions<Functions>(
    functions: {
        [Name in keyof Functions]:
            | RemoteFunctionWithExtraArgs<'provider', any, any>
            | RemoteFunctionWithoutExtraArgs<'provider', any, any>
    },
) {
    for (const [name, metadata] of Object.entries(functions)) {
        const typedMetadata = metadata as
            | RemoteFunctionWithExtraArgs<'provider', any, any>
            | RemoteFunctionWithoutExtraArgs<'provider', any, any>
        makeRemotelyCallable(
            { [name]: typedMetadata.function },
            { insertExtraArg: typedMetadata.withExtraArgs },
        )
    }
}

// === Initiating side ===

// The extra options available when calling a remote function
interface RPCOpts {
    tabId?: number
}

// runInBackground and runInTab create a Proxy object that look like the real interface but actually call remote functions
//
// When the Proxy is asked for a property (such as a method)
// return a function that executes the requested method over the RPC interface
//
// Example Usage:
//      interface AnalyticsInterface { trackEvent({}) => any }
//      const analytics = runInBackground<AnalyticsInterface>()
//      analytics.trackEvent(...)

// Runs a remoteFunction in the background script
export function runInBackground<T extends object>(): T {
    return new Proxy<T>({} as T, {
        get(target, property): (...args: any[]) => Promise<any> {
            return async (...args) =>
                rpcConnection.postMessageRequestToExtension(
                    property.toString(),
                    args,
                )
        },
    })
}

// Runs a remoteFunction in the content script on a certain tab
export function runInTab<T extends object>(tabId): T {
    return new Proxy<T>({} as T, {
        get(target, property): any {
            return (...args) =>
                rpcConnection.postMessageRequestToTab(
                    tabId,
                    property.toString(),
                    args,
                )
        },
    })
}

// Runs a remoteFunction in the content script on a certain tab by asking the background script to do so
export function runInTabViaBg<T extends object>(tabId): T {
    return new Proxy<T>({} as T, {
        get(target, property): any {
            return (...args) =>
                rpcConnection.postMessageRequestToTabViaExtension(
                    tabId,
                    property.toString(),
                    args,
                )
        },
    })
}

// @depreciated - Don't call this function directly. Instead use the above typesafe version runInBackground
export function remoteFunction(
    funcName: string,
    { tabId }: { tabId?: number } = {},
): any {
    // console.log(`depreciated: remoteFunction call for: ${funcName}`)
    if (tabId) {
        return (...args) =>
            rpcConnection.postMessageRequestToTab(tabId, funcName, args)
    } else {
        return (...args) =>
            rpcConnection.postMessageRequestToExtension(funcName, args)
    }
}

// === Executing side ===

const remotelyCallableFunctions =
    typeof window !== 'undefined' ? window['remoteFunctions'] || {} : {}
if (typeof window !== 'undefined') {
    window['remoteFunctions'] = remotelyCallableFunctions
}

export function setupRemoteFunctionsImplementations<T>(
    implementations: RemoteFunctionImplementations<'provider'>,
): void {
    for (const [group, functions] of Object.entries(implementations)) {
        makeRemotelyCallableType<typeof functions>(functions)
    }
}

// Register a function to allow remote scripts to call it.
// Arguments:
// - functions (required):
//     An object with a {functionName: function} mapping.
//     Each function will be callable with the given name.
// - options (optional): {
//       insertExtraArg:
//           If truthy, each executed function also receives, as its first
//           argument before the arguments it was invoked with, an object with
//           the details of the tab that sent the message.
//   }
export function makeRemotelyCallableType<T = never>(
    functions: { [P in keyof T]: T[P] },
    { insertExtraArg = false } = {},
) {
    return makeRemotelyCallable(functions, { insertExtraArg })
}
// @Depreciated to call this directly. Should use the above typesafe version
export function makeRemotelyCallable<T>(
    functions: { [P in keyof T]: T[P] },
    { insertExtraArg = false } = {},
) {
    // Every function is passed an extra argument with sender information,
    // so remove this from the call if this was not desired.
    if (!insertExtraArg) {
        // Replace each func with...
        // @ts-ignore
        const wrapFunctions = mapValues((func) =>
            // ...a function that calls func, but hides the inserted argument.
            // @ts-ignore
            (extraArg, ...args) => func(...args),
        )
        // @ts-ignore
        functions = wrapFunctions(functions)
    }

    for (const functionName of Object.keys(functions)) {
        if (remotelyCallableFunctions.hasOwnProperty(functionName)) {
            const error = `RPC function with name ${functionName} has already been registered `
            console.warn(error)
        }
    }
    // Add the functions to our global repetoir.
    Object.assign(remotelyCallableFunctions, functions)
    // console.log('assigned to remotelyCallableFunctions this new functions', {
    //     functions,
    // })
}

export class RemoteFunctionRegistry {
    registerRemotelyCallable(functions, { insertExtraArg = false } = {}) {
        makeRemotelyCallable(functions, { insertExtraArg })
    }
}

export function fakeRemoteFunctions(functions: {
    [name: string]: (...args) => any
}) {
    return (name) => {
        if (!functions[name]) {
            throw new Error(
                `Tried to call fake remote function '${name}' for which no implementation was provided`,
            )
        }
        return (...args) => {
            return Promise.resolve(functions[name](...args))
        }
    }
}

export interface RemoteEventEmitter<T> {
    emit: (eventName: keyof T, data: any) => Promise<any>
}
const __REMOTE_EVENT__ = '__REMOTE_EVENT__'
const __REMOTE_EVENT_TYPE__ = '__REMOTE_EVENT_TYPE__'
const __REMOTE_EVENT_NAME__ = '__REMOTE_EVENT_NAME__'

// Sending Side, (e.g. background script)
export function remoteEventEmitter<T>(
    eventType: string,
    { broadcastToTabs = false } = {},
): RemoteEventEmitter<T> {
    const message = {
        __REMOTE_EVENT__,
        __REMOTE_EVENT_TYPE__: eventType,
    }

    if (broadcastToTabs) {
        return {
            emit: async (eventName, data) => {
                const tabs = (await browser.tabs.query({})) ?? []
                for (const { id: tabId } of tabs) {
                    browser.tabs.sendMessage(tabId, {
                        ...message,
                        __REMOTE_EVENT_NAME__: eventName,
                        data,
                    })
                }
            },
        }
    }

    return {
        emit: async (eventName, data) =>
            browser.runtime.sendMessage({
                ...message,
                __REMOTE_EVENT_NAME__: eventName,
                data,
            }),
    }
}

// Receiving Side (e.g. content script, options page, etc)
const remoteEventEmitters: RemoteEventEmitters = {} as RemoteEventEmitters
type RemoteEventEmitters = {
    [K in keyof RemoteEvents]?: TypedRemoteEventEmitter<K>
}
export type TypedRemoteEventEmitter<
    T extends keyof RemoteEvents
> = TypedEventEmitter<RemoteEvents[T]>

// Statically defined types for now, move this to a registry
interface RemoteEvents {
    auth: AuthRemoteEvents
    sync: InitialSyncEvents
    contentSharing: ContentSharingEvents
}

function registerRemoteEventForwarder() {
    if (browser.runtime.onMessage.hasListener(remoteEventForwarder)) {
        return
    }
    browser.runtime.onMessage.addListener(remoteEventForwarder)
}

const remoteEventForwarder = (message, _) => {
    if (message == null || message[__REMOTE_EVENT__] !== __REMOTE_EVENT__) {
        return
    }

    const emitterType = message[__REMOTE_EVENT_TYPE__]
    const emitter = remoteEventEmitters[emitterType]

    if (emitter == null) {
        return
    }

    emitter.emit(message[__REMOTE_EVENT_NAME__], message.data)
}

export function getRemoteEventEmitter<EventType extends keyof RemoteEvents>(
    eventType: EventType,
): RemoteEventEmitters[EventType] {
    const existingEmitter = remoteEventEmitters[eventType]
    if (existingEmitter) {
        return existingEmitter
    }

    const newEmitter = new EventEmitter() as any
    remoteEventEmitters[eventType] = newEmitter
    registerRemoteEventForwarder()
    return newEmitter
}

// Containing the evil globals here
let rpcConnection: PortBasedRPCManager
export const setupRpcConnection = (options: {
    sideName: string
    role: 'content' | 'background'
}) => {
    rpcConnection = new PortBasedRPCManager(
        options.sideName,
        (name) => remotelyCallableFunctions[name],
        browser.runtime.connect,
        browser.runtime.onConnect,
    )

    if (options.role === 'content') {
        rpcConnection.registerConnectionToBackground()
    }

    if (options.role === 'background') {
        rpcConnection.registerListenerForIncomingConnections()
    }

    return rpcConnection
}