text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>systems.manifold</groupId>
    <artifactId>manifold-parent</artifactId>
    <version>2022.1.27-SNAPSHOT</version>
  </parent>

  <artifactId>manifold-deps-parent</artifactId>
  <packaging>pom</packaging>

  <name>Manifold :: Dependencies Parent</name>
  <description>
    Manifold is a Java compiler plugin, its features include Metaprogramming, Properties, Extension
    Methods, Operator Overloading, Templates, a Preprocessor, and more.
  </description>
  <url>http://manifold.systems/</url>

  <modules>
    <module>manifold-tuple</module>
    <module>manifold-tuple-rt</module>
    <module>manifold-tuple-test</module>
    <module>manifold-collections</module>
    <module>manifold-collections-test</module>
    <module>manifold-csv</module>
    <module>manifold-csv-rt</module>
    <module>manifold-csv-test</module>
    <module>manifold-darkj</module>
    <module>manifold-darkj-test</module>
    <module>manifold-highjump</module>
    <module>manifold-highjump-test</module>
    <module>manifold-exceptions</module>
    <module>manifold-exceptions-test</module>
    <module>manifold-ext</module>
    <module>manifold-ext-rt</module>
    <module>manifold-ext-test</module>
    <module>manifold-ext-middle-test</module>
    <module>manifold-ext-producer-sample</module>
    <module>manifold-ext-producer-sample-test</module>
    <module>manifold-graphql</module>
    <module>manifold-graphql-rt</module>
    <module>manifold-graphql-test</module>
    <module>manifold-io</module>
    <module>manifold-io-test</module>
    <module>manifold-image</module>
    <module>manifold-image-test</module>
    <module>manifold-js</module>
    <module>manifold-js-rt</module>
    <module>manifold-js-test</module>
    <module>manifold-json</module>
    <module>manifold-json-rt</module>
    <module>manifold-json-test</module>
    <module>manifold-preprocessor</module>
    <module>manifold-preprocessor-android-syms</module>
    <module>manifold-preprocessor-test</module>
    <module>manifold-props</module>
    <module>manifold-props-rt</module>
    <module>manifold-props-middle-test</module>
    <module>manifold-props-test</module>
    <module>manifold-properties</module>
    <module>manifold-properties-test</module>
    <module>manifold-science</module>
    <module>manifold-science-test</module>
    <module>manifold-strings</module>
    <module>manifold-strings-test</module>
    <module>manifold-strings-test-excl</module>
    <module>manifold-templates</module>
    <module>manifold-templates-rt</module>
    <module>manifold-templates-test</module>
    <module>manifold-test</module>
    <module>manifold-text</module>
    <module>manifold-text-test</module>
    <module>manifold-xml</module>
    <module>manifold-xml-rt</module>
    <module>manifold-xml-test</module>
    <module>manifold-yaml</module>
    <module>manifold-yaml-rt</module>
    <module>manifold-yaml-test</module>
  </modules>

  <dependencies>
    <dependency>
      <groupId>systems.manifold</groupId>
      <artifactId>manifold-javadoc-agent</artifactId>
      <scope>provided</scope>
      <optional>true</optional>
      <version>2022.1.27-SNAPSHOT</version>
    </dependency>
  </dependencies>

  <profiles>
    <profile>
      <id>release</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-javadoc-plugin</artifactId>
            <version>3.0.1</version>
            <configuration>
              <encoding>UTF-8</encoding>
              <additionalOptions>
                <additionalOption>-Xdoclint:none</additionalOption>
              </additionalOptions>
              <additionalJOptions>
                <additionalJOption>-J-javaagent:${systems.manifold:manifold-javadoc-agent:jar}</additionalJOption>
<!--                <additionalJOption>-J-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005</additionalJOption>-->
              </additionalJOptions>
              <!-- The manifold.science module uses binding expressions which don't parse in the javadoc parser at the moment -->
<!--              <excludePackageNames>manifold.science.measures;manifold.science.util;manifold.science.vector;manifold.ext.props.middle</excludePackageNames>-->

            </configuration>
            <executions>
              <execution>
                <id>attach-javadocs</id>
                <goals>
                  <goal>jar</goal>
                </goals>
              </execution>
            </executions>
          </plugin>

        </plugins>
      </build>
    </profile>
  </profiles>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <configuration>
            <compilerArgs>
              <!-- Do not enable bootstrapping here, we don't want to force Manifold runtime on projects -->
              <arg>-Xplugin:Manifold no-bootstrap</arg>
              <!--<arg>--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED</arg>-->
              <!--<arg>--add-exports=jdk.compiler/com.sun.tools.javac.jvm=ALL-UNNAMED</arg>-->
              <!--<arg>--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED</arg>-->
              <!--<arg>--add-exports=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED</arg>-->
              <!--<arg>--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED</arg>-->
              <!--<arg>--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED</arg>-->
              <!--<arg>--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED</arg>-->
              <!--<arg>--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED</arg>-->
              <!--<arg>--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED</arg>-->
              <!--<arg>--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED</arg>-->
              <!--<arg>--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED</arg>-->
              <!--<arg>--add-exports=java.base/jdk.internal.loader=ALL-UNNAMED</arg>-->
            </compilerArgs>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>

</project>


text:
import { combineReducers } from 'redux'
import userReducer from '../routes/Auth/modules/login'
import { reducer as formReducer } from 'redux-form'
import { routerReducer } from 'react-router-redux'

export const makeRootReducer = (asyncReducers) => {
  return combineReducers({
    user: userReducer,
    form: formReducer,
    routing: routerReducer,
    ...asyncReducers
  })
}

export const injectReducer = (store, { key, reducer }) => {
  store.asyncReducers[key] = reducer
  store.replaceReducer(makeRootReducer(store.asyncReducers))
}

export default makeRootReducer

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Discord;
using Fclp.Internals.Extensions;
using SkillBotv2.Extensions;
using SkillBotv2.Util;

namespace SkillBotv2.Command
{
    class CommandImagify : ICommand
    {
        public async Task<object> ParseArguments(string[] args, Message message)
        {
            return ulong.Parse(args.ElementAtOrDefault(0, "0"));
        }

        public async Task Execute(object arguments, Message m)
        {
            ulong messageId = (ulong) arguments;
            Message table;
            string parsedText;
            Stopwatch find = new Stopwatch(),
                      convert = new Stopwatch(),
                      upload = new Stopwatch();

            // Getting message
            table = messageId == 0
                ? find.TimeTask(() => m.Channel.Messages.OrderByDescending(o => o.Id).FirstOrDefault(o => o.Text.Matches(@"\A```(.*?)```\z", RegexOptions.Singleline)))
                : find.TimeTask(() => m.Channel.GetMessage(messageId));

            // Chekcing if message was found
            if (table?.Text == null || (parsedText = Regex.Match(table.Text, @"\A```(.*?)```\z", RegexOptions.Singleline).Groups[1].Value) == null)
                throw new Exception("Message could not be found.");

            var img = convert.TimeTask(() => ImageUtil.ToImage(parsedText));
            var link = await upload.TimeTaskAsync(async () => await ImageUtil.PostToImgur(img));
            await m.Channel.SendMessage(link + "\n" +
                                        $"**Find Message**: {find.ElapsedMilliseconds}ms | " +
                                        $"**Convert Text**: {convert.ElapsedMilliseconds}ms | " +
                                        $"**Upload Image**: {upload.ElapsedMilliseconds}ms");
        }
    }
}


text:
: '
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you 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.
'

echo "Starting Myriad..."

if [ ! -z $ALTERNATE_HADOOP_URL ]; then
  echo "OVERIDING URL"
  exec /install-yarn.sh $ALTERNATE_HADOOP_URL
  unset $ALTERNATE_HADOOP_URL
fi

export MYRIAD_CONFIG_FILE="/myriad-conf/myriad-config-default.yml"
export YARN_SITE="/myriad-conf/yarn-site.xml"

# modify the core-site.xml file within the docker
sed -i.bak "s=<configuration>=<configuration>\<property>\<name>fs\.default\.name\</name>\<value>hdfs://${HADOOP_NAMENODE}\</value>\</property>=g" /usr/local/hadoop/etc/hadoop/core-site.xml

# Copy the configs over
cp /myriad-conf/* /usr/local/hadoop/etc/hadoop/

# Ensure myriad conf file is present
if [ ! -f $MYRIAD_CONFIG_FILE ]; then
    echo "[FATAL] Myriad config not found! - ${MYRIAD_CONFIG_FILE}"
    exit 1
fi
if [ ! -f $YARN_SITE ]; then
    echo "[FATAL] yarn-site.xml config not found! - ${YARN_SITE}"
    exit 1
fi

if [ -z $HADOOP_NAMENODE ]; then
    echo "[FATAL] HADOOP_NAMENODE env variable not set!"
    exit 1
fi

#su - $HADOOP_USER /usr/local/hadoop/bin/yarn resourcemanager
/usr/local/hadoop/bin/yarn resourcemanager


text:
describe Facts::Freebsd::Ruby::Version do
  describe '#call_the_resolver' do
    subject(:fact) { Facts::Freebsd::Ruby::Version.new }

    let(:value) { '2.4.5' }

    before do
      allow(Facter::Resolvers::Ruby).to receive(:resolve).with(:version).and_return(value)
    end

    it 'calls Facter::Resolvers::Ruby' do
      fact.call_the_resolver
      expect(Facter::Resolvers::Ruby).to have_received(:resolve).with(:version)
    end

    it 'returns ruby version fact' do
      expect(fact.call_the_resolver)
        .to be_an_instance_of(Array)
        .and contain_exactly(an_object_having_attributes(name: 'ruby.version', value: value),
                             an_object_having_attributes(name: 'rubyversion', value: value, type: :legacy))
    end
  end
end


text:
package plugin // import "github.com/docker/infrakit/pkg/plugin"

import (
	"fmt"
	"path/filepath"
	"strings"
)

// Names is a list of Names
type Names []Name

// NamesFrom returns a slice of Names from a string list
func NamesFrom(list []string) Names {
	n := []Name{}
	for _, v := range list {
		n = append(n, Name(v))
	}
	return Names(n)
}

// Name is a reference to the plugin.  Places where it appears include JSON files as type of field `Plugin`.
type Name string

// Zero returns true if the name is zero value
func (n Name) Zero() bool {
	return len(n) == 0
}

// NameFrom creates a name from the parts
func NameFrom(lookup, sub string) Name {
	if sub != "" {
		return Name(strings.Join([]string{lookup, sub}, "/"))
	}
	return Name(lookup)
}

// Rel computes the relative form, assuming the receiver is the base path
// so that Join(other, n.Rel(other)) == other.  If it's not relative at all, then the receiver is returned
func (n Name) Rel(other Name) Name {
	rel, err := filepath.Rel(other.String(), n.String())
	if err == nil {
		if rel == "." {
			return n
		}
		return Name(rel)
	}
	return n
}

// Lookup returns the lookup portion of the name
func (n Name) Lookup() string {
	lookup, _ := n.GetLookupAndType()
	return lookup
}

// LookupOnly returns the trailing slash form e.g. us-east/
func (n Name) LookupOnly() Name {
	lookup, _ := n.GetLookupAndType()
	return Name(string(lookup + "/"))
}

// WithType returns a new name with the same lookup but a different type
func (n Name) WithType(t interface{}) Name {
	return Name(fmt.Sprintf("%v/%v", n.Lookup(), t))
}

// Sub is the same as WithType
func (n Name) Sub(v string) Name {
	return n.WithType(v)
}

// Equal returns true if the other name is the same
func (n Name) Equal(other Name) bool {
	return string(n) == string(other)
}

// HasType returns true if the name is of the form lookup/type
func (n Name) HasType() bool {
	_, s := n.GetLookupAndType()
	return s != ""
}

// Type returns the second portion of the name 'ec2-instance' in 'aws/ec2-instance'
func (n Name) Type() string {
	_, t := n.GetLookupAndType()
	return t
}

// IsEmpty returns true if the name is an empty string
func (n Name) IsEmpty() bool {
	return string(n) == ""
}

// String returns the string form
func (n Name) String() string {
	return string(n)
}

// GetLookupAndType returns the plugin name for lookup and sub-type supported by the plugin.
// The name follows a microformat of $plugin[/$subtype] where $plugin is used for the discovery / lookup by name.
// The $subtype is used for the Type parameter in the RPC requests.
// Example: instance-file/json means lookup socket file 'instance-file' and the type is 'json'.
func (n Name) GetLookupAndType() (string, string) {
	name := string(n)
	if first := strings.Index(name, "/"); first >= 0 {
		return name[0:first], name[first+1:]
	}
	return name, ""
}

// MarshalJSON implements the JSON marshaler interface
func (n Name) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf(`"%s"`, n.String())), nil
}

// UnmarshalJSON implements the JSON unmarshaler interface
func (n *Name) UnmarshalJSON(data []byte) error {
	str := string(data)
	start := strings.Index(str, "\"")
	last := strings.LastIndex(str, "\"")
	if start == 0 && last == len(str)-1 {
		str = str[start+1 : last]
	} else {
		return fmt.Errorf("bad-format-for-name:%v", string(data))
	}
	*n = Name(str)
	return nil
}


text:
Sim.WebGLDetector = {

	detectWebGL : function()
	{
		var canvas = document.createElement("canvas");

	    var gl = null;
	    var msg = "Your browser does not support WebGL, " +
	    	"or it is not enabled by default.";
	    try
	    {
	        gl = canvas.getContext("experimental-webgl");
	    }
	    catch (e)
	    {
	        msg = "Error creating WebGL Context!: " + e.toString();
	    }

	    if (!gl)
	    {
	    	throw new Error(msg);
	    }
	},

};


text:
require(["angular"], function(angular) {
});


text:
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;

namespace Ds3.Calls
{
    public class VerifyAllTapesSpectraS3Request : Ds3Request
    {

        private Priority? _taskPriority;
        public Priority? TaskPriority
        {
            get { return _taskPriority; }
            set { WithTaskPriority(value); }
        }

        public VerifyAllTapesSpectraS3Request WithTaskPriority(Priority? taskPriority)
        {
            this._taskPriority = taskPriority;
            if (taskPriority != null)
            {
                this.QueryParams.Add("task_priority", taskPriority.ToString());
            }
            else
            {
                this.QueryParams.Remove("task_priority");
            }
            return this;
        }

        public VerifyAllTapesSpectraS3Request()
        {
            this.QueryParams.Add("operation", "verify");

        }

        internal override HttpVerb Verb
        {
            get
            {
                return HttpVerb.PUT;
            }
        }

        internal override string Path
        {
            get
            {
                return "/_rest_/tape";
            }
        }
    }
}


text:
__precompile__(true)
#=
TAGS:
	#WANTCONST, HIDEWARN_0.7
=#

module MDDatasets

import Base: values
using Statistics

#==Suggested scalar data types
	-Use concrete types of the largest size natively supported by processor
   -Eventually should move to 128-bit values, etc.==#
const DataFloat = Float64
const DataInt = Int64
const DataComplex = Complex{Float64}
#==NOTES:
Don't use Int.  If this is like c, "Int" represents the "native" integer
size/type.  That might not be the same as the largest integer that can be
handled with reasonable efficiency

No reason to have an alias for Bool.  Probably best to keep the default
representation.==#

#Type used to dispatch on a symbol & minimize namespace pollution:
#-------------------------------------------------------------------------------
struct DS{Symbol}; end; #Dispatchable symbol
DS(v::Symbol) = DS{v}()

#-------------------------------------------------------------------------------
include("functions.jl")
include("math.jl")
include("arrays.jl")
include("base.jl")
include("datahr.jl")
include("datars.jl")
include("datasetop.jl")
include("meas_cross.jl")
include("meas_cksignals.jl")
include("meas_binsignals.jl")
include("broadcast.jl")
include("broadcast_datahr.jl")
include("broadcast_datars.jl")
include("datasetop_reg.jl")
include("measinterface.jl")
include("show.jl")
include("doc.jl")

#==TODO: Watch out for value() being exported by multiple modules...
Maybe it can be defined in "Units"
==#

#Data types:
#-------------------------------------------------------------------------------
export DataFloat, DataInt, DataComplex
export DataMD #Prefered abstraction for high-level functions
export PSweep #Parameter sweep
export Index #A way to identify parameters as array indicies
export DataFloat, DataInt, DataComplex, DataF1 #Leaf data types
export DataHR, DataRS

#Support functions:
#-------------------------------------------------------------------------------
export ensure

#Scalar operations:
#-------------------------------------------------------------------------------
export sanitize #Clamp down infinite values & substitute NaNs

#Accessor functions:
#-------------------------------------------------------------------------------
export value #High-collision WARNING: other modules probably want to export "value".
export sweep #Access values from a particular parameter sweep.
export sweeps #Get the list of parameter sweeps in DataHR.
#Base.ndims #Return number of dimensions (parametric sweeps).
export dimension #Returns the dimension corresponding to the given parameter name.
export subscripts #Provides subscripts iterator to access each element in DataHR.
export getsubarray
export coordinates #Get parameter sweep coordinates corresponding to given subscripts.
export paramlist #Return a list of parameter values being swept.
export parameter #Get parameter values for a particular sweep.

#Basic dataset operations:
#-------------------------------------------------------------------------------
@doc "Gets a dataset with all the x-values as the y-values" xval
export xval #Gets a dataset with all the x-values as the y-values
#value(ds, x=value) (already exported): get y-value @ given x.
export clip #clips a dataset within an xrange
export sample #Samples a dataset
export delta, xshift, xscale
export yvsx
export deriv, iinteg #derivative, definite integral, indefinite integral
export integ, xmin, xmax

#Cross operations:
#-------------------------------------------------------------------------------
#==API
NOTE: using "{Event}" for type stability (I hope)

Returns x-values of d1 (up-to nmax) when d1 crosses 0 (nmax=0: get all crossings):
xcross(d1, nmax; xstart, allow::CrossType)
xcross(Event, d1, nmax; xstart, allow::CrossType)

Returns y-values of d2 (up-to nmax) when when d1 crosses d2 (nmax=0: get all crossings):
ycross(d1, d2, nmax; xstart, allow::CrossType)
ycross(Event, d1, d2, nmax; xstart, allow::CrossType)

Returns scalar x-value of d1 on n-th zero-crossing:
xcross1(d1; n, xstart, allow::CrossType)
xcross1(Event, d1; n, xstart, allow::CrossType)

Returns scalar y-value of d1 on n-th crossing of d1 & d2:
ycross1(d1, d2; n, xstart, allow::CrossType)
ycross1(Event, d1, d2; n, xstart, allow::CrossType)

Resultant x-values are x-values of d1 @ crossings:
(x/y)cross

Resultant x-values corresponds to number of current crossing event (1, 2, ..., n):
(x/y)cross{Event}
==#
export Event #Identifies result as having event count in x-axis
export CrossType #To filter out unwanted crossings
export xcross, xcross1 #Measure x @ crossing events
export ycross, ycross1 #Measure y @ crossing events
export measdelay #Measure delay between crossing events of two signals
export measperiod, measfreq, measduty, measckstats
export measck2q, measskew
export measrise, measfall

export meas #Use meas(:MEASTYPE, ...) to minimize namespace pollution.
#==Sample usage:
TODO: Deprecate direct call of x/ycross/1 & measdelay
ON CONDITION: Only if this interface does not mess up type stability.
meas(:xcross, Event, d1)
==#

#==Initialization
===============================================================================#
function __init__()
	show(:HACK_SHOWTOUNFREEZE) #Not sure why show unfreezes dependent modules (those using this one)
	println() #newline
	return
end

end #MDDatasets

#Last line


text:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="concept" name="DC.Type" />
<meta name="DC.Title" content="XA and the Network Server" />
<meta content="XA, and Network Server" name="DC.subject" />
<meta content="XA, and Network Server" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="cadminapps59125.html" />
<meta scheme="URI" name="DC.Relation" content="cadminappsthenetworkserverandjvms.html" />
<meta scheme="URI" name="DC.Relation" content="tadminappschangingyourclasspath.html" />
<meta scheme="URI" name="DC.Relation" content="tadmincbdjhhfd.html" />
<meta scheme="URI" name="DC.Relation" content="tadminconfigshuttingdownthenetworkserver.html" />
<meta scheme="URI" name="DC.Relation" content="tadminconfigsysteminformation.html" />
<meta scheme="URI" name="DC.Relation" content="cadminappsclient.html" />
<meta scheme="URI" name="DC.Relation" content="cadminnsdatasources.html" />
<meta scheme="URI" name="DC.Relation" content="cadminappsusingthederbytoolswiththene.html" />
<meta scheme="URI" name="DC.Relation" content="cadminapps.html" />
<meta scheme="URI" name="DC.Relation" content="tadminappssettingportnumbers.html" />
<meta scheme="URI" name="DC.Relation" content="cadminappsxawthdriver.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="cadminapps811478" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>XA and the Network Server</title>

XA and the Network Server

Both the Derby embedded
driver and the Network Server provide XA support. The Network Server provides
DRDA level 7 support. DRDA clients that support XAMGR, such as the
Derby network client, can send XA requests to
the Network Server.

Using XA with the network client driver

Parent topic: Using the Network Server with preexisting Derby applications

Related concepts

The Network Server and JVMs

Accessing the Network Server by using the network client driver

Accessing the Network Server by using a DataSource object

Using the Derby tools with the Network Server

Differences between running Derby in embedded mode and using the Network Server

Related tasks

Installing required jar files and adding them to the classpath

Starting the Network Server

Shutting down the Network Server

Obtaining system information

Setting port numbers


text:
<?php
/**
 * @file
 */

namespace BackupMigrate\Core\Tests\Main;

use BackupMigrate\Core\Config\Config;
use BackupMigrate\Core\Main\BackupMigrateInterface;
use BackupMigrate\Core\Plugin\PluginManager;
use BackupMigrate\Core\Main\BackupMigrate;
use BackupMigrate\Core\Plugin\PluginManagerInterface;
use BackupMigrate\Core\Tests\File\TempFileConsumerTestTrait;
use \BackupMigrate\Core\File\ReadableStreamBackupFile;

/**
 * Class BackupMigrateTest
 * @package BackupMigrate\Core\Tests\Services
 */
class BackupMigrateTest extends \PHPUnit_Framework_TestCase {
  use TempFileConsumerTestTrait;

  /**
   * @var PluginManagerInterface
   */
  protected $plugins;

  /**
   * @var BackupMigrate
   */
  protected $bam;

  public function setUp() {
    $conf = new Config(
      [
        'test' => ['foo' => 'bar',],
        'test2' => ['foo' => 'baz', 'hello' => 'world']
      ]
    );
    $this->_setUpFiles(['file.txt' => 'Hello, World!']);

    $this->bam = new BackupMigrate();
    $this->bam->setConfig($conf);
  }

  /**
   * Test backing up from a source to a destination.
   */
  public function testAddPlugin() {
    // Create a stub for the plugin class.
    $plugin = $this->getMockBuilder('\BackupMigrate\Core\Plugin\PluginBase')
      ->getMock();
    $plugin2 = $this->getMockBuilder('\BackupMigrate\Core\Plugin\PluginBase')
      ->getMock();

    $this->bam->plugins()->add('test', $plugin);
    $this->bam->plugins()->add('test2', $plugin2);

    $this->assertEquals($plugin, $this->bam->plugins()->get('test'));
    $this->assertEquals($plugin2, $this->bam->plugins()->get('test2'));

    $this->assertEquals(['test' => $plugin, 'test2' => $plugin2], $this->bam->plugins()->getAll());

  }

  /**
   * Test backing up from a source to a destination.
   */
  public function testBackup() {
    $file = new ReadableStreamBackupFile('vfs://root/file.txt');

    $source = $this->getMockBuilder('\BackupMigrate\Core\Source\SourceBase')
      ->setMethods(['exportToFile', 'importFromFile'])
      ->getMock();
    $source->method('exportToFile')->willReturn($file);

    $plugin = $this->getMockBuilder('\BackupMigrate\Core\Plugin\PluginBase')
      ->setMethods(['afterBackup', 'supportedOps'])
      ->getMock();
    $plugin->method('supportedOps')->willReturn(
      ['afterBackup' => ['weight' => 100]]
    );
    $plugin->method('afterBackup')->willReturn($file);

    $destination = $this->getMockBuilder('\BackupMigrate\Core\Destination\DirectoryDestination')
      ->setMethods(['saveFile', 'checkWritable'])
      ->getMock();
    $destination->method('checkWritable')->willReturn(true);

    $destination->expects($this->once())->method('checkWritable');
    $destination->expects($this->once())->method('saveFile')->with(
      $this->equalTo($file)
    );
    $destination2 = $this->getMockBuilder('\BackupMigrate\Core\Destination\DirectoryDestination')
      ->setMethods(['saveFile'])
      ->getMock();

    $destination2->expects($this->never())->method('saveFile')->with(
      $this->equalTo($file)
    );

    $plugin->expects($this->once())->method('afterBackup')->with(
      $this->equalTo($file)
    );

    $this->bam->sources()->add('source', $source);
    $this->bam->destinations()->add('destination', $destination);
    $this->bam->destinations()->add('destination2', $destination2);
    $this->bam->plugins()->add('test', $plugin);

    $this->bam->backup('source', 'destination');

  }

  /**
   * Test backing up from a source to a destination.
   */
  public function testBackupMultiple() {
    $file = new ReadableStreamBackupFile('vfs://root/file.txt');

    $source = $this->getMockBuilder('\BackupMigrate\Core\Source\SourceBase')
      ->setMethods(['exportToFile', 'importFromFile'])
      ->getMock();
    $source->method('exportToFile')->willReturn($file);

    $plugin = $this->getMockBuilder('\BackupMigrate\Core\Plugin\PluginBase')
      ->setMethods(['afterBackup', 'supportedOps'])
      ->getMock();
    $plugin->method('supportedOps')->willReturn(
      ['afterBackup' => ['weight' => 100]]
    );
    $plugin->method('afterBackup')->willReturn($file);

    $destination = $this->getMockBuilder('\BackupMigrate\Core\Destination\DirectoryDestination')
      ->setMethods(['saveFile', 'checkWritable'])
      ->getMock();
    $destination->method('checkWritable')->willReturn(true);

    $destination->expects($this->once())->method('checkWritable');
    $destination->expects($this->once())->method('saveFile')->with(
      $this->equalTo($file)
    );
    $destination2 = $this->getMockBuilder('\BackupMigrate\Core\Destination\DirectoryDestination')
      ->setMethods(['saveFile', 'checkWritable'])
      ->getMock();
    $destination2->method('checkWritable')->willReturn(true);

    $destination2->expects($this->once())->method('checkWritable');
    $destination2->expects($this->once())->method('saveFile')->with(
      $this->equalTo($file)
    );

    $plugin->expects($this->once())->method('afterBackup')->with(
      $this->equalTo($file)
    );

    $this->bam->sources()->add('source', $source);
    $this->bam->destinations()->add('destination', $destination);
    $this->bam->destinations()->add('destination2', $destination2);
    $this->bam->plugins()->add('test', $plugin);

    $this->bam->backup('source', array('destination', 'destination2'));

  }

  /**
   * Test backing up from a source to a destination.
   */
  public function testRestore() {
    $file = new ReadableStreamBackupFile('vfs://root/file.txt');

    $source = $this->getMockBuilder('\BackupMigrate\Core\Source\SourceBase')
      ->setMethods(['exportToFile', 'importFromFile'])
      ->getMock();

    $plugin = $this->getMockBuilder('\BackupMigrate\Core\Plugin\PluginBase')
      ->setMethods(['beforeRestore', 'supportedOps'])
      ->getMock();
    $plugin->method('supportedOps')->willReturn(
      ['beforeRestore' => ['weight' => 100]]
    );
    $plugin->method('beforeRestore')->willReturn($file);

    $destination = $this->getMockBuilder('\BackupMigrate\Core\Destination\DirectoryDestination')
      ->setMethods(['getFile'])
      ->getMock();
    $destination->method('getFile')->willReturn($file);

    $destination->expects($this->once())->method('getFile')->with(
      $this->equalTo('file.txt')
    );
    $plugin->expects($this->once())->method('beforeRestore')->with(
      $this->equalTo($file)
    );
    $source->expects($this->once())->method('importFromFile')->with(
      $this->equalTo($file)
    );

    $this->bam->sources()->add('source', $source);
    $this->bam->destinations()->add('destination', $destination);
    $this->bam->plugins()->add('test', $plugin);

    $this->bam->restore('source', 'destination', 'file.txt');
  }
}


text:
Before("@eventbridge") do
  @service = Aws::EventBridge::Resource.new
  @client = @service.client
end

After("@eventbridge") do
  # shared cleanup logic
end


text:
package br.gov.siscomex.portalunico.cct_ext.model;

import java.util.List;

import javax.validation.Valid;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import com.fasterxml.jackson.annotation.JsonProperty;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@XmlAccessorType(XmlAccessType.FIELD)
 @XmlType(name = "VeiculoRodoviario", propOrder =
    { "cpfCondutor", "documentoCondutorEstrangeiro", "nomeCondutorEstrangeiro", "veiculos"
})

@XmlRootElement(name="VeiculoRodoviario")
/**
  * Dados do veículo rodoviário
 **/
@ApiModel(description="Dados do veículo rodoviário")
public class VeiculoRodoviario  {

  @XmlElement(name="cpfCondutor")
  @ApiModelProperty(example = "15573459106", value = "CPF do condutor
Informado quando o condutor for brasileiro
Tamanho: 11
Formato: NNNNNNNNNNN")
 /**
   * CPF do condutor
Informado quando o condutor for brasileiro
Tamanho: 11
Formato: NNNNNNNNNNN
  **/
  private String cpfCondutor = null;

  @XmlElement(name="documentoCondutorEstrangeiro")
  @ApiModelProperty(example = "15573459000106", value = "Documento de identificação do condutor estrangeiro
Informado quando o condutor for estrangeiro juntamente com o nome do condutor
Tamanho: 15")
 /**
   * Documento de identificação do condutor estrangeiro
Informado quando o condutor for estrangeiro juntamente com o nome do condutor
Tamanho: 15
  **/
  private String documentoCondutorEstrangeiro = null;

  @XmlElement(name="nomeCondutorEstrangeiro")
  @ApiModelProperty(example = "Nome do Condutor", value = "Nome do condutor estrangeiro
Informado quando o condutor for estrangeiro juntamente com o documento do condutor
Tamanho: 60")
 /**
   * Nome do condutor estrangeiro
Informado quando o condutor for estrangeiro juntamente com o documento do condutor
Tamanho: 60
  **/
  private String nomeCondutorEstrangeiro = null;

  @XmlElement(name="veiculos")
  @ApiModelProperty(value = "Informação de cada veiculo envolvido no trânsito
Máximo de 4 veículos diferentes entre si. Esta tag contém os dados do \"cavalo\" e seus reboques e será obedecida a seguinte ordem nas informações de veículo rodoviário quando informado : Truck/Cavalo, 1º Reboque, 2º Reboque e 3º Reboque;")
  @Valid
 /**
   * Informação de cada veiculo envolvido no trânsito
Máximo de 4 veículos diferentes entre si. Esta tag contém os dados do \"cavalo\" e seus reboques e será obedecida a seguinte ordem nas informações de veículo rodoviário quando informado : Truck/Cavalo, 1º Reboque, 2º Reboque e 3º Reboque;
  **/
  private List<Veiculo> veiculos = null;
 /**
   * CPF do condutor<br>Informado quando o condutor for brasileiro<br>Tamanho: 11<br>Formato: NNNNNNNNNNN
   * @return cpfCondutor
  **/
  @JsonProperty("cpfCondutor")
  public String getCpfCondutor() {
    return cpfCondutor;
  }

  public void setCpfCondutor(String cpfCondutor) {
    this.cpfCondutor = cpfCondutor;
  }

  public VeiculoRodoviario cpfCondutor(String cpfCondutor) {
    this.cpfCondutor = cpfCondutor;
    return this;
  }

 /**
   * Documento de identificação do condutor estrangeiro<br>Informado quando o condutor for estrangeiro juntamente com o nome do condutor<br>Tamanho: 15
   * @return documentoCondutorEstrangeiro
  **/
  @JsonProperty("documentoCondutorEstrangeiro")
  public String getDocumentoCondutorEstrangeiro() {
    return documentoCondutorEstrangeiro;
  }

  public void setDocumentoCondutorEstrangeiro(String documentoCondutorEstrangeiro) {
    this.documentoCondutorEstrangeiro = documentoCondutorEstrangeiro;
  }

  public VeiculoRodoviario documentoCondutorEstrangeiro(String documentoCondutorEstrangeiro) {
    this.documentoCondutorEstrangeiro = documentoCondutorEstrangeiro;
    return this;
  }

 /**
   * Nome do condutor estrangeiro<br>Informado quando o condutor for estrangeiro juntamente com o documento do condutor<br>Tamanho: 60
   * @return nomeCondutorEstrangeiro
  **/
  @JsonProperty("nomeCondutorEstrangeiro")
  public String getNomeCondutorEstrangeiro() {
    return nomeCondutorEstrangeiro;
  }

  public void setNomeCondutorEstrangeiro(String nomeCondutorEstrangeiro) {
    this.nomeCondutorEstrangeiro = nomeCondutorEstrangeiro;
  }

  public VeiculoRodoviario nomeCondutorEstrangeiro(String nomeCondutorEstrangeiro) {
    this.nomeCondutorEstrangeiro = nomeCondutorEstrangeiro;
    return this;
  }

 /**
   * Informação de cada veiculo envolvido no trânsito<br>Máximo de 4 veículos diferentes entre si. Esta tag contém os dados do \"cavalo\" e seus reboques e será obedecida a seguinte ordem nas informações de veículo rodoviário quando informado : Truck/Cavalo, 1º Reboque, 2º Reboque e 3º Reboque;
   * @return veiculos
  **/
  @JsonProperty("veiculos")
  public List<Veiculo> getVeiculos() {
    return veiculos;
  }

  public void setVeiculos(List<Veiculo> veiculos) {
    this.veiculos = veiculos;
  }

  public VeiculoRodoviario veiculos(List<Veiculo> veiculos) {
    this.veiculos = veiculos;
    return this;
  }

  public VeiculoRodoviario addVeiculosItem(Veiculo veiculosItem) {
    this.veiculos.add(veiculosItem);
    return this;
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class VeiculoRodoviario {\n");

    sb.append("    cpfCondutor: ").append(toIndentedString(cpfCondutor)).append("\n");
    sb.append("    documentoCondutorEstrangeiro: ").append(toIndentedString(documentoCondutorEstrangeiro)).append("\n");
    sb.append("    nomeCondutorEstrangeiro: ").append(toIndentedString(nomeCondutorEstrangeiro)).append("\n");
    sb.append("    veiculos: ").append(toIndentedString(veiculos)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private static String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

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

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'title') ?>

    <?= $form->field($model, 'desc') ?>

    <?= $form->field($model, 'content')->textarea(['cols'=>15,'rows'=>25]) ?>

        <?= Html::submitButton($model->isNewRecord ? 'Создать' : 'Обновить', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

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


text:
"use strict";

module.exports = {
  "parser": "babel-eslint",
  "plugins": [
    "react"
  ],
  "ecmaFeatures": {
    "jsx": false
  },
  "rules": {
    // Prevent missing displayName in a React component definition
    "react/display-name": [0, { "acceptTranspilerName": false }],
    // Forbid certain propTypes
    "react/forbid-prop-types": [0, { "forbid": ["any", "array", "object"] }],
    // Enforce boolean attributes notation in JSX
    "react/jsx-boolean-value": [2, "never"],
    // Validate closing bracket location in JSX
    "react/jsx-closing-bracket-location": [2, "line-aligned"],
    // Enforce or disallow spaces inside of curly braces in JSX attributes
    "react/jsx-curly-spacing": [0, "never", { "allowMultiline": true }],
    // Enforce event handler naming conventions in JSX
    "react/jsx-handler-names": [0, {
      "eventHandlerPrefix": "handle",
      "eventHandlerPropPrefix": "on"
    }],
    // Validate props indentation in JSX
    "react/jsx-indent-props": [2, 2],
    // Validate JSX has key prop when in array or iterator
    "react/jsx-key": 0,
    // Limit maximum of props on a single line in JSX
    "react/jsx-max-props-per-line": [0, { "maximum": 1 }],
    // Prevent usage of .bind() and arrow functions in JSX props
    "react/jsx-no-bind": 2,
    // Prevent duplicate props in JSX
    "react/jsx-no-duplicate-props": [0, { "ignoreCase": false }],
    // Prevent usage of isMounted
    "react/no-is-mounted": 2,
    // Prevent usage of unwrapped JSX strings
    "react/jsx-no-literals": 0,
    // Disallow undeclared variables in JSX
    "react/jsx-no-undef": 2,
    // Enforce PascalCase for user-defined JSX components
    "react/jsx-pascal-case": 0,
    // Enforce quote style for JSX attributes
    "react/jsx-quotes": 0,
    // Enforce propTypes declarations alphabetical sorting
    "react/jsx-sort-prop-types": [0, {
      "ignoreCase": false,
      "callbacksLast": false
    }],
    // Enforce props alphabetical sorting
    "react/jsx-sort-props": [0, {
      "ignoreCase": false,
      "callbacksLast": false
    }],
    // Prevent React to be incorrectly marked as unused
    "react/jsx-uses-react": [2, { "pragma": "React" }],
    // Prevent variables used in JSX to be incorrectly marked as unused
    "react/jsx-uses-vars": 2,
    // Prevent usage of dangerous JSX properties
    "react/no-danger": 0,
    // Prevent usage of deprecated methods
    "react/no-deprecated": [1, { "react": "0.14.0" }],
    // Prevent usage of setState in componentDidMount
    "react/no-did-mount-set-state": [2, "allow-in-func"],
    // Prevent usage of setState in componentDidUpdate
    "react/no-did-update-set-state": [2, "allow-in-func"],
    // Prevent direct mutation of this.state
    "react/no-direct-mutation-state": 0,
    // Prevent multiple component definition per file
    "react/no-multi-comp": [2, { "ignoreStateless": true }],
    // Prevent usage of setState
    "react/no-set-state": 0,
    // Prevent using string references in ref attribute.
    "react/no-string-refs": 0,
    // Prevent usage of unknown DOM property
    "react/no-unknown-property": 0,
    // Enforce ES5 or ES6 class for React Components
    "react/prefer-es6-class": [2, "always"],
    // Prevent missing props validation in a React component definition
    "react/prop-types": [2, { "ignore": [], "customValidators": [] }],
    // Prevent missing React when using JSX
    "react/react-in-jsx-scope": 2,
    // Restrict file extensions that may be required
    "react/require-extension": [0, { "extensions": [".jsx"] }],
    // Prevent extra closing tags for components without children
    "react/self-closing-comp": 2,
    // Enforce component methods order
    "react/sort-comp": [2, {
      "order": [
        "lifecycle",
        "/^on.+$/",
        "/^(get|set)(?!(InitialState$|DefaultProps$|ChildContext$)).+$/",
        "everything-else",
        "/^render.+$/",
        "render"
      ]
    }],
    // Prevent missing parentheses around multilines JSX
    "react/wrap-multilines": [2, {
      declaration: true,
      assignment: true,
      return: true
    }]
  }
};


text:
export class SuggestParameters {
	id:number;
	name:string;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
     Copyright (C) 2015 The Android Open Source Project

     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.
 -->
<resources>

    <color name="white">#FFFFFF</color>
    <color name="grey">#cccccc</color>
    <color name="grey_700">#646464</color>
    <color name="black">#000000</color>

    <!-- using the "Light Blue" Material Palette -->
    <color name="primary">#03A9F4</color>  <!-- 500 -->
    <color name="primary_dark">#0288D1</color>  <!-- 700 -->
    <color name="primary_light">#B3E5FC</color> <!-- 100 -->
    <color name="accent">#FFD740</color>

</resources>


text:
package com.trivago.jcha.correlation;

import com.trivago.jcha.core.SortStyle;

public class CorrelationFactory
{

	/**
	 * Returns a Correlator for the given SortStyle.
	 *
	 * @param sortStyle
	 * @return
	 */
	public static BaseCorrelator get(SortStyle sortStyle)
	{
		if (sortStyle == null)
			throw new IllegalArgumentException("sortStyle must not be null");

		switch (sortStyle)
		{
			case AbsCount:
				return new CorrelatorAbsInstances();
			case AbsSize:
				return new CorrelatorAbsSize();
			case RelCount:
				return new CorrelatorRelInstances();
			case RelSize:
				return new CorrelatorRelSize();
			default:
				throw new IllegalArgumentException("Unsupported sortStyle" + sortStyle);
		}
	}

}


text:
struct PlayerData
{
	char character[MAX_PATH];
	char map[MAX_PATH];
};

#endif


text:
package co.edu.eafit.solver.lib.test.integrals;

import static org.junit.Assert.*;

import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;

import co.edu.eafit.solver.lib.integrals.Simpson13;
import co.edu.eafit.solver.lib.interpolation.EInterpolationParameter;
import co.edu.eafit.solver.lib.systemsolver.MatrixUtility;
import co.edu.eafit.solver.lib.systemsolver.exception.BadParameterException;

public class Simpson13Test {

	private double[][] points = {{1, 0.718281828}, {1.5, 1.48168907}, {2, 3.389056099}};
	private double y = 1.6723490345;

	private Simpson13 s13;
	@Before
	public void setUp() throws BadParameterException {
		JSONObject parameters = new JSONObject();
		parameters.put(EInterpolationParameter.Points.toString(),
				MatrixUtility.matrix2Json(points));

		s13 = new Simpson13();
		s13.setParameters(parameters);
	}

	@Test
	public void testRun() throws Exception {
		s13.interpolate();
	}

	@Test
	public void testSolution() throws Exception {
		s13.interpolate();
		assertEquals(s13.getValue(), y, 0.000001);
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using ElmahLogAnalyzer.Core.Common;
using NUnit.Framework;

namespace ElmahLogAnalyzer.UnitTests.Common
{
	[TestFixture]
	public class UrlCleanerTests : UnitTestBase
	{
		[Test]
		public void Clean_WebformsUrl()
		{
			// act
			var result = UrlCleaner.Clean("/seh/entreprenor/pages/Fakturering.aspx");

			// assert
			Assert.That(result, Is.EqualTo("/seh/entreprenor/pages/Fakturering.aspx"));
		}

		[Test]
		public void Clean_WebformsUrlWithQuerystringParameters()
		{
			// act
			var result = UrlCleaner.Clean("/seh/entreprenor/pages/Fakturering.aspx?someparam=somevalue&someother=someothervalue");

			// assert
			Assert.That(result, Is.EqualTo("/seh/entreprenor/pages/Fakturering.aspx"));
		}

		[Test]
		public void Clean_MvcUrl()
		{
			// act
			var result = UrlCleaner.Clean("/Ruttplan/SkapaValtLappsRad");

			// assert
			Assert.That(result, Is.EqualTo("/Ruttplan/SkapaValtLappsRad"));
		}

		[Test]
		public void Clean_MvcUrlWithGuidAsIdParameter()
		{
			// act
			var result = UrlCleaner.Clean("/Faktura/HamtaFakturaPdf/92dd2ada-bc26-4e42-b8cf-9eb401249cea");

			// assert
			Assert.That(result, Is.EqualTo("/Faktura/HamtaFakturaPdf"));
		}

		[Test]
		public void Clean_MvcUrlWithQueryParameters()
		{
			// act
			var result = UrlCleaner.Clean("/Faktura/HamtaFakturaPdf/92dd2ada-bc26-4e42-b8cf-9eb401249cea?displaymode=edit");

			// assert
			Assert.That(result, Is.EqualTo("/Faktura/HamtaFakturaPdf"));
		}

		[Test]
		public void Clean_MvcRootUrl()
		{
			// act
			var result = UrlCleaner.Clean("/");

			// assert
			Assert.That(result, Is.EqualTo("/"));
		}
	}
}


text:
require 'atomos'
require 'fileutils'
require 'securerandom'

require 'xcodeproj/project/object'
require 'xcodeproj/project/project_helper'
require 'xcodeproj/project/uuid_generator'
require 'xcodeproj/plist'

module Xcodeproj
  # This class represents a Xcode project document.
  #
  # It can be used to manipulate existing documents or even create new ones
  # from scratch.
  #
  # An Xcode project document is a plist file where the root is a dictionary
  # containing the following keys:
  #
  # - archiveVersion: the version of the document.
  # - objectVersion: the version of the objects description.
  # - classes: a key that apparently is always empty.
  # - objects: a dictionary where the UUID of every object is associated to
  #   its attributes.
  # - rootObject: the UUID identifier of the root object ({PBXProject}).
  #
  # Every object is in turn a dictionary that specifies an `isa` (the class of
  # the object) and in accordance to it maintains a set attributes. Those
  # attributes might reference one or more other objects by UUID. If the
  # reference is a collection, it is ordered.
  #
  # The {Project} API returns instances of {AbstractObject} which wrap the
  # objects described in the Xcode project document. All the attributes types
  # are preserved from the plist, except for the relationships which are
  # replaced with objects instead of UUIDs.
  #
  # An object might be referenced by multiple objects, an when no other object
  # is references it, it becomes unreachable (the root object is referenced by
  # the project itself). Xcodeproj takes care of adding and removing those
  # objects from the `objects` dictionary so the project is always in a
  # consistent state.
  #
  class Project
    include Object

    # @return [Pathname] the path of the project.
    #
    attr_reader :path

    # @return [Pathname] the directory of the project
    #
    attr_reader :project_dir

    # @param  [Pathname, String] path @see path
    #         The path provided will be expanded to an absolute path.
    # @param  [Bool] skip_initialization
    #         Wether the project should be initialized from scratch.
    # @param  [Int] object_version
    #         Object version to use for serialization, defaults to Xcode 3.2 compatible.
    #
    # @example Creating a project
    #         Project.new("path/to/Project.xcodeproj")
    #
    # @note When initializing the project, Xcodeproj mimics the Xcode behaviour
    #       including the setup of a debug and release configuration. If you want a
    #       clean project without any configurations, you should override the
    #       `initialize_from_scratch` method to not add these configurations and
    #       manually set the object version.
    #
    def initialize(path, skip_initialization = false, object_version = Constants::DEFAULT_OBJECT_VERSION)
      @path = Pathname.new(path).expand_path
      @project_dir = @path.dirname
      @objects_by_uuid = {}
      @generated_uuids = []
      @available_uuids = []
      @dirty           = true
      unless skip_initialization.is_a?(TrueClass) || skip_initialization.is_a?(FalseClass)
        raise ArgumentError, '[Xcodeproj] Initialization parameter expected to ' \
          "be a boolean #{skip_initialization}"
      end
      unless skip_initialization
        initialize_from_scratch
        @object_version = object_version.to_s
        unless Constants::COMPATIBILITY_VERSION_BY_OBJECT_VERSION.key?(object_version)
          raise ArgumentError, "[Xcodeproj] Unable to find compatibility version string for object version `#{object_version}`."
        end
        root_object.compatibility_version = Constants::COMPATIBILITY_VERSION_BY_OBJECT_VERSION[object_version]
      end
    end

    # Opens the project at the given path.
    #
    # @param  [Pathname, String] path
    #         The path to the Xcode project document (xcodeproj).
    #
    # @raise  If the project versions are more recent than the ones know to
    #         Xcodeproj to prevent it from corrupting existing projects.
    #         Naturally, this would never happen with a project generated by
    #         xcodeproj itself.
    #
    # @raise  If it can't find the root object. This means that the project is
    #         malformed.
    #
    # @example Opening a project
    #         Project.open("path/to/Project.xcodeproj")
    #
    def self.open(path)
      path = Pathname.pwd + path
      unless Pathname.new(path).exist?
        raise "[Xcodeproj] Unable to open `#{path}` because it doesn't exist."
      end
      project = new(path, true)
      project.send(:initialize_from_file)
      project
    end

    # @return [String] the archive version.
    #
    attr_reader :archive_version

    # @return [Hash] an dictionary whose purpose is unknown.
    #
    attr_reader :classes

    # @return [String] the objects version.
    #
    attr_reader :object_version

    # @return [Hash{String => AbstractObject}] A hash containing all the
    #         objects of the project by UUID.
    #
    attr_reader :objects_by_uuid

    # @return [PBXProject] the root object of the project.
    #
    attr_reader :root_object

    # A fast way to see if two {Project} instances refer to the same projects on
    # disk. Use this over {#eql?} when you do not need to compare the full data.
    #
    # This shallow comparison was chosen as the (common) `==` implementation,
    # because it was too easy to introduce changes into the Xcodeproj code-base
    # that were slower than O(1).
    #
    # @return [Boolean] whether or not the two `Project` instances refer to the
    #         same projects on disk, determined solely by {#path} and
    #         `root_object.uuid` equality.
    #
    # @todo If ever needed, we could also compare `uuids.sort` instead.
    #
    def ==(other)
      other && path == other.path && root_object.uuid == other.root_object.uuid
    end

    # Compares the project to another one, or to a plist representation.
    #
    # @note This operation can be extremely expensive, because it converts a
    #       `Project` instance to a hash, and should _only_ ever be used to
    #       determine wether or not the data contents of two `Project` instances
    #       are completely equal.
    #
    #       To simply determine wether or not two {Project} instances refer to
    #       the same projects on disk, use the {#==} method instead.
    #
    # @param  [#to_hash] other the object to compare.
    #
    # @return [Boolean] whether the project is equivalent to the given object.
    #
    def eql?(other)
      other.respond_to?(:to_hash) && to_hash == other.to_hash
    end

    def to_s
      "#<#{self.class}> path:`#{path}` UUID:`#{root_object.uuid}`"
    end

    alias_method :inspect, :to_s

    public

    # @!group Initialization
    #-------------------------------------------------------------------------#

    # Initializes the instance from scratch.
    #
    def initialize_from_scratch
      @archive_version =  Constants::LAST_KNOWN_ARCHIVE_VERSION.to_s
      @classes         =  {}

      root_object.remove_referrer(self) if root_object
      @root_object = new(PBXProject)
      root_object.add_referrer(self)

      root_object.main_group = new(PBXGroup)
      root_object.product_ref_group = root_object.main_group.new_group('Products')

      config_list = new(XCConfigurationList)
      root_object.build_configuration_list = config_list
      config_list.default_configuration_name = 'Release'
      config_list.default_configuration_is_visible = '0'
      add_build_configuration('Debug', :debug)
      add_build_configuration('Release', :release)

      new_group('Frameworks')
    end

    # Initializes the instance with the project stored in the `path` attribute.
    #
    def initialize_from_file
      pbxproj_path = path + 'project.pbxproj'
      plist = Plist.read_from_path(pbxproj_path.to_s)
      root_object.remove_referrer(self) if root_object
      @root_object     = new_from_plist(plist['rootObject'], plist['objects'], self)
      @archive_version = plist['archiveVersion']
      @object_version  = plist['objectVersion']
      @classes         = plist['classes'] || {}
      @dirty           = false

      unless root_object
        raise "[Xcodeproj] Unable to find a root object in #{pbxproj_path}."
      end

      if archive_version.to_i > Constants::LAST_KNOWN_ARCHIVE_VERSION
        raise '[Xcodeproj] Unknown archive version.'
      end

      if object_version.to_i > Constants::LAST_KNOWN_OBJECT_VERSION
        raise '[Xcodeproj] Unknown object version.'
      end

      # Projects can have product_ref_groups that are not listed in the main_groups["Products"]
      root_object.product_ref_group ||= root_object.main_group['Products'] || root_object.main_group.new_group('Products')
    end

    public

    # @!group Plist serialization
    #-------------------------------------------------------------------------#

    # Creates a new object from the given UUID and `objects` hash (of a plist).
    #
    # The method sets up any relationship of the new object, generating the
    # destination object(s) if not already present in the project.
    #
    # @note   This method is used to generate the root object
    #         from a plist. Subsequent invocation are called by the
    #         {AbstractObject#configure_with_plist}. Clients of {Xcodeproj} are
    #         not expected to call this method.
    #
    # @param  [String] uuid
    #         The UUID of the object that needs to be generated.
    #
    # @param  [Hash {String => Hash}] objects_by_uuid_plist
    #         The `objects` hash of the plist representation of the project.
    #
    # @param  [Boolean] root_object
    #         Whether the requested object is the root object and needs to be
    #         retained by the project before configuration to add it to the
    #         `objects` hash and avoid infinite loops.
    #
    # @return [AbstractObject] the new object.
    #
    # @visibility private.
    #
    def new_from_plist(uuid, objects_by_uuid_plist, root_object = false)
      attributes = objects_by_uuid_plist[uuid]
      if attributes
        klass = Object.const_get(attributes['isa'])
        object = klass.new(self, uuid)
        objects_by_uuid[uuid] = object
        object.add_referrer(self) if root_object
        object.configure_with_plist(objects_by_uuid_plist)
        object
      end
    end

    # @return [Hash] The hash representation of the project.
    #
    def to_hash
      plist = {}
      objects_dictionary = {}
      objects.each { |obj| objects_dictionary[obj.uuid] = obj.to_hash }
      plist['objects']        =  objects_dictionary
      plist['archiveVersion'] =  archive_version.to_s
      plist['objectVersion']  =  object_version.to_s
      plist['classes']        =  classes
      plist['rootObject']     =  root_object.uuid
      plist
    end

    def to_ascii_plist
      plist = {}
      objects_dictionary = {}
      objects
        .sort_by { |o| [o.isa, o.uuid] }
        .each do |obj|
          key = Nanaimo::String.new(obj.uuid, obj.ascii_plist_annotation)
          value = obj.to_ascii_plist.tap { |a| a.annotation = nil }
          objects_dictionary[key] = value
        end
      plist['archiveVersion'] =  archive_version.to_s
      plist['classes']        =  classes
      plist['objectVersion']  =  object_version.to_s
      plist['objects']        =  objects_dictionary
      plist['rootObject']     =  Nanaimo::String.new(root_object.uuid, root_object.ascii_plist_annotation)
      Nanaimo::Plist.new.tap { |p| p.root_object = plist }
    end

    # Converts the objects tree to a hash substituting the hash
    # of the referenced to their UUID reference. As a consequence the hash of
    # an object might appear multiple times and the information about their
    # uniqueness is lost.
    #
    # This method is designed to work in conjunction with {Hash#recursive_diff}
    # to provide a complete, yet readable, diff of two projects *not* affected
    # by differences in UUIDs.
    #
    # @return [Hash] a hash representation of the project different from the
    #         plist one.
    #
    def to_tree_hash
      hash = {}
      objects_dictionary = {}
      hash['objects']        =  objects_dictionary
      hash['archiveVersion'] =  archive_version.to_s
      hash['objectVersion']  =  object_version.to_s
      hash['classes']        =  classes
      hash['rootObject']     =  root_object.to_tree_hash
      hash
    end

    # @return [Hash{String => Hash}] A hash suitable to display the project
    #         to the user.
    #
    def pretty_print
      build_configurations = root_object.build_configuration_list.build_configurations
      {
        'File References' => root_object.main_group.pretty_print.values.first,
        'Targets' => root_object.targets.map(&:pretty_print),
        'Build Configurations' => build_configurations.sort_by(&:name).map(&:pretty_print),
      }
    end

    # Serializes the project in the xcodeproj format using the path provided
    # during initialization or the given path (`xcodeproj` file). If a path is
    # provided file references depending on the root of the project are not
    # updated automatically, thus clients are responsible to perform any needed
    # modification before saving.
    #
    # @param  [String, Pathname] path
    #         The optional path where the project should be saved.
    #
    # @example Saving a project
    #   project.save
    #   project.save
    #
    # @return [void]
    #
    def save(save_path = nil)
      save_path ||= path
      @dirty = false if save_path == path
      FileUtils.mkdir_p(save_path)
      file = File.join(save_path, 'project.pbxproj')
      Atomos.atomic_write(file) do |f|
        Nanaimo::Writer::PBXProjWriter.new(to_ascii_plist, :pretty => true, :output => f, :strict => false).write
      end
    end

    # Marks the project as dirty, that is, modified from what is on disk.
    #
    # @return [void]
    #
    def mark_dirty!
      @dirty = true
    end

    # @return [Boolean] Whether this project has been modified since read from
    #         disk or saved.
    #
    def dirty?
      @dirty == true
    end

    # Replaces all the UUIDs in the project with deterministic MD5 checksums.
    #
    # @note The current sorting of the project is taken into account when
    #       generating the new UUIDs.
    #
    # @note This method should only be used for entirely machine-generated
    #       projects, as true UUIDs are useful for tracking changes in the
    #       project.
    #
    # @return [void]
    #
    def predictabilize_uuids
      UUIDGenerator.new([self]).generate!
    end

    # Replaces all the UUIDs in the list of provided projects with deterministic MD5 checksums.
    #
    # @param  [Array<Project>] projects
    #
    # @note The current sorting of the project is taken into account when
    #       generating the new UUIDs.
    #
    # @note This method should only be used for entirely machine-generated
    #       projects, as true UUIDs are useful for tracking changes in the
    #       project.
    #
    # @return [void]
    #
    def self.predictabilize_uuids(projects)
      UUIDGenerator.new(projects).generate!
    end

    public

    # @!group Creating objects
    #-------------------------------------------------------------------------#

    # Creates a new object with a suitable UUID.
    #
    # The object is only configured with the default values of the `:simple`
    # attributes, for this reason it is better to use the convenience methods
    # offered by the {AbstractObject} subclasses or by this class.
    #
    # @param  [Class, String] klass
    #         The concrete subclass of AbstractObject for new object or its
    #         ISA.
    #
    # @return [AbstractObject] the new object.
    #
    def new(klass)
      if klass.is_a?(String)
        klass = Object.const_get(klass)
      end
      object = klass.new(self, generate_uuid)
      object.initialize_defaults
      object
    end

    # Generates a UUID unique for the project.
    #
    # @note   UUIDs are not guaranteed to be generated unique because we need
    #         to trim the ones generated in the xcodeproj extension.
    #
    # @note   Implementation detail: as objects usually are created serially
    #         this method creates a batch of UUID and stores the not colliding
    #         ones, so the search for collisions with known UUIDS (a
    #         performance bottleneck) is performed less often.
    #
    # @return [String] A UUID unique to the project.
    #
    def generate_uuid
      generate_available_uuid_list while @available_uuids.empty?
      @available_uuids.shift
    end

    # @return [Array<String>] the list of all the generated UUIDs.
    #
    # @note   Used for checking new UUIDs for duplicates with UUIDs already
    #         generated but used for objects which are not yet part of the
    #         `objects` hash but which might be added at a later time.
    #
    attr_reader :generated_uuids

    # Pre-generates the given number of UUIDs. Useful for optimizing
    # performance when the rough number of objects that will be created is
    # known in advance.
    #
    # @param  [Integer] count
    #         the number of UUIDs that should be generated.
    #
    # @note   This method might generated a minor number of uniques UUIDs than
    #         the given count, because some might be duplicated a thus will be
    #         discarded.
    #
    # @return [void]
    #
    def generate_available_uuid_list(count = 100)
      new_uuids = (0..count).map { SecureRandom.hex(12).upcase }
      uniques = (new_uuids - (@generated_uuids + uuids))
      @generated_uuids += uniques
      @available_uuids += uniques
    end

    public

    # @!group Convenience accessors
    #-------------------------------------------------------------------------#

    # @return [Array<AbstractObject>] all the objects of the project.
    #
    def objects
      objects_by_uuid.values
    end

    # @return [Array<String>] all the UUIDs of the project.
    #
    def uuids
      objects_by_uuid.keys
    end

    # @return [Array<AbstractObject>] all the objects of the project with a
    #         given ISA.
    #
    def list_by_class(klass)
      objects.select { |o| o.class == klass }
    end

    # @return [PBXGroup] the main top-level group.
    #
    def main_group
      root_object.main_group
    end

    # @return [ObjectList<PBXGroup>] a list of all the groups in the
    #         project.
    #
    def groups
      main_group.groups
    end

    # Returns a group at the given subpath relative to the main group.
    #
    # @example
    #   frameworks = project['Frameworks']
    #   frameworks.name #=> 'Frameworks'
    #   main_group.children.include? frameworks #=> True
    #
    # @param  [String] group_path @see MobileCoreServices
    #
    # @return [PBXGroup] the group at the given subpath.
    #
    def [](group_path)
      main_group[group_path]
    end

    # @return [ObjectList<PBXFileReference>] a list of all the files in the
    #         project.
    #
    def files
      objects.grep(PBXFileReference)
    end

    # Returns the file reference for the given absolute path.
    #
    # @param  [#to_s] absolute_path
    #         The absolute path of the file whose reference is needed.
    #
    # @return [PBXFileReference] The file reference.
    # @return [Nil] If no file reference could be found.
    #
    def reference_for_path(absolute_path)
      absolute_pathname = Pathname.new(absolute_path)

      unless absolute_pathname.absolute?
        raise ArgumentError, "Paths must be absolute #{absolute_path}"
      end

      objects.find do |child|
        child.isa == 'PBXFileReference' && child.real_path == absolute_pathname
      end
    end

    # @return [ObjectList<AbstractTarget>] A list of all the targets in the
    #         project.
    #
    def targets
      root_object.targets
    end

    # @return [ObjectList<PBXNativeTarget>] A list of all the targets in the
    #         project excluding aggregate targets.
    #
    def native_targets
      root_object.targets.grep(PBXNativeTarget)
    end

    # Checks the native target for any targets in the project
    # that are dependent on the native target and would be
    # embedded in it at build time
    #
    # @param  [PBXNativeTarget] native target to check for
    #         embedded targets
    #
    #
    # @return [Array<PBXNativeTarget>] A list of all targets that
    #         are embedded in the passed in target
    #
    def embedded_targets_in_native_target(native_target)
      native_targets.select do |target|
        host_targets_for_embedded_target(target).map(&:uuid).include? native_target.uuid
      end
    end

    # Returns the native targets, in which the embedded target is
    # embedded. This works by traversing the targets to find those
    # where the target is a dependency.
    #
    # @param  [PBXNativeTarget] native target that might be embedded
    #         in another target
    #
    # @return [Array<PBXNativeTarget>] the native targets that host the
    #         embedded target
    #
    def host_targets_for_embedded_target(embedded_target)
      native_targets.select do |native_target|
        ((embedded_target.uuid != native_target.uuid) &&
         (native_target.dependencies.map(&:native_target_uuid).include? embedded_target.uuid))
      end
    end

    # @return [PBXGroup] The group which holds the product file references.
    #
    def products_group
      root_object.product_ref_group
    end

    # @return [ObjectList<PBXFileReference>] A list of the product file
    #         references.
    #
    def products
      products_group.children
    end

    # @return [PBXGroup] the `Frameworks` group creating it if necessary.
    #
    def frameworks_group
      main_group['Frameworks'] || main_group.new_group('Frameworks')
    end

    # @return [ObjectList<XCConfigurationList>] The build configuration list of
    #         the project.
    #
    def build_configuration_list
      root_object.build_configuration_list
    end

    # @return [ObjectList<XCBuildConfiguration>] A list of project wide
    #         build configurations.
    #
    def build_configurations
      root_object.build_configuration_list.build_configurations
    end

    # Returns the build settings of the project wide build configuration with
    # the given name.
    #
    # @param  [String] name
    #         The name of a project wide build configuration.
    #
    # @return [Hash] The build settings.
    #
    def build_settings(name)
      root_object.build_configuration_list.build_settings(name)
    end

    public

    # @!group Helpers
    #-------------------------------------------------------------------------#

    # Creates a new file reference in the main group.
    #
    # @param  @see PBXGroup#new_file
    #
    # @return [PBXFileReference] the new file.
    #
    def new_file(path, source_tree = :group)
      main_group.new_file(path, source_tree)
    end

    # Creates a new group at the given subpath of the main group.
    #
    # @param  @see PBXGroup#new_group
    #
    # @return [PBXGroup] the new group.
    #
    def new_group(name, path = nil, source_tree = :group)
      main_group.new_group(name, path, source_tree)
    end

    # Creates a new target and adds it to the project.
    #
    # The target is configured for the given platform and its file reference it
    # is added to the {products_group}.
    #
    # The target is pre-populated with common build settings, and the
    # appropriate Framework according to the platform is added to to its
    # Frameworks phase.
    #
    # @param  [Symbol] type
    #         the type of target. Can be `:application`, `:framework`,
    #         `:dynamic_library` or `:static_library`.
    #
    # @param  [String] name
    #         the name of the target product.
    #
    # @param  [Symbol] platform
    #         the platform of the target. Can be `:ios` or `:osx`.
    #
    # @param  [String] deployment_target
    #         the deployment target for the platform.
    #
    # @param  [PBXGroup] product_group
    #         the product group, where to add to a file reference of the
    #         created target.
    #
    # @param  [Symbol] language
    #         the primary language of the target, can be `:objc` or `:swift`.
    #
    # @return [PBXNativeTarget] the target.
    #
    def new_target(type, name, platform, deployment_target = nil, product_group = nil, language = nil)
      product_group ||= products_group
      ProjectHelper.new_target(self, type, name, platform, deployment_target, product_group, language)
    end

    # Creates a new resource bundles target and adds it to the project.
    #
    # The target is configured for the given platform and its file reference it
    # is added to the {products_group}.
    #
    # The target is pre-populated with common build settings
    #
    # @param  [String] name
    #         the name of the resources bundle.
    #
    # @param  [Symbol] platform
    #         the platform of the resources bundle. Can be `:ios` or `:osx`.
    #
    # @return [PBXNativeTarget] the target.
    #
    def new_resources_bundle(name, platform, product_group = nil)
      product_group ||= products_group
      ProjectHelper.new_resources_bundle(self, name, platform, product_group)
    end

    # Creates a new target and adds it to the project.
    #
    # The target is configured for the given platform and its file reference it
    # is added to the {products_group}.
    #
    # The target is pre-populated with common build settings, and the
    # appropriate Framework according to the platform is added to to its
    # Frameworks phase.
    #
    # @param  [String] name
    #         the name of the target.
    #
    # @param  [Array<AbstractTarget>] target_dependencies
    #         targets, which should be added as dependencies.
    #
    # @param  [Symbol] platform
    #         the platform of the aggregate target. Can be `:ios` or `:osx`.
    #
    # @param  [String] deployment_target
    #         the deployment target for the platform.
    #
    # @return [PBXNativeTarget] the target.
    #
    def new_aggregate_target(name, target_dependencies = [], platform = nil, deployment_target = nil)
      ProjectHelper.new_aggregate_target(self, name, platform, deployment_target).tap do |aggregate_target|
        target_dependencies.each do |dep|
          aggregate_target.add_dependency(dep)
        end
      end
    end

    # Adds a new build configuration to the project and populates its with
    # default settings according to the provided type.
    #
    # @param  [String] name
    #         The name of the build configuration.
    #
    # @param  [Symbol] type
    #         The type of the build configuration used to populate the build
    #         settings, must be :debug or :release.
    #
    # @return [XCBuildConfiguration] The new build configuration.
    #
    def add_build_configuration(name, type)
      build_configuration_list = root_object.build_configuration_list
      if build_configuration = build_configuration_list[name]
        build_configuration
      else
        build_configuration = new(XCBuildConfiguration)
        build_configuration.name = name
        common_settings = Constants::PROJECT_DEFAULT_BUILD_SETTINGS
        settings = ProjectHelper.deep_dup(common_settings[:all])
        settings.merge!(ProjectHelper.deep_dup(common_settings[type]))
        build_configuration.build_settings = settings
        build_configuration_list.build_configurations << build_configuration
        build_configuration
      end
    end

    # Sorts the project.
    #
    # @param  [Hash] options
    #         the sorting options.
    # @option options [Symbol] :groups_position
    #         the position of the groups can be either `:above` or `:below`.
    #
    # @return [void]
    #
    def sort(options = nil)
      root_object.sort_recursively(options)
    end

    public

    # @!group Schemes
    #-------------------------------------------------------------------------#

    # Get list of shared schemes in project
    #
    # @param [String] path
    #         project path
    #
    # @return [Array]
    #
    def self.schemes(project_path)
      schemes = Dir[File.join(project_path, 'xcshareddata', 'xcschemes', '*.xcscheme')].map do |scheme|
        File.basename(scheme, '.xcscheme')
      end
      schemes << File.basename(project_path, '.xcodeproj') if schemes.empty?
      schemes
    end

    # Recreates the user schemes of the project from scratch (removes the
    # folder) and optionally hides them.
    #
    # @param  [Bool] visible
    #         Whether the schemes should be visible or hidden.
    #
    # @return [void]
    #
    def recreate_user_schemes(visible = true)
      schemes_dir = XCScheme.user_data_dir(path)
      FileUtils.rm_rf(schemes_dir)
      FileUtils.mkdir_p(schemes_dir)

      xcschememanagement = {}
      xcschememanagement['SchemeUserState'] = {}
      xcschememanagement['SuppressBuildableAutocreation'] = {}

      targets.each do |target|
        scheme = XCScheme.new

        test_target = target if target.respond_to?(:test_target_type?) && target.test_target_type?
        launch_target = target.respond_to?(:launchable_target_type?) && target.launchable_target_type?
        scheme.configure_with_targets(target, test_target, :launch_target => launch_target)

        yield scheme, target if block_given?
        scheme.save_as(path, target.name, false)
        xcschememanagement['SchemeUserState']["#{target.name}.xcscheme"] = {}
        xcschememanagement['SchemeUserState']["#{target.name}.xcscheme"]['isShown'] = visible
      end

      xcschememanagement_path = schemes_dir + 'xcschememanagement.plist'
      Plist.write_to_path(xcschememanagement, xcschememanagement_path)
    end

    #-------------------------------------------------------------------------#
  end
end


text:
/*
 * 2012-3 Red Hat Inc. and/or its affiliates and other contributors.
 *
 * 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.
 */
package org.overlord.rtgov.activity.processor;

import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import org.overlord.rtgov.activity.processor.mvel.MVELExpressionEvaluator;
import org.overlord.rtgov.activity.processor.xpath.XPathExpressionEvaluator;

/**
 * This abstract class represents an expression evaluator.
 *
 */
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type")
@JsonSubTypes({@Type(value=MVELExpressionEvaluator.class, name="mvel"),
    @Type(value=XPathExpressionEvaluator.class, name="xpath") })
public abstract class ExpressionEvaluator {

    private String _expression=null;

    private boolean _optional=false;

    /**
     * This method returns the expression.
     *
     * @return The expression
     */
    public String getExpression() {
        return (_expression);
    }

    /**
     * This method sets the expression.
     *
     * @param expr The expression
     */
    public void setExpression(String expr) {
        _expression = expr;
    }

    /**
     * This method gets whether the value being obtained
     * is optional.
     *
     * @return Whether the value associated with the expression is optional
     */
    public boolean getOptional() {
        return (_optional);
    }

    /**
     * This method sets whether the value being obtained
     * is optional.
     *
     * @param optional Whether the value associated with the expression is optional
     */
    public void setOptional(boolean optional) {
        _optional = optional;
    }

    /**
     * This method initializes the expression evaluator.
     *
     * @throws Exception Failed to initialize
     */
    public void init() throws Exception {
    }

    /**
     * This method evaluates the supplied information to
     * derive and return a result.
     *
     * @param information The information
     * @return The result, or null if unable to evaluate
     */
    public abstract String evaluate(Object information);

    /**
     * This method closes the expression evaluator.
     *
     * @throws Exception Failed to close
     */
    public void close() throws Exception {
    }

}


text:
/*************************************************
 * 名称: uiproxy.h
 * 作者: 赵欣昊
 * 时间: 20170616
 * 内容描述: UiProxy类(Messager派生类),为客户端程序中所有UI代理类的基类,
 *      在Messager类的基础上,拥有多个信号槽,功能见代码
 *      所有UiProxy构成一棵树
 * 版权: 这是我们自行完成的程序,没有使用其他来源代码
 ************************************************/

#ifndef UIPROXY_H
#define UIPROXY_H

#include "messager.h"
#include <QMap>
#include <QString>

class UiProxy : public Messager
{
    Q_OBJECT
public:

    explicit UiProxy(UiProxy* parent=0, Messager* player=0);
    virtual ~UiProxy();

    virtual bool setItem(QObject* item);//以某个QObject指针为参数设置UiProxy类的item
    virtual bool setItem(QString name);//以QObject的objectName为参数设置UiProxy类的item
    void setName(QString name);//设置该Proxy类的名字
    QString name;
    QObject* item;//被代理的对象

    template<typename T>
    UiProxy* addChild(QString name,Messager* player);//添加子UiProxy

    QMap<QString, UiProxy*> children;

    virtual void connectSignal();

signals:

public slots:
    virtual void receiveMessage(QString str1, QString str2 = "", QString str3 = "", QString str4 = "", QString str5 = "") = 0;

protected:
    UiProxy* parent;
    Messager* player;

};

template<typename T>
UiProxy* UiProxy::addChild(QString name, Messager* player){
    children[name]=new T(this,player);
    children[name]->name=name;
    return children[name];
}

#endif // UIPROXY_H


text:
var cheerio = require('cheerio'),
	AbstractScraper = require('./AbstractScraper');

/**
 * A static scraper. This can only scrape static content, with the
 *   help of jQuery.
 * This version uses cheerio {@link https://github.com/cheeriojs/cheerio}.
 *
 * @extends {AbstractScraper}
 */
var StaticScraper = function() {
	AbstractScraper.call(this);
	/**
	 * jQuery.
	 *
	 * @type {!function}
	 * @private
	 */
	this.$ = null;
};
StaticScraper.prototype = Object.create(AbstractScraper.prototype);
/**
 * @override
 * @inheritDoc
 */
StaticScraper.prototype.loadBody = function(done) {
	this.$ = cheerio.load(this.body);
	done();
	return this;
};
/**
 * Scrapes the webpage. According to a function, and a callback.
 *
 * @param  {!function(function(), ...?)} scraperFn Function to scrape
 *   the content. It receives the jQuery function to manipulate the
 *   DOM, and the args as parameters, if passed.
 * @param  {!function(?)} callbackFn Function that receives the
 *   result of the scraping.
 * @param  {!Array=} args Extra arguments to pass to the scraping
 *   function.
 * @return {!AbstractScraper} This scraper.
 * @override
 * @public
 */
StaticScraper.prototype.scrape = function(scraperFn, callbackFn, args) {
	var result = null, err = null;
	args = args || [];
	args.unshift(this.$);
	try {
		result = scraperFn.apply(null, args);
	} catch (e) {
		err = e;
	}
	callbackFn(err, result);
	return this;
};
/**
 * @override
 * @inheritDoc
 */
StaticScraper.prototype.close = function() {
	return this;
};
/**
 * @override
 * @inheritDoc
 */
StaticScraper.prototype.clone = function() {
	return new StaticScraper();
};
/**
 * Creates a static scraper, wrapped around a scraper promise.
 *
 * @param  {!string=} url If provided makes an HTTP GET request to the
 *   given URL.
 * @return {!ScraperPromise} Scraper promise, with a static scraper.
 * @public
 * @static
 */
StaticScraper.create = function(url) {
	return AbstractScraper.create(StaticScraper, url);
};

module.exports = StaticScraper;


text:
#include <stdio.h>
#include <stdlib.h>

#include "gmp.h"
#include "gmp-impl.h"
#include "tests.h"

void dump_abort __GMP_PROTO ((char *, mpz_t, unsigned long));
void debug_mp __GMP_PROTO ((mpz_t, int));

int
main (int argc, char **argv)
{
  mpz_t dividend;
  mpz_t quotient, remainder;
  mpz_t quotient2, remainder2;
  mpz_t temp;
  mp_size_t dividend_size;
  unsigned long divisor;
  int i;
  int reps = 10000;
  gmp_randstate_ptr rands;
  mpz_t bs;
  unsigned long bsi, size_range;
  unsigned long r_rq, r_q, r_r, r;

  tests_start ();
  rands = RANDS;

  mpz_init (bs);

  if (argc == 2)
     reps = atoi (argv[1]);

  mpz_init (dividend);
  mpz_init (quotient);
  mpz_init (remainder);
  mpz_init (quotient2);
  mpz_init (remainder2);
  mpz_init (temp);

  for (i = 0; i < reps; i++)
    {
      mpz_urandomb (bs, rands, 32);
      size_range = mpz_get_ui (bs) % 10 + 2; /* 0..2047 bit operands */

      do
	{
	  mpz_rrandomb (bs, rands, 64);
	  divisor = mpz_get_ui (bs);
	}
      while (divisor == 0);

      mpz_urandomb (bs, rands, size_range);
      dividend_size = mpz_get_ui (bs);
      mpz_rrandomb (dividend, rands, dividend_size);

      mpz_urandomb (bs, rands, 2);
      bsi = mpz_get_ui (bs);
      if ((bsi & 1) != 0)
	mpz_neg (dividend, dividend);

      /* printf ("%ld\n", SIZ (dividend)); */

      r_rq = mpz_cdiv_qr_ui (quotient, remainder, dividend, divisor);
      r_q = mpz_cdiv_q_ui (quotient2, dividend, divisor);
      r_r = mpz_cdiv_r_ui (remainder2, dividend, divisor);
      r = mpz_cdiv_ui (dividend, divisor);

      /* First determine that the quotients and remainders computed
	 with different functions are equal.  */
      if (mpz_cmp (quotient, quotient2) != 0)
	dump_abort ("quotients from mpz_cdiv_qr_ui and mpz_cdiv_q_ui differ",
		    dividend, divisor);
      if (mpz_cmp (remainder, remainder2) != 0)
	dump_abort ("remainders from mpz_cdiv_qr_ui and mpz_cdiv_r_ui differ",
		    dividend, divisor);

      /* Check if the sign of the quotient is correct.  */
      if (mpz_cmp_ui (quotient, 0) != 0)
	if ((mpz_cmp_ui (quotient, 0) < 0)
	    != (mpz_cmp_ui (dividend, 0) < 0))
	dump_abort ("quotient sign wrong", dividend, divisor);

      /* Check if the remainder has the opposite sign as the (positive) divisor
	 (quotient rounded towards minus infinity).  */
      if (mpz_cmp_ui (remainder, 0) != 0)
	if (mpz_cmp_ui (remainder, 0) > 0)
	  dump_abort ("remainder sign wrong", dividend, divisor);

      mpz_mul_ui (temp, quotient, divisor);
      mpz_add (temp, temp, remainder);
      if (mpz_cmp (temp, dividend) != 0)
	dump_abort ("n mod d != n - [n/d]*d", dividend, divisor);

      mpz_abs (remainder, remainder);
      if (mpz_cmp_ui (remainder, divisor) >= 0)
	dump_abort ("remainder greater than divisor", dividend, divisor);

      if (mpz_cmp_ui (remainder, r_rq) != 0)
	dump_abort ("remainder returned from mpz_cdiv_qr_ui is wrong",
		    dividend, divisor);
      if (mpz_cmp_ui (remainder, r_q) != 0)
	dump_abort ("remainder returned from mpz_cdiv_q_ui is wrong",
		    dividend, divisor);
      if (mpz_cmp_ui (remainder, r_r) != 0)
	dump_abort ("remainder returned from mpz_cdiv_r_ui is wrong",
		    dividend, divisor);
      if (mpz_cmp_ui (remainder, r) != 0)
	dump_abort ("remainder returned from mpz_cdiv_ui is wrong",
		    dividend, divisor);
    }

  mpz_clear (bs);
  mpz_clear (dividend);
  mpz_clear (quotient);
  mpz_clear (remainder);
  mpz_clear (quotient2);
  mpz_clear (remainder2);
  mpz_clear (temp);

  tests_end ();
  exit (0);
}

void
dump_abort (char *str, mpz_t dividend, unsigned long divisor)
{
  fprintf (stderr, "ERROR: %s\n", str);
  fprintf (stderr, "dividend = "); debug_mp (dividend, -16);
  fprintf (stderr, "divisor  = %lX\n", divisor);
  abort();
}

void
debug_mp (mpz_t x, int base)
{
  mpz_out_str (stderr, base, x); fputc ('\n', stderr);
}


text:
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

source ${SCRIPT_DIR}/kafka_env.sh

if ! docker ps | grep -q "${KAFKA_NODE}"; then
    echo "Kafka Docker container is not running, cannot continue"
    exit 1
fi

echo "Creating Kafka topics..."

for topic in "${TOPICS[@]}"
do
    if docker exec -it ${KAFKA_NODE} ./bin/kafka-topics.sh --bootstrap-server ${BOOTSTRAP_SERVER} --list | grep -q "${topic}"; then
        echo -e "\t- Kafka topic ${topic} already exists"
    else
        docker exec -it ${KAFKA_NODE} ./bin/kafka-topics.sh --bootstrap-server ${BOOTSTRAP_SERVER} --create --topic ${topic} --partitions ${PARTITIONS} --replication-factor ${REPLICATION_FACTOR} > /dev/null
        echo -e "\t- Created Kafka topic ${topic} with partitions ${PARTITIONS} and replication factor ${REPLICATION_FACTOR}"
    fi
done

echo "Completed Kafka topics creation"


text:
package publish_test

import "testing"

func TestCreateStructFromDraft(t *testing.T) {
	name := "create_product_from_draft"
	pbdraft.Create(&Product{Name: name, Color: Color{Name: name}})

	if !pbprod.First(&Product{}, "name = ?", name).RecordNotFound() {
		t.Errorf("record should not be found in production db")
	}

	if pbdraft.First(&Product{}, "name = ?", name).RecordNotFound() {
		t.Errorf("record should be found in draft db")
	}

	if pbprod.Table("colors").First(&Color{}, "name = ?", name).Error != nil {
		t.Errorf("color should be saved")
	}

	if pbprod.Table("colors_draft").First(&Color{}, "name = ?", name).Error == nil {
		t.Errorf("no colors_draft table")
	}

	var product Product
	pbdraft.First(&product, "name = ?", name)

	if !product.PublishStatus {
		t.Errorf("Product's publish status should be DIRTY when created from draft db")
	}

	if pbdraft.Model(&product).Related(&product.Color); product.Color.Name != name {
		t.Errorf("should be able to find related struct")
	}
}

func TestCreateStructFromProduction(t *testing.T) {
	name := "create_product_from_production"
	pbprod.Create(&Product{Name: name, Color: Color{Name: name}})

	if pbprod.First(&Product{}, "name = ?", name).RecordNotFound() {
		t.Errorf("record should not be found in production db")
	}

	if pbdraft.First(&Product{}, "name = ?", name).RecordNotFound() {
		t.Errorf("record should be found in draft db")
	}

	if pbprod.Table("colors").First(&Color{}, "name = ?", name).Error != nil {
		t.Errorf("color should be saved")
	}

	var product Product
	pbprod.First(&product, "name = ?", name)

	if product.PublishStatus {
		t.Errorf("Product's publish status should be PUBLISHED when created from production db")
	}

	if pbprod.Model(&product).Related(&product.Color); product.Color.Name != name {
		t.Errorf("should be able to find related struct")
	}
}


text:
package com.webtrends.harness.component.metrics

import akka.actor.ActorSystem
import akka.testkit.{TestKit, TestProbe}
import com.webtrends.harness.component.TestKitSpecificationWithJUnit
import com.webtrends.harness.component.metrics.messages.{MeterObservation, CounterObservation}
import com.webtrends.harness.component.metrics.metrictype.{Counter, Meter}

class MetricsEventBusSpec extends TestKitSpecificationWithJUnit(ActorSystem("harness")) {

  val metric = Counter("group.subgroup.name.scope")
  val meter = Meter("group.subgroup.name.scope")

  sequential

  "The event bus should " should {

    " allow actors to subscribe and receive metric observations" in {
      val probe = new TestProbe(system)
      MetricsEventBus.subscribe(probe.ref)

      val obs = CounterObservation(metric, 1)
      MetricsEventBus.publish(obs)
      MetricsEventBus.unsubscribe(probe.ref)

      obs must be equalTo probe.expectMsg(obs)
    }

    " allow actors to subscribe and then un-subscribe" in {
      val probe = new TestProbe(system)
      MetricsEventBus.subscribe(probe.ref)

      val obs = MeterObservation(meter, 1)
      MetricsEventBus.publish(obs)
      obs must be equalTo probe.expectMsg(obs)

      MetricsEventBus.unsubscribe(probe.ref)
      MetricsEventBus.publish(obs)
      probe.expectNoMsg()
      success
    }
  }

  step {
    TestKit.shutdownActorSystem(system)
  }
}


text:
<?php
namespace Aca\Bundle\ShopBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class AcaShopBundle extends Bundle
{
}


text:
using System;
using System.Text.RegularExpressions;

namespace RDFSharp.Model
{
    /// <summary>
    /// RDFNamespace represents a generic namespace in the RDF model.
    /// </summary>
    public class RDFNamespace : IEquatable<RDFNamespace>
    {
        #region Properties
        /// <summary>
        /// Regex for validation of prefixes
        /// </summary>
        internal static readonly Lazy<Regex> PrefixRegex = new Lazy<Regex>(() => new Regex(@"^[a-zA-Z0-9_\-]+$", RegexOptions.Compiled));

        /// <summary>
        /// Unique representation of the namespace
        /// </summary>
        internal long NamespaceID { get; set; }

        /// <summary>
        /// Flag indicating that the namespace is temporary
        /// </summary>
        internal bool IsTemporary { get; set; }

        /// <summary>
        /// Prefix representation of the namespace
        /// </summary>
        public string NamespacePrefix { get; internal set; }

        /// <summary>
        /// Uri representation of the namespace
        /// </summary>
        public Uri NamespaceUri { get; internal set; }

        /// <summary>
        /// Uri dereference representation of the namespace
        /// </summary>
        public Uri DereferenceUri { get; internal set; }
        #endregion

        #region Ctors
        /// <summary>
        /// Builds a namespace with given prefix and Uri
        /// </summary>
        public RDFNamespace(string prefix, string uri)
        {
            if (string.IsNullOrWhiteSpace(prefix))
                throw new RDFModelException("Cannot create RDFNamespace because \"prefix\" parameter is null or empty");
            if (string.IsNullOrWhiteSpace(uri))
                throw new RDFModelException("Cannot create RDFNamespace because \"uri\" parameter is null or empty");

            //Prefix must contain only letters/numbers and cannot be "bnode" or "xmlns"
            string finalPrefix = prefix.Trim();
            if (!PrefixRegex.Value.Match(finalPrefix).Success)
                throw new RDFModelException("Cannot create RDFNamespace because \"prefix\" parameter contains unallowed characters");
            if (finalPrefix.Equals("bnode", StringComparison.OrdinalIgnoreCase) || finalPrefix.Equals("xmlns", StringComparison.OrdinalIgnoreCase))
                throw new RDFModelException("Cannot create RDFNamespace because \"prefix\" parameter cannot be \"bnode\" or \"xmlns\"");

            //Uri must be absolute and cannot start with "bnode:" or "xmlns:"
            Uri finalUri = RDFModelUtilities.GetUriFromString(uri.Trim());
            if (finalUri == null)
                throw new RDFModelException("Cannot create RDFNamespace because \"uri\" parameter is not a valid Uri");
            if (finalUri.ToString().StartsWith("bnode", StringComparison.OrdinalIgnoreCase) || finalUri.ToString().StartsWith("xmlns", StringComparison.OrdinalIgnoreCase))
                throw new RDFModelException("Cannot create RDFNamespace because \"uri\" parameter cannot start with \"bnode:\" or \"xmlns:\"");

            this.NamespacePrefix = finalPrefix;
            this.NamespaceUri = finalUri;
            this.DereferenceUri = finalUri;
            this.NamespaceID = RDFModelUtilities.CreateHash(this.ToString());
        }
        #endregion

        #region Interfaces
        /// <summary>
        /// Gives the string representation of the namespace
        /// </summary>
        public override string ToString()
            => this.NamespaceUri.ToString();

        /// <summary>
        /// Performs the equality comparison between two namespaces
        /// </summary>
        public bool Equals(RDFNamespace other)
            => other != null && this.NamespaceID.Equals(other.NamespaceID);
        #endregion

        #region Methods
        /// <summary>
        /// Sets the Uri for dereferencing the namespace when invoked as RDF representation
        /// </summary>
        public RDFNamespace SetDereferenceUri(Uri dereferenceUri)
        {
            if (dereferenceUri != null &&
                  dereferenceUri.IsAbsoluteUri &&
                    !dereferenceUri.ToString().StartsWith("bnode:", StringComparison.OrdinalIgnoreCase) &&
                      !dereferenceUri.ToString().StartsWith("xmlns:", StringComparison.OrdinalIgnoreCase))
            {
                this.DereferenceUri = dereferenceUri;
            }
            return this;
        }

        /// <summary>
        /// Sets or unsets this namespace as temporary
        /// </summary>
        internal RDFNamespace SetTemporary(bool temporary)
        {
            this.IsTemporary = temporary;
            return this;
        }
        #endregion
    }
}


text:
module.exports = {
	description: 'simple chunking',
	options: {
		input: ['main1.js', 'main2.js']
	}
};


text:
"""Loader functionality for SavedModel with hermetic, language-neutral exports.

Load and restore capability for a SavedModel, which may include multiple meta
graph defs. Each SavedModel is associated with a single checkpoint. Each meta
graph def is saved with one or more tags, which are used to identify the exact
meta graph def to load.

The `load` operation requires the session in which to restore the graph
definition and variables, the tags used to identify the meta graph def to
load and the location of the SavedModel.

Upon a load, the subset of variables and assets supplied as part of the specific
meta graph def, will be restored into the supplied session. The values of the
variables though will correspond to the saved values from the first meta graph
added to the SavedModel using `add_meta_graph_and_variables(...)` in
`builder.py`.

Typical usage:

```python
...
builder = tf.saved_model.builder.SavedModelBuilder(export_dir)

with tf.Session(graph=tf.Graph()) as sess:
  ...
  builder.add_meta_graph_and_variables(sess,
                                       ["foo-tag"],
                                       signature_def_map=foo_signatures,
                                       assets_collection=foo_assets)
...

with tf.Session(graph=tf.Graph()) as sess:
  ...
  builder.add_meta_graph(["bar-tag", "baz-tag"],
                         assets_collection=bar_baz_assets)
...

builder.save()

...
with tf.Session(graph=tf.Graph()) as sess:
  tf.saved_model.loader.load(sess, ["foo-tag"], export_dir)
  ...

```
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

# pylint: disable=unused-import
from tensorflow.python.saved_model.loader_impl import load
from tensorflow.python.saved_model.loader_impl import maybe_saved_model_directory
# pylint: enable=unused-import
from tensorflow.python.util.all_util import remove_undocumented

_allowed_symbols = [
    "load",
    "maybe_saved_model_directory",
]
remove_undocumented(__name__, _allowed_symbols)


text:
id: 5900f4761000cf542c50ff88
challengeType: 5
title: 'Problem 265: Binary Circles'
videoUrl: ''
localeTitle: ''
---

## Description
undefined

## Instructions
undefined

## Tests

```yml
tests:
  - text: ''
    testString: 'assert.strictEqual(euler265(), 209110240768, "<code>euler265()</code> should return 209110240768.");'

```

## Challenge Seed

```js
function euler265() {
  // Good luck!
  return true;
}

euler265();

```

## Solution

```js
// solution required
```


text:
[![Build Status](https://travis-ci.org/golmansax/todo-app-on-mean-stack.svg?branch=master)](https://travis-ci.org/golmansax/todo-app-on-mean-stack)
[![Dependencies Status](https://david-dm.org/golmansax/todo-app-on-mean-stack.svg)](https://david-dm.org/golmansax/todo-app-on-mean-stack)

### Todo App on MEAN Stack