text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

		    <link rel="stylesheet" type="text/css" href="Styles/branding.css"/>
		    		<title>Content Type Binding</title>
				<meta name="Description" content="Adds a binding between a content type and a list" />

								SharePoint Software Factory

								Recipe Index

								SPSF Artefacts

								Lists and Libaries

											List Definition

											List Instance

											Module

											Site Column

											Content Type

											ContentType: Add Field

Content Type Binding

											ContentType: Add Document Template

											ContentType: Add Event Receiver

											ContentType: Add Custom Form

											LINQ to SharePoint

Related Links

Content Type Binding Schema

Content Type Binding

Adds a binding between a content type and a list

Arguments

                        Name
                        Description

								Content Type Binding

								Content Type
								Required Text. A string that represents the content type ID of the site content type to add to the specified list.

								List Url
								Required Text. A string that represents the Web-relative path to the list to which to add the content type (e.g. "Pages", "Lists/Contacts").

								RootWebOnly
								Optional Boolean. TRUE to associate this binding only on the root Web site in a site collection (new in SP 2010).

References

						Content Type Binding Schema

Authors

Torsten Mandelkow

Version history

1.0 Initial Recipe

						Disclaimer: The views and opinions expressed in this documentation and in SPSF are those of the authors and do not necessarily reflect the opinions and recommendations of Microsoft or any member of Microsoft. All trademarks, service marks, collective marks, copyrights, registered names, and marks used or cited by this documentation are the property of their respective owners.

						SharePoint Software Factory, Version 4.1.3.2705, GPLv2, see http://spsf.codeplex.com for more information


text:
emukit.model\_wrappers package
==============================

Submodules
----------

.. automodule:: emukit.model_wrappers.gpy_model_wrappers
    :members:
    :undoc-members:
    :show-inheritance:

.. automodule:: emukit.model_wrappers.gpy_quadrature_wrappers
    :members:
    :undoc-members:
    :show-inheritance:

.. automodule:: emukit.model_wrappers.simple_gp_model
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: emukit.model_wrappers
    :members:
    :undoc-members:
    :show-inheritance:

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('repository', '0004_multidestination'),
    ]

    operations = [
        migrations.AddField(
            model_name='contentformat',
            name='pdc_endpoint',
            field=models.CharField(max_length=200, null=True),
        ),
    ]


text:
package org.zmlx.hg4idea.execution;

import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.process.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vcs.LineHandlerHelper;
import com.intellij.vcs.VcsLocaleHelper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.nio.charset.Charset;
import java.util.List;

public final class ShellCommand {
  private final GeneralCommandLine myCommandLine;

  public ShellCommand(@NotNull List<String> commandLine, @Nullable String dir, @Nullable Charset charset) {
    if (commandLine.isEmpty()) {
      throw new IllegalArgumentException("commandLine is empty");
    }
    myCommandLine = new GeneralCommandLine(commandLine);
    if (dir != null) {
      myCommandLine.setWorkDirectory(new File(dir));
    }
    if (charset != null) {
      myCommandLine.setCharset(charset);
    }
    if (ApplicationManager.getApplication().isUnitTestMode()) {
      //ignore all hg config files except current repository config
      myCommandLine.getEnvironment().put("HGRCPATH", "");
    }
    myCommandLine.withEnvironment(VcsLocaleHelper.getDefaultLocaleEnvironmentVars("hg"));
  }

  @NotNull
  public HgCommandResult execute(boolean showTextOnIndicator, boolean isBinary) throws ShellCommandException {
    CommandResultCollector listener = new CommandResultCollector(isBinary);
    execute(showTextOnIndicator, isBinary, listener);
    return listener.getResult();
  }

  public void execute(boolean showTextOnIndicator, boolean isBinary, @NotNull HgLineProcessListener listener)
    throws ShellCommandException {
    ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
    try {
      OSProcessHandler processHandler = isBinary
                                        ? new BinaryOSProcessHandler(myCommandLine)
                                        : new KillableProcessHandler(myCommandLine, Registry.is("hg4idea.execute.with.mediator"));
      ProcessAdapter outputAdapter = new ProcessAdapter() {
        @Override
        public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) {
          for (String line : LineHandlerHelper.splitText(event.getText())) {
            if (ProcessOutputTypes.STDOUT == outputType && indicator != null && showTextOnIndicator) {
              indicator.setText2(line);
            }
            listener.onLineAvailable(line, outputType);
          }
        }

        @Override
        public void processTerminated(@NotNull ProcessEvent event) {
          listener.setExitCode(event.getExitCode());
        }
      };
      processHandler.addProcessListener(outputAdapter);
      processHandler.startNotify();
      while (!processHandler.waitFor(300)) {
        if (indicator != null && indicator.isCanceled()) {
          processHandler.destroyProcess();
          listener.setExitCode(255);
          break;
        }
      }
      if (isBinary) {
        listener.setBinaryOutput(((BinaryOSProcessHandler)processHandler).getOutput());
      }
    }
    catch (ExecutionException e) {
      throw new ShellCommandException(e);
    }
  }

  public static class CommandResultCollector extends HgLineProcessListener {
    @NotNull private final ProcessOutput myOutput;
    private final boolean myIsBinary;

    public CommandResultCollector(boolean binary) {
      myIsBinary = binary;
      myOutput = new ProcessOutput();
    }

    @Override
    protected void processOutputLine(@NotNull String line) {
      myOutput.appendStdout(line);
    }

    @Override
    protected void processErrorLine(@NotNull String line) {
      super.processErrorLine(line);
      myOutput.appendStderr(line);
    }

    @Override
    public void setExitCode(int exitCode) {
      super.setExitCode(exitCode);
      myOutput.setExitCode(exitCode);
    }

    public HgCommandResult getResult() {
      return myIsBinary ? new HgCommandResult(myOutput, getBinaryOutput()) : new HgCommandResult(myOutput);
    }
  }
}


text:
/*
 * Created on 25-Jan-2006
 */
package org.apache.lucene.xmlparser.builders;

import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanFilter;
import org.apache.lucene.search.DuplicateFilter;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.FilterClause;
import org.apache.lucene.xmlparser.DOMUtils;
import org.apache.lucene.xmlparser.FilterBuilder;
import org.apache.lucene.xmlparser.ParserException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 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.
 */

/**
 *
 */
public class DuplicateFilterBuilder implements FilterBuilder {

	public Filter getFilter(Element e) throws ParserException {
        String fieldName=DOMUtils.getAttributeWithInheritanceOrFail(e,"fieldName");
		DuplicateFilter df=new DuplicateFilter(fieldName);
		String keepMode=DOMUtils.getAttribute(e,"keepMode","first");
		if(keepMode.equalsIgnoreCase("first"))
		{
			df.setKeepMode(DuplicateFilter.KM_USE_FIRST_OCCURRENCE);
		}
		else
			if(keepMode.equalsIgnoreCase("last"))
			{
				df.setKeepMode(DuplicateFilter.KM_USE_LAST_OCCURRENCE);
			}
			else
			{
				throw new ParserException("Illegal keepMode attribute in DuplicateFilter:"+keepMode);
			}
		String processingMode=DOMUtils.getAttribute(e,"processingMode","full");
		if(processingMode.equalsIgnoreCase("full"))
		{
			df.setProcessingMode(DuplicateFilter.PM_FULL_VALIDATION);
		}
		else
			if(processingMode.equalsIgnoreCase("fast"))
			{
				df.setProcessingMode(DuplicateFilter.PM_FAST_INVALIDATION);
			}
			else
			{
				throw new ParserException("Illegal processingMode attribute in DuplicateFilter:"+processingMode);
			}

		return df;
	}

}


text:
using System.Collections.Generic;
using System.Web;

namespace Vecc.WebSecurity.ContentSecurity.Policy
{
    /// <summary>
    ///     The content security policy for the server response.
    /// </summary>
    public class Policy
    {
        #region Properties

        /// <summary>
        ///     Gets or sets whether or not to apply the policy in the apply method.
        /// </summary>
        public bool Enabled { get; set; }

        /// <summary>
        ///     Gets or sets whether the policy will only report violation or if it will report and block requests.
        /// </summary>
        public bool ReportOnly { get; set; }

        /// <summary>
        ///     Gets or sets the uri to send violation reports to.
        /// </summary>
        public string ReportUri { get; set; }

        /// <summary>
        ///     The default policy for loading content such as
        ///     JavaScript, Images, CSS, Font's, AJAX requests,
        ///     Frames, HTML5 Media.
        /// </summary>
        public Directive Default { get; set; }

        /// <summary>
        ///     This directive applies to XMLHttpRequest (AJAX), WebSocket or EventSource.
        ///     If not allowed the browser emulates a 400 HTTP status code.
        /// </summary>
        public Directive Connect { get; set; }

        /// <summary>
        ///     Custom directives that may or may not be in the spec, as such, they may not be honored by the browser.
        /// </summary>
        public ICollection<Directive> CustomDirectives { get; set; }

        /// <summary>
        ///     This directive defines valid sources of fonts.
        /// </summary>
        public Directive Font { get; private set; }

        /// <summary>
        ///     This directive defines valid sources for loading frames.
        /// </summary>
        public Directive Frame { get; private set; }

        /// <summary>
        ///     This directive defines valid sources of images.
        /// </summary>
        public Directive Image { get; private set; }

        /// <summary>
        ///     This directive defines valid sources of audio and video, eg HTML5 <audio>, <video> elements.
        /// </summary>
        public Directive Media { get; private set; }

        /// <summary>
        ///     This directive defines valid sources of plugins, eg <object>, <embed> or <applet>.
        /// </summary>
        public Directive Object { get; private set; }

        /// <summary>
        ///     This directive defines valid sources of JavaScript
        /// </summary>
        public Directive Script { get; private set; }

        /// <summary>
        ///     This directive defines valid sources of stylesheets.
        /// </summary>
        public Directive Style { get; private set; }

        #endregion Properties

        #region Constructors

        /// <summary>
        ///     The default constructor
        /// </summary>
        public Policy()
        {
            this.Connect = new Directive(Directives.Connect);
            this.Default = new Directive(Directives.Default);
            this.Font = new Directive(Directives.Font);
            this.Frame = new Directive(Directives.Frame);
            this.Image = new Directive(Directives.Image);
            this.Media = new Directive(Directives.Media);
            this.Object = new Directive(Directives.Object);
            this.Script = new Directive(Directives.Script);
            this.Style = new Directive(Directives.Style);

            this.CustomDirectives = new List<Directive>();
        }

        #endregion Constructors

        #region Public Methods

        /// <summary>
        ///     Creates the header text from all of the directives.
        /// </summary>
        /// <returns></returns>
        public virtual string ToHeader()
        {
            var result =
                this.Connect.ToHeader() +
                this.Default.ToHeader() +
                this.Font.ToHeader() +
                this.Frame.ToHeader() +
                this.Image.ToHeader() +
                this.Media.ToHeader() +
                this.Object.ToHeader() +
                this.Script.ToHeader() +
                this.Style.ToHeader();

            foreach (var directive in this.CustomDirectives)
            {
                result += directive.ToHeader();
            }

            if (!string.IsNullOrWhiteSpace(this.ReportUri))
            {
                result += "report-uri " + this.ReportUri + ";";
            }

            return result;
        }

        /// <summary>
        ///     If enabled is true, will create and add the header to the context response.
        /// </summary>
        /// <param name="context">Context to apply the header to.</param>
        public virtual void Apply(HttpContext context)
        {
            if (this.Enabled)
            {
                var headerName = this.ReportOnly ? "content-security-policy-report-only" : "content-security-policy";
                var headerValue = this.ToHeader();
                if (!string.IsNullOrWhiteSpace(headerValue))
                {
                    context.Response.AddHeader(headerName, headerValue);
                }
            }
        }

        #endregion Public Methods
    }
}


text:
@interface DVTBasicFindBar : DVTFindBar
{
    long long _foundResultCount;
}

- (void)updateStatusInformingDelegate:(BOOL)arg1;
- (void)performFindHighlightingFirstResult:(BOOL)arg1 informDelegate:(BOOL)arg2;
- (void)findBarLostFocus;
- (void)findPrevious:(id)arg1;
- (void)findNext:(id)arg1;
- (BOOL)supportsCaseInsensitiveMatch;
- (BOOL)supportsTextMatchStyle:(int)arg1;
- (BOOL)supportsFindBarMode:(unsigned long long)arg1;
- (BOOL)supportsFindBarType:(unsigned long long)arg1;
@property(retain, nonatomic) id findObject;

@end


text:
<?php

namespace ForkCMS\Modules\Pages\Domain\Page;

use ForkCMS\Modules\Internationalisation\Backend\Domain\Locale\Locale;

final class CopyPageDataTransferObject
{
    /** @var Locale */
    public $from;

    /** @var Locale */
    public $to;

    /** @var Page|null */
    public $pageToCopy;

    public function __construct(Locale $from = null, Page $pageToCopy = null)
    {
        $this->from = $from;
        $this->pageToCopy = $pageToCopy;
    }
}


text:
.class public Landroid/text/Hyphenator;
.super Ljava/lang/Object;
.source "Hyphenator.java"

# static fields
.field private static final LOCALE_FALLBACK_DATA:[[Ljava/lang/String;

.field private static TAG:Ljava/lang/String;

.field static final sEmptyHyphenator:Landroid/text/Hyphenator;

.field private static final sLock:Ljava/lang/Object;

.field static final sMap:Ljava/util/HashMap;
    .annotation build Lcom/android/internal/annotations/GuardedBy;
        value = "sLock"
    .end annotation

    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/HashMap",
            "<",
            "Ljava/util/Locale;",
            "Landroid/text/Hyphenator;",
            ">;"
        }
    .end annotation
.end field

# instance fields
.field private final mNativePtr:J

# direct methods
.method static constructor <clinit>()V
    .registers 7

    .prologue
    const/4 v6, 0x2

    const/4 v5, 0x1

    const/4 v4, 0x0

    .line 41
    const-string/jumbo v0, "Hyphenator"

    sput-object v0, Landroid/text/Hyphenator;->TAG:Ljava/lang/String;

    .line 43
    new-instance v0, Ljava/lang/Object;

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

    sput-object v0, Landroid/text/Hyphenator;->sLock:Ljava/lang/Object;

    .line 46
    new-instance v0, Ljava/util/HashMap;

    invoke-direct {v0}, Ljava/util/HashMap;-><init>()V

    sput-object v0, Landroid/text/Hyphenator;->sMap:Ljava/util/HashMap;

    .line 48
    new-instance v0, Landroid/text/Hyphenator;

    const-string/jumbo v1, ""

    invoke-static {v1}, Landroid/text/StaticLayout;->nLoadHyphenator(Ljava/lang/String;)J

    move-result-wide v2

    invoke-direct {v0, v2, v3}, Landroid/text/Hyphenator;-><init>(J)V

    sput-object v0, Landroid/text/Hyphenator;->sEmptyHyphenator:Landroid/text/Hyphenator;

    .line 114
    const/16 v0, 0xd

    new-array v0, v0, [[Ljava/lang/String;

    .line 119
    new-array v1, v6, [Ljava/lang/String;

    const-string/jumbo v2, "en-AS"

    aput-object v2, v1, v4

    const-string/jumbo v2, "en-US"

    aput-object v2, v1, v5

    aput-object v1, v0, v4

    .line 120
    new-array v1, v6, [Ljava/lang/String;

    const-string/jumbo v2, "en-GU"

    aput-object v2, v1, v4

    const-string/jumbo v2, "en-US"

    aput-object v2, v1, v5

    aput-object v1, v0, v5

    .line 121
    new-array v1, v6, [Ljava/lang/String;

    const-string/jumbo v2, "en-MH"

    aput-object v2, v1, v4

    const-string/jumbo v2, "en-US"

    aput-object v2, v1, v5

    aput-object v1, v0, v6

    .line 122
    new-array v1, v6, [Ljava/lang/String;

    const-string/jumbo v2, "en-MP"

    aput-object v2, v1, v4

    const-string/jumbo v2, "en-US"

    aput-object v2, v1, v5

    const/4 v2, 0x3

    aput-object v1, v0, v2

    .line 123
    new-array v1, v6, [Ljava/lang/String;

    const-string/jumbo v2, "en-PR"

    aput-object v2, v1, v4

    const-string/jumbo v2, "en-US"

    aput-object v2, v1, v5

    const/4 v2, 0x4

    aput-object v1, v0, v2

    .line 124
    new-array v1, v6, [Ljava/lang/String;

    const-string/jumbo v2, "en-UM"

    aput-object v2, v1, v4

    const-string/jumbo v2, "en-US"

    aput-object v2, v1, v5

    const/4 v2, 0x5

    aput-object v1, v0, v2

    .line 125
    new-array v1, v6, [Ljava/lang/String;

    const-string/jumbo v2, "en-VI"

    aput-object v2, v1, v4

    const-string/jumbo v2, "en-US"

    aput-object v2, v1, v5

    const/4 v2, 0x6

    aput-object v1, v0, v2

    .line 128
    new-array v1, v6, [Ljava/lang/String;

    const-string/jumbo v2, "no"

    aput-object v2, v1, v4

    const-string/jumbo v2, "nb"

    aput-object v2, v1, v5

    const/4 v2, 0x7

    aput-object v1, v0, v2

    .line 133
    new-array v1, v6, [Ljava/lang/String;

    const-string/jumbo v2, "am"

    aput-object v2, v1, v4

    const-string/jumbo v2, "und-Ethi"

    aput-object v2, v1, v5

    const/16 v2, 0x8

    aput-object v1, v0, v2

    .line 134
    new-array v1, v6, [Ljava/lang/String;

    const-string/jumbo v2, "byn"

    aput-object v2, v1, v4

    const-string/jumbo v2, "und-Ethi"

    aput-object v2, v1, v5

    const/16 v2, 0x9

    aput-object v1, v0, v2

    .line 135
    new-array v1, v6, [Ljava/lang/String;

    const-string/jumbo v2, "gez"

    aput-object v2, v1, v4

    const-string/jumbo v2, "und-Ethi"

    aput-object v2, v1, v5

    const/16 v2, 0xa

    aput-object v1, v0, v2

    .line 136
    new-array v1, v6, [Ljava/lang/String;

    const-string/jumbo v2, "ti"

    aput-object v2, v1, v4

    const-string/jumbo v2, "und-Ethi"

    aput-object v2, v1, v5

    const/16 v2, 0xb

    aput-object v1, v0, v2

    .line 137
    new-array v1, v6, [Ljava/lang/String;

    const-string/jumbo v2, "wal"

    aput-object v2, v1, v4

    const-string/jumbo v2, "und-Ethi"

    aput-object v2, v1, v5

    const/16 v2, 0xc

    aput-object v1, v0, v2

    .line 114
    sput-object v0, Landroid/text/Hyphenator;->LOCALE_FALLBACK_DATA:[[Ljava/lang/String;

    .line 37
    return-void
.end method

.method private constructor <init>(J)V
    .registers 4
    .param p1, "nativePtr"    # J

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

    .line 53
    iput-wide p1, p0, Landroid/text/Hyphenator;->mNativePtr:J

    .line 52
    return-void
.end method

.method public static get(Ljava/util/Locale;)J
    .registers 9
    .param p0, "locale"    # Ljava/util/Locale;

    .prologue
    .line 57
    sget-object v5, Landroid/text/Hyphenator;->sLock:Ljava/lang/Object;

    monitor-enter v5

    .line 58
    :try_start_3
    sget-object v4, Landroid/text/Hyphenator;->sMap:Ljava/util/HashMap;

    invoke-virtual {v4, p0}, Ljava/util/HashMap;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Landroid/text/Hyphenator;

    .line 59
    .local v1, "result":Landroid/text/Hyphenator;
    if-eqz v1, :cond_11

    .line 60
    iget-wide v6, v1, Landroid/text/Hyphenator;->mNativePtr:J
    :try_end_f
    .catchall {:try_start_3 .. :try_end_f} :catchall_6e

    monitor-exit v5

    return-wide v6

    .line 66
    :cond_11
    :try_start_11
    new-instance v0, Ljava/util/Locale;

    invoke-virtual {p0}, Ljava/util/Locale;->getLanguage()Ljava/lang/String;

    move-result-object v4

    invoke-direct {v0, v4}, Ljava/util/Locale;-><init>(Ljava/lang/String;)V

    .line 67
    .local v0, "languageOnlyLocale":Ljava/util/Locale;
    sget-object v4, Landroid/text/Hyphenator;->sMap:Ljava/util/HashMap;

    invoke-virtual {v4, v0}, Ljava/util/HashMap;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v1

    .end local v1    # "result":Landroid/text/Hyphenator;
    check-cast v1, Landroid/text/Hyphenator;

    .line 68
    .restart local v1    # "result":Landroid/text/Hyphenator;
    if-eqz v1, :cond_2d

    .line 69
    sget-object v4, Landroid/text/Hyphenator;->sMap:Ljava/util/HashMap;

    invoke-virtual {v4, p0, v1}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    .line 70
    iget-wide v6, v1, Landroid/text/Hyphenator;->mNativePtr:J
    :try_end_2b
    .catchall {:try_start_11 .. :try_end_2b} :catchall_6e

    monitor-exit v5

    return-wide v6

    .line 74
    :cond_2d
    :try_start_2d
    invoke-virtual {p0}, Ljava/util/Locale;->getScript()Ljava/lang/String;

    move-result-object v2

    .line 75
    .local v2, "script":Ljava/lang/String;
    const-string/jumbo v4, ""

    invoke-virtual {v2, v4}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v4

    if-nez v4, :cond_61

    .line 76
    new-instance v4, Ljava/util/Locale$Builder;

    invoke-direct {v4}, Ljava/util/Locale$Builder;-><init>()V

    .line 77
    const-string/jumbo v6, "und"

    .line 76
    invoke-virtual {v4, v6}, Ljava/util/Locale$Builder;->setLanguage(Ljava/lang/String;)Ljava/util/Locale$Builder;

    move-result-object v4

    invoke-virtual {v4, v2}, Ljava/util/Locale$Builder;->setScript(Ljava/lang/String;)Ljava/util/Locale$Builder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/util/Locale$Builder;->build()Ljava/util/Locale;

    move-result-object v3

    .line 80
    .local v3, "scriptOnlyLocale":Ljava/util/Locale;
    sget-object v4, Landroid/text/Hyphenator;->sMap:Ljava/util/HashMap;

    invoke-virtual {v4, v3}, Ljava/util/HashMap;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v1

    .end local v1    # "result":Landroid/text/Hyphenator;
    check-cast v1, Landroid/text/Hyphenator;

    .line 81
    .restart local v1    # "result":Landroid/text/Hyphenator;
    if-eqz v1, :cond_61

    .line 82
    sget-object v4, Landroid/text/Hyphenator;->sMap:Ljava/util/HashMap;

    invoke-virtual {v4, p0, v1}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    .line 83
    iget-wide v6, v1, Landroid/text/Hyphenator;->mNativePtr:J
    :try_end_5f
    .catchall {:try_start_2d .. :try_end_5f} :catchall_6e

    monitor-exit v5

    return-wide v6

    .line 87
    .end local v3    # "scriptOnlyLocale":Ljava/util/Locale;
    :cond_61
    :try_start_61
    sget-object v4, Landroid/text/Hyphenator;->sMap:Ljava/util/HashMap;

    sget-object v6, Landroid/text/Hyphenator;->sEmptyHyphenator:Landroid/text/Hyphenator;

    invoke-virtual {v4, p0, v6}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
    :try_end_68
    .catchall {:try_start_61 .. :try_end_68} :catchall_6e

    monitor-exit v5

    .line 89
    sget-object v4, Landroid/text/Hyphenator;->sEmptyHyphenator:Landroid/text/Hyphenator;

    iget-wide v4, v4, Landroid/text/Hyphenator;->mNativePtr:J

    return-wide v4

    .line 57
    .end local v0    # "languageOnlyLocale":Ljava/util/Locale;
    .end local v1    # "result":Landroid/text/Hyphenator;
    .end local v2    # "script":Ljava/lang/String;
    :catchall_6e
    move-exception v4

    monitor-exit v5

    throw v4
.end method

.method private static getSystemHyphenatorLocation()Ljava/io/File;
    .registers 2

    .prologue
    .line 106
    new-instance v0, Ljava/io/File;

    const-string/jumbo v1, "/system/usr/hyphen-data"

    invoke-direct {v0, v1}, Ljava/io/File;-><init>(Ljava/lang/String;)V

    return-object v0
.end method

.method public static init()V
    .registers 12

    .prologue
    const/4 v11, 0x1

    const/4 v10, 0x0

    const/4 v7, 0x0

    .line 148
    sget-object v6, Landroid/text/Hyphenator;->sMap:Ljava/util/HashMap;

    invoke-virtual {v6, v7, v7}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    .line 151
    const/16 v6, 0x8

    new-array v0, v6, [Ljava/lang/String;

    const-string/jumbo v6, "en-US"

    aput-object v6, v0, v10

    const-string/jumbo v6, "eu"

    aput-object v6, v0, v11

    const-string/jumbo v6, "hu"

    const/4 v7, 0x2

    aput-object v6, v0, v7

    const-string/jumbo v6, "hy"

    const/4 v7, 0x3

    aput-object v6, v0, v7

    const-string/jumbo v6, "nb"

    const/4 v7, 0x4

    aput-object v6, v0, v7

    const-string/jumbo v6, "nn"

    const/4 v7, 0x5

    aput-object v6, v0, v7

    const-string/jumbo v6, "sa"

    const/4 v7, 0x6

    aput-object v6, v0, v7

    const-string/jumbo v6, "und-Ethi"

    const/4 v7, 0x7

    aput-object v6, v0, v7

    .line 152
    .local v0, "availableLanguages":[Ljava/lang/String;
    const/4 v3, 0x0

    .local v3, "i":I
    :goto_3b
    array-length v6, v0

    if-ge v3, v6, :cond_52

    .line 153
    aget-object v5, v0, v3

    .line 154
    .local v5, "languageTag":Ljava/lang/String;
    invoke-static {v5}, Landroid/text/Hyphenator;->loadHyphenator(Ljava/lang/String;)Landroid/text/Hyphenator;

    move-result-object v2

    .line 155
    .local v2, "h":Landroid/text/Hyphenator;
    if-eqz v2, :cond_4f

    .line 156
    sget-object v6, Landroid/text/Hyphenator;->sMap:Ljava/util/HashMap;

    invoke-static {v5}, Ljava/util/Locale;->forLanguageTag(Ljava/lang/String;)Ljava/util/Locale;

    move-result-object v7

    invoke-virtual {v6, v7, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    .line 152
    :cond_4f
    add-int/lit8 v3, v3, 0x1

    goto :goto_3b

    .line 160
    .end local v2    # "h":Landroid/text/Hyphenator;
    .end local v5    # "languageTag":Ljava/lang/String;
    :cond_52
    const/4 v3, 0x0

    :goto_53
    sget-object v6, Landroid/text/Hyphenator;->LOCALE_FALLBACK_DATA:[[Ljava/lang/String;

    array-length v6, v6

    if-ge v3, v6, :cond_7c

    .line 161
    sget-object v6, Landroid/text/Hyphenator;->LOCALE_FALLBACK_DATA:[[Ljava/lang/String;

    aget-object v6, v6, v3

    aget-object v4, v6, v10

    .line 162
    .local v4, "language":Ljava/lang/String;
    sget-object v6, Landroid/text/Hyphenator;->LOCALE_FALLBACK_DATA:[[Ljava/lang/String;

    aget-object v6, v6, v3

    aget-object v1, v6, v11

    .line 163
    .local v1, "fallback":Ljava/lang/String;
    sget-object v7, Landroid/text/Hyphenator;->sMap:Ljava/util/HashMap;

    invoke-static {v4}, Ljava/util/Locale;->forLanguageTag(Ljava/lang/String;)Ljava/util/Locale;

    move-result-object v8

    sget-object v6, Landroid/text/Hyphenator;->sMap:Ljava/util/HashMap;

    invoke-static {v1}, Ljava/util/Locale;->forLanguageTag(Ljava/lang/String;)Ljava/util/Locale;

    move-result-object v9

    invoke-virtual {v6, v9}, Ljava/util/HashMap;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v6

    check-cast v6, Landroid/text/Hyphenator;

    invoke-virtual {v7, v8, v6}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    .line 160
    add-int/lit8 v3, v3, 0x1

    goto :goto_53

    .line 147
    .end local v1    # "fallback":Ljava/lang/String;
    .end local v4    # "language":Ljava/lang/String;
    :cond_7c
    return-void
.end method

.method private static loadHyphenator(Ljava/lang/String;)Landroid/text/Hyphenator;
    .registers 10
    .param p0, "languageTag"    # Ljava/lang/String;

    .prologue
    .line 93
    new-instance v6, Ljava/lang/StringBuilder;

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

    const-string/jumbo v7, "hyph-"

    invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v6

    sget-object v7, Ljava/util/Locale;->US:Ljava/util/Locale;

    invoke-virtual {p0, v7}, Ljava/lang/String;->toLowerCase(Ljava/util/Locale;)Ljava/lang/String;

    move-result-object v7

    invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v6

    const-string/jumbo v7, ".pat.txt"

    invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v6

    invoke-virtual {v6}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v5

    .line 94
    .local v5, "patternFilename":Ljava/lang/String;
    new-instance v4, Ljava/io/File;

    invoke-static {}, Landroid/text/Hyphenator;->getSystemHyphenatorLocation()Ljava/io/File;

    move-result-object v6

    invoke-direct {v4, v6, v5}, Ljava/io/File;-><init>(Ljava/io/File;Ljava/lang/String;)V

    .line 96
    .local v4, "patternFile":Ljava/io/File;
    :try_start_2a
    invoke-virtual {v4}, Ljava/io/File;->getAbsolutePath()Ljava/lang/String;

    move-result-object v6

    invoke-static {v6}, Llibcore/io/IoUtils;->readFileAsString(Ljava/lang/String;)Ljava/lang/String;

    move-result-object v1

    .line 97
    .local v1, "patternData":Ljava/lang/String;
    invoke-static {v1}, Landroid/text/StaticLayout;->nLoadHyphenator(Ljava/lang/String;)J

    move-result-wide v2

    .line 98
    .local v2, "nativePtr":J
    new-instance v6, Landroid/text/Hyphenator;

    invoke-direct {v6, v2, v3}, Landroid/text/Hyphenator;-><init>(J)V
    :try_end_3b
    .catch Ljava/io/IOException; {:try_start_2a .. :try_end_3b} :catch_3c

    return-object v6

    .line 99
    .end local v1    # "patternData":Ljava/lang/String;
    .end local v2    # "nativePtr":J
    :catch_3c
    move-exception v0

    .line 100
    .local v0, "e":Ljava/io/IOException;
    sget-object v6, Landroid/text/Hyphenator;->TAG:Ljava/lang/String;

    new-instance v7, Ljava/lang/StringBuilder;

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

    const-string/jumbo v8, "error loading hyphenation "

    invoke-virtual {v7, v8}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v7

    invoke-virtual {v7, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v7

    invoke-virtual {v7}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v7

    invoke-static {v6, v7, v0}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    .line 101
    const/4 v6, 0x0

    return-object v6
.end method


text:
Implement a doubly linked list.

Like an array, a linked list is a simple linear data structure. Several
common data types can be implemented using linked lists, like queues,
stacks, and associative arrays.

A linked list is a collection of data elements called *nodes*. In a
*singly linked list* each node holds a value and a link to the next node.
In a *doubly linked list* each node also holds a link to the previous
node.

You will write an implementation of a doubly linked list. Implement a
Node to hold a value and pointers to the next and previous nodes. Then
implement a List which holds references to the first and last node and
offers an array-like interface for adding and removing items:

* `push` (*insert value at back*);
* `pop` (*remove value at back*);
* `shift` (*remove value at front*).
* `unshift` (*insert value at front*);

To keep your implementation simple, the tests will not cover error
conditions. Specifically: `pop` or `shift` will never be called on an
empty list.

If you want to know more about linked lists, check [Wikipedia](https://en.wikipedia.org/wiki/Linked_list).

## Running the tests

To run the tests, run the command `dotnet test` from within the exercise directory.

Initially, only the first test will be enabled. This is to encourage you to solve the exercise one step at a time.
Once you get the first test passing, remove the `Skip` property from the next test and work on getting that test passing.
Once none of the tests are skipped and they are all passing, you can submit your solution
using `exercism submit LinkedList.cs`

## Further information

For more detailed information about the C# track, including how to get help if
you're having trouble, please visit the exercism.io [C# language page](http://exercism.io/languages/csharp/resources).

## Source

Classic computer science topic


text:
<?php

namespace Depot\Api\Client\Server;

use Depot\Api\Client\HttpClient\HttpClientInterface;
use Depot\Core\Model;

class Profile
{
    protected $httpClient;

    public function __construct(HttpClientInterface $httpClient)
    {
        $this->httpClient = $httpClient;
    }

    public function getProfile(Model\Server\ServerInterface $server)
    {
        return ServerHelper::tryAllServers($server, array($this, 'getProfileInternal'));
    }

    public function getProfileType(Model\Server\ServerInterface $server, $type)
    {
        return ServerHelper::tryAllServers($server, array($this, 'getProfileTypeInternal'), array($type));
    }

    public function putProfileType(Model\Server\ServerInterface $server, Model\Entity\ProfileTypeInterface $profileType)
    {
        return ServerHelper::tryAllServers($server, array($this, 'putProfileTypeInternal'), array($profileType));
    }

    public function getProfileInternal(Model\Server\ServerInterface $server, $apiRoot)
    {
        $response = $this->httpClient->get($apiRoot.'/profile');

        $profile = static::createProfileFromJson(json_decode($response->body(), true));

        $newTypes = array();
        foreach ($profile->types() as $type) {
            $newTypes[$type] = true;
            $server->entity()->profile()->set($profile->find($type));
        }

        foreach ($server->entity()->profile()->types() as $type) {
            if (! isset($newTypes[$type])) {
                $server->entity()->profile()->remove($type);
            }
        }

        return $profile;
    }

    public function getProfileTypeInternal(Model\Server\ServerInterface $server, $apiRoot, $type)
    {
        $response = $this->httpClient->get($apiRoot.'/profile/'.rawurlencode($type));

        $profileType = new Model\Entity\ProfileType($type, json_decode($response->body(), true));

        $server->entity()->profile()->set($profileType);

        return $profileType;
    }

    public function putProfileTypeInternal(Model\Server\ServerInterface $server, $apiRoot, Model\Entity\ProfileTypeInterface $profileType)
    {
        $response = $this->httpClient->put(
            $apiRoot.'/profile/'.rawurlencode($profileType->uri()),
            null,
            json_encode($profileType->content())
        );

        $profileType = new Model\Entity\ProfileType($profileType->uri(), json_decode($response->body(), true));

        $server->entity()->profile()->set($profileType);

        return $profileType;
    }

    public static function createProfileFromJson($json)
    {
        if ( ! isset($json['https://tent.io/types/info/core/v0.1.0']['entity'])) {
            return null;
        }

        if ( ! isset($json['https://tent.io/types/info/core/v0.1.0']['servers'])) {
            return null;
        }

        $profile = new Model\Entity\Profile;
        foreach ($json as $type => $content) {
            $profile->set(new Model\Entity\ProfileType($type, $content));
        }

        return $profile;
    }
}


text:
package org.apache.flink.runtime.jobmanager;

import org.apache.flink.runtime.client.JobExecutionException;
import org.apache.flink.runtime.io.network.api.reader.RecordReader;
import org.apache.flink.runtime.io.network.api.writer.RecordWriter;
import org.apache.flink.runtime.io.network.partition.ResultPartitionType;
import org.apache.flink.runtime.jobgraph.JobVertex;
import org.apache.flink.runtime.jobgraph.DistributionPattern;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable;
import org.apache.flink.runtime.testingUtils.TestingCluster;
import org.apache.flink.runtime.testingUtils.TestingUtils;
import org.apache.flink.types.IntValue;

import org.apache.flink.util.TestLogger;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.util.BitSet;

public class SlotCountExceedingParallelismTest extends TestLogger {

	// Test configuration
	private final static int NUMBER_OF_TMS = 2;
	private final static int NUMBER_OF_SLOTS_PER_TM = 2;
	private final static int PARALLELISM = NUMBER_OF_TMS * NUMBER_OF_SLOTS_PER_TM;

	private static TestingCluster flink;

	@BeforeClass
	public static void setUp() throws Exception {
		flink = TestingUtils.startTestingCluster(
				NUMBER_OF_SLOTS_PER_TM,
				NUMBER_OF_TMS,
				TestingUtils.DEFAULT_AKKA_ASK_TIMEOUT());
	}

	@AfterClass
	public static void tearDown() throws Exception {
		if (flink != null) {
			flink.stop();
		}
	}

	@Test
	public void testNoSlotSharingAndBlockingResult() throws Exception {
		final String jobName = "SlotCountExceedingParallelismTest (no slot sharing, blocking results)";

		// Sender with higher parallelism than available slots
		JobGraph jobGraph = createTestJobGraph(jobName, PARALLELISM * 2, PARALLELISM);
		submitJobGraphAndWait(jobGraph);

		// Receiver with higher parallelism than available slots
		jobGraph = createTestJobGraph(jobName, PARALLELISM, PARALLELISM * 2);
		submitJobGraphAndWait(jobGraph);

		// Both sender and receiver with higher parallelism than available slots
		jobGraph = createTestJobGraph(jobName, PARALLELISM * 2, PARALLELISM * 2);
		submitJobGraphAndWait(jobGraph);
	}

	// ---------------------------------------------------------------------------------------------

	private void submitJobGraphAndWait(final JobGraph jobGraph) throws JobExecutionException {
		flink.submitJobAndWait(jobGraph, false, TestingUtils.TESTING_DURATION());
	}

	private JobGraph createTestJobGraph(
			String jobName,
			int senderParallelism,
			int receiverParallelism) {

		// The sender and receiver invokable logic ensure that each subtask gets the expected data
		final JobVertex sender = new JobVertex("Sender");
		sender.setInvokableClass(RoundRobinSubtaskIndexSender.class);
		sender.getConfiguration().setInteger(RoundRobinSubtaskIndexSender.CONFIG_KEY, receiverParallelism);
		sender.setParallelism(senderParallelism);

		final JobVertex receiver = new JobVertex("Receiver");
		receiver.setInvokableClass(SubtaskIndexReceiver.class);
		receiver.getConfiguration().setInteger(SubtaskIndexReceiver.CONFIG_KEY, senderParallelism);
		receiver.setParallelism(receiverParallelism);

		receiver.connectNewDataSetAsInput(
				sender,
				DistributionPattern.ALL_TO_ALL,
				ResultPartitionType.BLOCKING);

		final JobGraph jobGraph = new JobGraph(jobName, sender, receiver);

		// We need to allow queued scheduling, because there are not enough slots available
		// to run all tasks at once. We queue tasks and then let them finish/consume the blocking
		// result one after the other.
		jobGraph.setAllowQueuedScheduling(true);

		return jobGraph;
	}

	/**
	 * Sends the subtask index a configurable number of times in a round-robin fashion.
	 */
	public static class RoundRobinSubtaskIndexSender extends AbstractInvokable {

		public final static String CONFIG_KEY = "number-of-times-to-send";

		@Override
		public void invoke() throws Exception {
			RecordWriter<IntValue> writer = new RecordWriter<>(getEnvironment().getWriter(0));
			final int numberOfTimesToSend = getTaskConfiguration().getInteger(CONFIG_KEY, 0);

			final IntValue subtaskIndex = new IntValue(
					getEnvironment().getTaskInfo().getIndexOfThisSubtask());

			try {
				for (int i = 0; i < numberOfTimesToSend; i++) {
					writer.emit(subtaskIndex);
				}
				writer.flush();
			}
			finally {
				writer.clearBuffers();
			}
		}
	}

	/**
	 * Expects to receive the subtask index from a configurable number of sender tasks.
	 */
	public static class SubtaskIndexReceiver extends AbstractInvokable {

		public final static String CONFIG_KEY = "number-of-indexes-to-receive";

		@Override
		public void invoke() throws Exception {
			RecordReader<IntValue> reader = new RecordReader<>(
					getEnvironment().getInputGate(0),
					IntValue.class,
					getEnvironment().getTaskManagerInfo().getTmpDirectories());

			try {
				final int numberOfSubtaskIndexesToReceive = getTaskConfiguration().getInteger(CONFIG_KEY, 0);
				final BitSet receivedSubtaskIndexes = new BitSet(numberOfSubtaskIndexesToReceive);

				IntValue record;

				int numberOfReceivedSubtaskIndexes = 0;

				while ((record = reader.next()) != null) {
					// Check that we don't receive more than expected
					numberOfReceivedSubtaskIndexes++;

					if (numberOfReceivedSubtaskIndexes > numberOfSubtaskIndexesToReceive) {
						throw new IllegalStateException("Received more records than expected.");
					}

					int subtaskIndex = record.getValue();

					// Check that we only receive each subtask index once
					if (receivedSubtaskIndexes.get(subtaskIndex)) {
						throw new IllegalStateException("Received expected subtask index twice.");
					}
					else {
						receivedSubtaskIndexes.set(subtaskIndex, true);
					}
				}

				// Check that we have received all expected subtask indexes
				if (receivedSubtaskIndexes.cardinality() != numberOfSubtaskIndexesToReceive) {
					throw new IllegalStateException("Finished receive, but did not receive "
							+ "all expected subtask indexes.");
				}
			}
			finally {
				reader.clearBuffers();
			}
		}
	}
}


text:
from .core import Pattern, PatternSet, Traverser, VAR
from .dynamic import DynamicPatternSet
from .static import StaticPatternSet


text:
package com.amazonaws.services.identitymanagement.model.transform;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.internal.ListWithAutoConstructFlag;
import com.amazonaws.services.identitymanagement.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * Change Password Request Marshaller
 */
public class ChangePasswordRequestMarshaller implements Marshaller<Request<ChangePasswordRequest>, ChangePasswordRequest> {

    public Request<ChangePasswordRequest> marshall(ChangePasswordRequest changePasswordRequest) {

        if (changePasswordRequest == null) {
            throw new AmazonClientException("Invalid argument passed to marshall(...)");
        }

        Request<ChangePasswordRequest> request = new DefaultRequest<ChangePasswordRequest>(changePasswordRequest, "AmazonIdentityManagement");
        request.addParameter("Action", "ChangePassword");
        request.addParameter("Version", "2010-05-08");

        if (changePasswordRequest.getOldPassword() != null) {
            request.addParameter("OldPassword", StringUtils.fromString(changePasswordRequest.getOldPassword()));
        }
        if (changePasswordRequest.getNewPassword() != null) {
            request.addParameter("NewPassword", StringUtils.fromString(changePasswordRequest.getNewPassword()));
        }

        return request;
    }
}


text:
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/regex.hpp>

#include <OpenEXR/half.h>

#include <cmath>

#include "OpenImageIO/imagebuf.h"
#include "OpenImageIO/imagebufalgo.h"
#include "OpenImageIO/imagebufalgo_util.h"
#include "OpenImageIO/dassert.h"
#include "OpenImageIO/platform.h"
#include "OpenImageIO/filter.h"
#include "OpenImageIO/thread.h"
#include "kissfft.hh"

///////////////////////////////////////////////////////////////////////////
// Guidelines for ImageBufAlgo functions:
//
// * Signature will always be:
//       bool function (ImageBuf &R /* result */,
//                      const ImageBuf &A, ...other input images...,
//                      ...other parameters...
//                      ROI roi = ROI::All(),
//                      int nthreads = 0);
// * The ROI should restrict the operation to those pixels (and channels)
//   specified. Default ROI::All() means perform the operation on all
//   pixel in R's data window.
// * It's ok to omit ROI and threads from the few functions that
//   (a) can't possibly be parallelized, and (b) do not make sense to
//   apply to anything less than the entire image.
// * Be sure to clamp the channel range to those actually used.
// * If R is initialized, do not change any pixels outside the ROI.
//   If R is uninitialized, redefine ROI to be the union of the input
//   images' data windows and allocate R to be that size.
// * Try to always do the "reasonable thing" rather than be too brittle.
// * For errors (where there is no "reasonable thing"), set R's error
//   condition using R.error() with R.error() and return false.
// * Always use IB::Iterators/ConstIterator, NEVER use getpixel/setpixel.
// * Use the iterator Black or Clamp wrap modes to avoid lots of special
//   cases inside the pixel loops.
// * Use OIIO_DISPATCH_* macros to call type-specialized templated
//   implemenations.  It is permissible to use OIIO_DISPATCH_COMMON_TYPES_*
//   to tame the cross-product of types, especially for binary functions
//   (A,B inputs as well as R output).
///////////////////////////////////////////////////////////////////////////

OIIO_NAMESPACE_ENTER
{

bool
ImageBufAlgo::IBAprep (ROI &roi, ImageBuf *dst, const ImageBuf *A,
                       const ImageBuf *B, const ImageBuf *C,
                       ImageSpec *force_spec, int prepflags)
{
    if ((A && !A->initialized()) ||
        (B && !B->initialized()) ||
        (C && !C->initialized())) {
        if (dst)
            dst->error ("Uninitialized input image");
        return false;
    }
    int maxchans = 10000;
    if (prepflags & IBAprep_CLAMP_MUTUAL_NCHANNELS) {
        // Instructions to clamp chend to the highest of the inputs
        if (dst && dst->initialized())
            maxchans = std::min (maxchans, dst->spec().nchannels);
        if (A && A->initialized())
            maxchans = std::min (maxchans, A->spec().nchannels);
        if (B && B->initialized())
            maxchans = std::min (maxchans, B->spec().nchannels);
        if (C && C->initialized())
            maxchans = std::min (maxchans, C->spec().nchannels);
    }
    if (dst->initialized()) {
        // Valid destination image.  Just need to worry about ROI.
        if (roi.defined()) {
            // Shrink-wrap ROI to the destination (including chend)
            roi = roi_intersection (roi, get_roi(dst->spec()));
        } else {
            // No ROI? Set it to all of dst's pixel window.
            roi = get_roi (dst->spec());
        }
        // If the dst is initialized but is a cached image, we'll need
        // to fully read it into allocated memory so that we're able
        // to write to it subsequently.
        dst->make_writeable (true);
    } else {
        // Not an initialized destination image!
        ASSERT ((A || roi.defined()) &&
                "ImageBufAlgo without any guess about region of interest");
        ROI full_roi;
        if (! roi.defined()) {
            // No ROI -- make it the union of the pixel regions of the inputs
            roi = A->roi();
            full_roi = A->roi_full();
            if (B) {
                roi = roi_union (roi, B->roi());
                full_roi = roi_union (full_roi, B->roi_full());
            }
            if (C) {
                roi = roi_union (roi, C->roi());
                full_roi = roi_union (full_roi, C->roi_full());
            }
        } else {
            if (A) {
                roi.chend = std::min (roi.chend, A->nchannels());
                if (! (prepflags & IBAprep_NO_COPY_ROI_FULL))
                    full_roi = A->roi_full();
            } else {
                full_roi = roi;
            }
        }
        // Now we allocate space for dst.  Give it A's spec, but adjust
        // the dimensions to match the ROI.
        ImageSpec spec;
        if (A) {
            // If there's an input image, give dst A's spec (with
            // modifications detailed below...)
            spec = force_spec ? (*force_spec) : A->spec();
            // For multiple inputs, if they aren't the same data type, punt and
            // allocate a float buffer. If the user wanted something else,
            // they should have pre-allocated dst with their desired format.
            if (B && A->spec().format != B->spec().format)
                spec.set_format (TypeDesc::FLOAT);
            if (C && (A->spec().format != C->spec().format ||
                      B->spec().format != C->spec().format))
                spec.set_format (TypeDesc::FLOAT);
            // No good can come from automatically polluting an ImageBuf
            // with some other ImageBuf's tile sizes.
            spec.tile_width = 0;
            spec.tile_height = 0;
            spec.tile_depth = 0;
        } else if (force_spec) {
            spec = *force_spec;
        } else {
            spec.set_format (TypeDesc::FLOAT);
            spec.nchannels = roi.chend;
            spec.default_channel_names ();
        }
        // Set the image dimensions based on ROI.
        set_roi (spec, roi);
        if (full_roi.defined())
            set_roi_full (spec, full_roi);
        else
            set_roi_full (spec, roi);

        if (prepflags & IBAprep_NO_COPY_METADATA)
            spec.extra_attribs.clear();
        else if (! (prepflags & IBAprep_COPY_ALL_METADATA)) {
            // Since we're altering pixels, be sure that any existing SHA
            // hash of dst's pixel values is erased.
            spec.erase_attribute ("oiio:SHA-1");
            static boost::regex regex_sha ("SHA-1=[[:xdigit:]]*[ ]*");
            std::string desc = spec.get_string_attribute ("ImageDescription");
            if (desc.size())
                spec.attribute ("ImageDescription",
                                boost::regex_replace (desc, regex_sha, ""));
        }

        dst->reset (spec);
    }
    roi.chend = std::min (roi.chend, maxchans);
    if (prepflags & IBAprep_REQUIRE_ALPHA) {
        if (dst->spec().alpha_channel < 0 ||
              (A && A->spec().alpha_channel < 0) ||
              (B && B->spec().alpha_channel < 0) ||
              (C && C->spec().alpha_channel < 0)) {
            dst->error ("images must have alpha channels");
            return false;
        }
    }
    if (prepflags & IBAprep_REQUIRE_Z) {
        if (dst->spec().z_channel < 0 ||
              (A && A->spec().z_channel < 0) ||
              (B && B->spec().z_channel < 0) ||
              (C && C->spec().z_channel < 0)) {
            dst->error ("images must have depth channels");
            return false;
        }
    }
    if (prepflags & IBAprep_REQUIRE_SAME_NCHANNELS) {
        int n = dst->spec().nchannels;
        if ((A && A->spec().nchannels != n) ||
            (B && B->spec().nchannels != n) ||
            (C && C->spec().nchannels != n)) {
            dst->error ("images must have the same number of channels");
            return false;
        }
    }
    if (prepflags & IBAprep_NO_SUPPORT_VOLUME) {
        if (dst->spec().depth > 1 ||
                (A && A->spec().depth > 1) ||
                (B && B->spec().depth > 1) ||
                (C && C->spec().depth > 1)) {
            dst->error ("volumes not supported");
            return false;
        }
    }
    if (! (prepflags & IBAprep_SUPPORT_DEEP) &&
        ((dst && dst->deep()) || (A && A->deep()) ||
         (B && B->deep()) || (C && C->deep()))) {
        dst->error ("deep data not supported");
        return false;
    }
    return true;
}

/// Given data types a and b, return a type that is a best guess for one
/// that can handle both without any loss of range or precision.
TypeDesc::BASETYPE
ImageBufAlgo::type_merge (TypeDesc::BASETYPE a, TypeDesc::BASETYPE b)
{
    // Same type already? done.
    if (a == b)
        return a;
    if (a == TypeDesc::UNKNOWN)
        return b;
    if (b == TypeDesc::UNKNOWN)
        return a;
    // Canonicalize so a's size (in bytes) is >= b's size in bytes. This
    // unclutters remaining cases.
    if (TypeDesc(a).size() < TypeDesc(b).size())
        std::swap (a, b);
    // Double or float trump anything else
    if (a == TypeDesc::DOUBLE || a == TypeDesc::FLOAT)
        return a;
    if (a == TypeDesc::UINT32 && (b == TypeDesc::UINT16 || b == TypeDesc::UINT8))
        return a;
    if (a == TypeDesc::INT32 && (b == TypeDesc::INT16 || b == TypeDesc::UINT16 ||
                                 b == TypeDesc::INT8 || b == TypeDesc::UINT8))
        return a;
    if ((a == TypeDesc::UINT16 || a == TypeDesc::HALF) && b == TypeDesc::UINT8)
        return a;
    if ((a == TypeDesc::INT16 || a == TypeDesc::HALF) &&
        (b == TypeDesc::INT8 || b == TypeDesc::UINT8))
        return a;
    // Out of common cases. For all remaining edge cases, punt and say that
    // we prefer float.
    return TypeDesc::FLOAT;
}

template<typename DSTTYPE, typename SRCTYPE>
static bool
convolve_ (ImageBuf &dst, const ImageBuf &src, const ImageBuf &kernel,
           bool normalize, ROI roi, int nthreads)
{
    if (nthreads != 1 && roi.npixels() >= 1000) {
        // Lots of pixels and request for multi threads? Parallelize.
        ImageBufAlgo::parallel_image (
            boost::bind(convolve_<DSTTYPE,SRCTYPE>, boost::ref(dst),
                        boost::cref(src), boost::cref(kernel), normalize,
                        _1 /*roi*/, 1 /*nthreads*/),
            roi, nthreads);
        return true;
    }

    // Serial case

    float scale = 1.0f;
    if (normalize) {
        scale = 0.0f;
        for (ImageBuf::ConstIterator<float> k (kernel); ! k.done(); ++k)
            scale += k[0];
        scale = 1.0f / scale;
    }

    float *sum = ALLOCA (float, roi.chend);
    ROI kroi = get_roi (kernel.spec());
    ImageBuf::Iterator<DSTTYPE> d (dst, roi);
    ImageBuf::ConstIterator<SRCTYPE> s (src, roi, ImageBuf::WrapClamp);
    for ( ; ! d.done();  ++d) {

        for (int c = roi.chbegin; c < roi.chend; ++c)
            sum[c] = 0.0f;

        for (ImageBuf::ConstIterator<float> k (kernel, kroi); !k.done(); ++k) {
            float kval = k[0];
            s.pos (d.x() + k.x(), d.y() + k.y(), d.z() + k.z());
            for (int c = roi.chbegin; c < roi.chend; ++c)
                sum[c] += kval * s[c];
        }

        for (int c = roi.chbegin; c < roi.chend; ++c)
            d[c] = scale * sum[c];
    }

    return true;
}

bool
ImageBufAlgo::convolve (ImageBuf &dst, const ImageBuf &src,
                        const ImageBuf &kernel, bool normalize,
                        ROI roi, int nthreads)
{
    if (! IBAprep (roi, &dst, &src, IBAprep_REQUIRE_SAME_NCHANNELS))
        return false;
    bool ok;
    const ImageBuf *K = &kernel;
    ImageBuf Ktmp;
    if (kernel.spec().format != TypeDesc::FLOAT) {
        Ktmp.copy (kernel, TypeDesc::FLOAT);
        K = &Ktmp;
    }
    OIIO_DISPATCH_COMMON_TYPES2 (ok, "convolve", convolve_,
                          dst.spec().format, src.spec().format,
                          dst, src, *K, normalize, roi, nthreads);
    return ok;
}

inline float binomial (int n, int k)
{
    float p = 1;
    for (int i = 1;  i <= k;  ++i)
        p *= float(n - (k-i)) / i;
    return p;
}

bool
ImageBufAlgo::make_kernel (ImageBuf &dst, string_view name,
                           float width, float height, float depth,
                           bool normalize)
{
    int w = std::max (1, (int)ceilf(width));
    int h = std::max (1, (int)ceilf(height));
    int d = std::max (1, (int)ceilf(depth));
    // Round up size to odd
    w |= 1;
    h |= 1;
    d |= 1;
    ImageSpec spec (w, h, 1 /*channels*/, TypeDesc::FLOAT);
    spec.depth = d;
    spec.x = -w/2;
    spec.y = -h/2;
    spec.z = -d/2;
    spec.full_x = spec.x;
    spec.full_y = spec.y;
    spec.full_z = spec.z;
    spec.full_width = spec.width;
    spec.full_height = spec.height;
    spec.full_depth = spec.depth;
    dst.reset (spec);

    if (Filter2D *filter = Filter2D::create (name, width, height)) {
        // Named continuous filter from filter.h
        for (ImageBuf::Iterator<float> p (dst);  ! p.done();  ++p)
            p[0] = (*filter)((float)p.x(), (float)p.y());
        delete filter;
    } else if (name == "binomial") {
        // Binomial filter
        float *wfilter = ALLOCA (float, width);
        for (int i = 0;  i < width;  ++i)
            wfilter[i] = binomial (width-1, i);
        float *hfilter = (height == width) ? wfilter : ALLOCA (float, height);
        if (height != width)
            for (int i = 0;  i < height;  ++i)
                hfilter[i] = binomial (height-1, i);
        float *dfilter = ALLOCA (float, depth);
        if (depth == 1)
            dfilter[0] = 1;
        else
            for (int i = 0;  i < depth;  ++i)
                dfilter[i] = binomial (depth-1, i);
        for (ImageBuf::Iterator<float> p (dst);  ! p.done();  ++p)
            p[0] = wfilter[p.x()-spec.x] * hfilter[p.y()-spec.y] * dfilter[p.z()-spec.z];
    } else {
        // No filter -- make a box
        float val = normalize ? 1.0f / ((w*h*d)) : 1.0f;
        for (ImageBuf::Iterator<float> p (dst);  ! p.done();  ++p)
            p[0] = val;
        dst.error ("Unknown kernel \"%s\"", name);
        return false;
    }
    if (normalize) {
        float sum = 0;
        for (ImageBuf::Iterator<float> p (dst);  ! p.done();  ++p)
            sum += p[0];
        for (ImageBuf::Iterator<float> p (dst);  ! p.done();  ++p)
            p[0] = p[0] / sum;
    }
    return true;
}

// Helper function for unsharp mask to perform the thresholding
static bool
threshold_to_zero (ImageBuf &dst, float threshold,
                   ROI roi, int nthreads)
{
    ASSERT (dst.spec().format.basetype == TypeDesc::FLOAT);

    if (nthreads != 1 && roi.npixels() >= 1000) {
        // Lots of pixels and request for multi threads? Parallelize.
        ImageBufAlgo::parallel_image (
            boost::bind(threshold_to_zero, boost::ref(dst), threshold,
                        _1 /*roi*/, 1 /*nthreads*/),
            roi, nthreads);
        return true;
    }

    // Serial case
    for (ImageBuf::Iterator<float> p (dst, roi);  ! p.done();  ++p)
        for (int c = roi.chbegin;  c < roi.chend;  ++c)
            if (fabsf(p[c]) < threshold)
                p[c] = 0.0f;

    return true;
}

bool
ImageBufAlgo::unsharp_mask (ImageBuf &dst, const ImageBuf &src,
                            string_view kernel, float width,
                            float contrast, float threshold,
                            ROI roi, int nthreads)
{
    if (! IBAprep (roi, &dst, &src,
            IBAprep_REQUIRE_SAME_NCHANNELS | IBAprep_NO_SUPPORT_VOLUME))
        return false;

    // Blur the source image, store in Blurry
    ImageSpec BlurrySpec = src.spec();
    BlurrySpec.set_format (TypeDesc::FLOAT);  // force float
    ImageBuf Blurry (BlurrySpec);

    if (kernel == "median") {
        median_filter (Blurry, src, ceilf(width), 0, roi, nthreads);
    } else {
        ImageBuf K;
        if (! make_kernel (K, kernel, width, width)) {
            dst.error ("%s", K.geterror());
            return false;
        }
        if (! convolve (Blurry, src, K, true, roi, nthreads)) {
            dst.error ("%s", Blurry.geterror());
            return false;
        }
    }

    // Compute the difference between the source image and the blurry
    // version.  (We store it in the same buffer we used for the difference
    // image.)
    ImageBuf &Diff (Blurry);
    bool ok = sub (Diff, src, Blurry, roi, nthreads);

    if (ok && threshold > 0.0f)
        ok = threshold_to_zero (Diff, threshold, roi, nthreads);

    // Scale the difference image by the contrast
    if (ok)
        ok = mul (Diff, Diff, contrast, roi, nthreads);
    if (! ok) {
        dst.error ("%s", Diff.geterror());
        return false;
    }

    // Add the scaled difference to the original, to get the final answer
    ok = add (dst, src, Diff, roi, nthreads);

    return ok;
}

template<class Rtype, class Atype>
static bool
median_filter_impl (ImageBuf &R, const ImageBuf &A, int width, int height,
                    ROI roi, int nthreads)
{
    if (nthreads != 1 && roi.npixels() >= 1000) {
        // Possible multiple thread case -- recurse via parallel_image
        ImageBufAlgo::parallel_image (
            boost::bind(median_filter_impl<Rtype,Atype>,
                        boost::ref(R), boost::cref(A),
                        width, height, _1 /*roi*/, 1 /*nthreads*/),
            roi, nthreads);
        return true;
    }

    if (width < 1)
        width = 1;
    if (height < 1)
        height = width;
    int w_2 = std::max (1, width/2);
    int h_2 = std::max (1, height/2);
    int windowsize = width*height;
    int nchannels = R.nchannels();
    float **chans = OIIO_ALLOCA (float*, nchannels);
    for (int c = 0;  c < nchannels;  ++c)
        chans[c] = OIIO_ALLOCA (float, windowsize);

    ImageBuf::ConstIterator<Atype> a (A, roi);
    for (ImageBuf::Iterator<Rtype> r (R, roi);  !r.done();  ++r) {
        a.rerange (r.x()-w_2, r.x()-w_2+width,
                   r.y()-h_2, r.y()-h_2+height,
                   r.z(), r.z()+1, ImageBuf::WrapClamp);
        int n = 0;
        for ( ;  ! a.done(); ++a) {
            if (a.exists()) {
                for (int c = 0;  c < nchannels;  ++c)
                    chans[c][n] = a[c];
                ++n;
            }
        }
        if (n) {
            int mid = n/2;
            for (int c = 0;  c < nchannels;  ++c) {
                std::sort (chans[c]+0, chans[c]+n);
                r[c] = chans[c][mid];
            }
        } else {
            for (int c = 0;  c < nchannels;  ++c)
                r[c] = 0.0f;
        }
    }
    return true;
}

bool
ImageBufAlgo::median_filter (ImageBuf &dst, const ImageBuf &src,
                             int width, int height,
                             ROI roi, int nthreads)
{
    if (! IBAprep (roi, &dst, &src,
            IBAprep_REQUIRE_SAME_NCHANNELS | IBAprep_NO_SUPPORT_VOLUME))
        return false;

    bool ok;
    OIIO_DISPATCH_COMMON_TYPES2 (ok, "median_filter",
                                 median_filter_impl, dst.spec().format,
                                 src.spec().format, dst, src,
                                 width, height, roi, nthreads);
    return ok;
}

// Helper function: fft of the horizontal rows
static bool
hfft_ (ImageBuf &dst, const ImageBuf &src, bool inverse, bool unitary,
       ROI roi, int nthreads)
{
    ASSERT (dst.spec().format.basetype == TypeDesc::FLOAT &&
            src.spec().format.basetype == TypeDesc::FLOAT &&
            dst.spec().nchannels == 2 && src.spec().nchannels == 2 &&
            dst.roi() == src.roi() &&
            (dst.storage() == ImageBuf::LOCALBUFFER || dst.storage() == ImageBuf::APPBUFFER) &&
            (src.storage() == ImageBuf::LOCALBUFFER || src.storage() == ImageBuf::APPBUFFER)
        );

    if (nthreads != 1 && roi.npixels() >= 1000) {
        // Lots of pixels and request for multi threads? Parallelize.
        ImageBufAlgo::parallel_image (
            boost::bind (hfft_, boost::ref(dst), boost::cref(src),
                         inverse, unitary,
                         _1 /*roi*/, 1 /*nthreads*/),
            roi, nthreads);
        return true;
    }

    // Serial case
    int width = roi.width();
    float rescale = sqrtf (1.0f / width);
    kissfft<float> F (width, inverse);
    for (int z = roi.zbegin;  z < roi.zend;  ++z) {
        for (int y = roi.ybegin;  y < roi.yend;  ++y) {
            std::complex<float> *s, *d;
            s = (std::complex<float> *)src.pixeladdr(roi.xbegin, y, z);
            d = (std::complex<float> *)dst.pixeladdr(roi.xbegin, y, z);
            F.transform (s, d);
            if (unitary)
                for (int x = 0;  x < width;  ++x)
                    d[x] *= rescale;
        }
    }
    return true;
}

bool
ImageBufAlgo::fft (ImageBuf &dst, const ImageBuf &src,
                   ROI roi, int nthreads)
{
    if (src.spec().depth > 1) {
        dst.error ("ImageBufAlgo::fft does not support volume images");
        return false;
    }
    if (! roi.defined())
        roi = roi_union (get_roi (src.spec()), get_roi_full (src.spec()));
    roi.chend = roi.chbegin+1;   // One channel only

    // Construct a spec that describes the result
    ImageSpec spec = src.spec();
    spec.width = spec.full_width = roi.width();
    spec.height = spec.full_height = roi.height();
    spec.depth = spec.full_depth = 1;
    spec.x = spec.full_x = 0;
    spec.y = spec.full_y = 0;
    spec.z = spec.full_z = 0;
    spec.set_format (TypeDesc::FLOAT);
    spec.channelformats.clear();
    spec.nchannels = 2;
    spec.channelnames.clear();
    spec.channelnames.push_back ("real");
    spec.channelnames.push_back ("imag");

    // And a spec that describes the transposed intermediate
    ImageSpec specT = spec;
    std::swap (specT.width, specT.height);
    std::swap (specT.full_width, specT.full_height);

    // Resize dst
    dst.reset (dst.name(), spec);

    // Copy src to a 2-channel (for "complex") float buffer
    ImageBuf A (spec);
    if (src.nchannels() < 2) {
        // If we're pasting fewer than 2 channels, zero out channel 1.
        ROI r = roi;
        r.chbegin = 1; r.chend = 2;
        zero (A, r);
    }
    if (! ImageBufAlgo::paste (A, 0, 0, 0, 0, src, roi, nthreads)) {
        dst.error ("%s", A.geterror());
        return false;
    }

    // FFT the rows (into temp buffer B).
    ImageBuf B (spec);
    hfft_ (B, A, false /*inverse*/, true /*unitary*/,
           get_roi(B.spec()), nthreads);

    // Transpose and shift back to A
    A.clear ();
    ImageBufAlgo::transpose (A, B, ROI::All(), nthreads);

    // FFT what was originally the columns (back to B)
    B.reset (specT);
    hfft_ (B, A, false /*inverse*/, true /*unitary*/,
           get_roi(A.spec()), nthreads);

    // Transpose again, into the dest
    ImageBufAlgo::transpose (dst, B, ROI::All(), nthreads);

    return true;
}

bool
ImageBufAlgo::ifft (ImageBuf &dst, const ImageBuf &src,
                    ROI roi, int nthreads)
{
    if (src.nchannels() != 2 || src.spec().format != TypeDesc::FLOAT) {
        dst.error ("ifft can only be done on 2-channel float images");
        return false;
    }
    if (src.spec().depth > 1) {
        dst.error ("ImageBufAlgo::ifft does not support volume images");
        return false;
    }

    if (! roi.defined())
        roi = roi_union (get_roi (src.spec()), get_roi_full (src.spec()));
    roi.chbegin = 0;
    roi.chend = 2;

    // Construct a spec that describes the result
    ImageSpec spec = src.spec();
    spec.width = spec.full_width = roi.width();
    spec.height = spec.full_height = roi.height();
    spec.depth = spec.full_depth = 1;
    spec.x = spec.full_x = 0;
    spec.y = spec.full_y = 0;
    spec.z = spec.full_z = 0;
    spec.set_format (TypeDesc::FLOAT);
    spec.channelformats.clear();
    spec.nchannels = 2;
    spec.channelnames.clear();
    spec.channelnames.push_back ("real");
    spec.channelnames.push_back ("imag");

    // Inverse FFT the rows (into temp buffer B).
    ImageBuf B (spec);
    hfft_ (B, src, true /*inverse*/, true /*unitary*/,
           get_roi(B.spec()), nthreads);

    // Transpose and shift back to A
    ImageBuf A;
    ImageBufAlgo::transpose (A, B, ROI::All(), nthreads);

    // Inverse FFT what was originally the columns (back to B)
    B.reset (A.spec());
    hfft_ (B, A, true /*inverse*/, true /*unitary*/,
           get_roi(A.spec()), nthreads);

    // Transpose again, into the dst, in the process throw out the
    // imaginary part and go back to a single (real) channel.
    spec.nchannels = 1;
    spec.channelnames.clear ();
    spec.channelnames.push_back ("R");
    dst.reset (dst.name(), spec);
    ROI Broi = get_roi(B.spec());
    Broi.chend = 1;
    ImageBufAlgo::transpose (dst, B, Broi, nthreads);

    return true;
}

template<class Rtype, class Atype>
static bool
polar_to_complex_impl (ImageBuf &R, const ImageBuf &A, ROI roi, int nthreads)
{
    if (nthreads != 1 && roi.npixels() >= 1000) {
        // Possible multiple thread case -- recurse via parallel_image
        ImageBufAlgo::parallel_image (
            boost::bind(polar_to_complex_impl<Rtype,Atype>, boost::ref(R), boost::cref(A),
                        _1 /*roi*/, 1 /*nthreads*/),
            roi, nthreads);
        return true;
    }

    ImageBuf::ConstIterator<Atype> a (A, roi);
    for (ImageBuf::Iterator<Rtype> r (R, roi);  !r.done();  ++r, ++a) {
        float amp = a[0];
        float phase = a[1];
        float sine, cosine;
        sincos (phase, &sine, &cosine);
        r[0] = amp * cosine;
        r[1] = amp * sine;
    }
    return true;
}

template<class Rtype, class Atype>
static bool
complex_to_polar_impl (ImageBuf &R, const ImageBuf &A, ROI roi, int nthreads)
{
    if (nthreads != 1 && roi.npixels() >= 1000) {
        // Possible multiple thread case -- recurse via parallel_image
        ImageBufAlgo::parallel_image (
            boost::bind(complex_to_polar_impl<Rtype,Atype>, boost::ref(R), boost::cref(A),
                        _1 /*roi*/, 1 /*nthreads*/),
            roi, nthreads);
        return true;
    }

    ImageBuf::ConstIterator<Atype> a (A, roi);
    for (ImageBuf::Iterator<Rtype> r (R, roi);  !r.done();  ++r, ++a) {
        float real = a[0];
        float imag = a[1];
        float phase = std::atan2 (imag, real);
        if (phase < 0.0f)
            phase += float (M_TWO_PI);
        r[0] = hypotf (real, imag);
        r[1] = phase;
    }
    return true;
}

bool
ImageBufAlgo::polar_to_complex (ImageBuf &dst, const ImageBuf &src,
                             ROI roi, int nthreads)
{
    if (src.nchannels() != 2) {
        dst.error ("polar_to_complex can only be done on 2-channel");
        return false;
    }

    if (! IBAprep (roi, &dst, &src))
        return false;
    if (dst.nchannels() != 2) {
        dst.error ("polar_to_complex can only be done on 2-channel");
        return false;
    }
    bool ok;
    OIIO_DISPATCH_COMMON_TYPES2 (ok, "polar_to_complex",
                                 polar_to_complex_impl, dst.spec().format,
                                 src.spec().format, dst, src, roi, nthreads);
    return ok;
}

bool
ImageBufAlgo::complex_to_polar (ImageBuf &dst, const ImageBuf &src,
                             ROI roi, int nthreads)
{
    if (src.nchannels() != 2) {
        dst.error ("complex_to_polar can only be done on 2-channel");
        return false;
    }

    if (! IBAprep (roi, &dst, &src))
        return false;
    if (dst.nchannels() != 2) {
        dst.error ("complex_to_polar can only be done on 2-channel");
        return false;
    }
    bool ok;
    OIIO_DISPATCH_COMMON_TYPES2 (ok, "complex_to_polar",
                                 complex_to_polar_impl, dst.spec().format,
                                 src.spec().format, dst, src, roi, nthreads);
    return ok;
}

// Helper for fillholes_pp: for any nonzero alpha pixels in dst, divide
// all components by alpha.
static bool
divide_by_alpha (ImageBuf &dst, ROI roi, int nthreads)
{
    if (nthreads != 1 && roi.npixels() >= 1000) {
        // Lots of pixels and request for multi threads? Parallelize.
        ImageBufAlgo::parallel_image (
            boost::bind(divide_by_alpha, boost::ref(dst),
                        _1 /*roi*/, 1 /*nthreads*/),
            roi, nthreads);
        return true;
    }

    // Serial case
    const ImageSpec &spec (dst.spec());
    ASSERT (spec.format == TypeDesc::FLOAT);
    int nc = spec.nchannels;
    int ac = spec.alpha_channel;
    for (ImageBuf::Iterator<float> d (dst, roi);  ! d.done();  ++d) {
        float alpha = d[ac];
        if (alpha != 0.0f) {
            for (int c = 0; c < nc; ++c)
                d[c] = d[c] / alpha;
        }
    }
    return true;
}

bool
ImageBufAlgo::fillholes_pushpull (ImageBuf &dst, const ImageBuf &src,
                                  ROI roi, int nthreads)
{
    if (! IBAprep (roi, &dst, &src))
        return false;
    const ImageSpec &dstspec (dst.spec());
    if (dstspec.nchannels != src.nchannels()) {
        dst.error ("channel number mismatch: %d vs. %d",
                   dstspec.nchannels, src.spec().nchannels);
        return false;
    }
    if (dst.spec().depth > 1 || src.spec().depth > 1) {
        dst.error ("ImageBufAlgo::fillholes_pushpull does not support volume images");
        return false;
    }
    if (dstspec.alpha_channel < 0 ||
        dstspec.alpha_channel != src.spec().alpha_channel) {
        dst.error ("Must have alpha channels");
        return false;
    }

    // We generate a bunch of temp images to form an image pyramid.
    // These give us a place to stash them and make sure they are
    // auto-deleted when the function exits.
    std::vector<boost::shared_ptr<ImageBuf> > pyramid;

    // First, make a writeable copy of the original image (converting
    // to float as a convenience) as the top level of the pyramid.
    ImageSpec topspec = src.spec();
    topspec.set_format (TypeDesc::FLOAT);
    ImageBuf *top = new ImageBuf (topspec);
    paste (*top, topspec.x, topspec.y, topspec.z, 0, src);
    pyramid.push_back (boost::shared_ptr<ImageBuf>(top));

    // Construct the rest of the pyramid by successive x/2 resizing and
    // then dividing nonzero alpha pixels by their alpha (this "spreads
    // out" the defined part of the image).
    int w = src.spec().width, h = src.spec().height;
    while (w > 1 || h > 1) {
        w = std::max (1, w/2);
        h = std::max (1, h/2);
        ImageSpec smallspec (w, h, src.nchannels(), TypeDesc::FLOAT);
        ImageBuf *small = new ImageBuf (smallspec);
        ImageBufAlgo::resize (*small, *pyramid.back(), "triangle");
        divide_by_alpha (*small, get_roi(smallspec), nthreads);
        pyramid.push_back (boost::shared_ptr<ImageBuf>(small));
        //debug small->save();
    }

    // Now pull back up the pyramid by doing an alpha composite of level
    // i over a resized level i+1, thus filling in the alpha holes.  By
    // time we get to the top, pixels whose original alpha are
    // unchanged, those with alpha < 1 are replaced by the blended
    // colors of the higher pyramid levels.
    for (int i = (int)pyramid.size()-2;  i >= 0;  --i) {
        ImageBuf &big(*pyramid[i]), &small(*pyramid[i+1]);
        ImageBuf blowup (big.spec());
        ImageBufAlgo::resize (blowup, small, "triangle");
        ImageBufAlgo::over (big, big, blowup);
        //debug big.save (Strutil::format ("after%d.exr", i));
    }

    // Now copy the completed base layer of the pyramid back to the
    // original requested output.
    paste (dst, dstspec.x, dstspec.y, dstspec.z, 0, *pyramid[0]);

    return true;
}

}
OIIO_NAMESPACE_EXIT


text:
<!DOCTYPE HTML>

<title>Source code</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="source: package: com.restfb.types, class: ProfilePictureSource">
<meta name="generator" content="javadoc/SourceToHTMLConverter">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

001// Generated by delombok at Tue Sep 27 22:25:18 CEST 2022
002
023package com.restfb.types;
024
025import com.restfb.Facebook;
026
027/**
028 * Represents the <a href="https://developers.facebook.com/docs/graph-api/reference/profile-picture-source/">Profile
029 * Picture Source Graph API type</a>.
030 *
031 * @author Norbert Bartels
032 */
033public class ProfilePictureSource extends AbstractFacebookType {
034  private static final long serialVersionUID = 1L;
035  /**
036   * URL of the profile picture
037   *
038   */
039  @Facebook
040  private String url;
041  /**
042   * Indicates whether the profile photo is the default 'silhouette' picture, or has been replaced
043   *
044   */
045  @Facebook("is_silhouette")
046  private Boolean isSilhouette;
047  /**
048   * Picture height in pixels
049   *
050   */
051  @Facebook
052  private Integer height;
053  /**
054   * Picture width in pixels
055   *
056   */
057  @Facebook
058  private Integer width;
059
060  /**
061   * URL of the profile picture
062   *
063   * @return URL of the profile picture
064   */
065  @java.lang.SuppressWarnings("all")
066  public String getUrl() {
067    return this.url;
068  }
069
070  /**
071   * URL of the profile picture
072   *
073   */
074  @java.lang.SuppressWarnings("all")
075  public void setUrl(final String url) {
076    this.url = url;
077  }
078
079  /**
080   * Indicates whether the profile photo is the default 'silhouette' picture, or has been replaced
081   *
082   * @return is the photo the default or has been replaced
083   */
084  @java.lang.SuppressWarnings("all")
085  public Boolean getIsSilhouette() {
086    return this.isSilhouette;
087  }
088
089  /**
090   * Indicates whether the profile photo is the default 'silhouette' picture, or has been replaced
091   *
092   */
093  @java.lang.SuppressWarnings("all")
094  public void setIsSilhouette(final Boolean isSilhouette) {
095    this.isSilhouette = isSilhouette;
096  }
097
098  /**
099   * Picture height in pixels
100   *
101   * @return Picture height in pixels
102   */
103  @java.lang.SuppressWarnings("all")
104  public Integer getHeight() {
105    return this.height;
106  }
107
108  /**
109   * Picture height in pixels
110   *
111   */
112  @java.lang.SuppressWarnings("all")
113  public void setHeight(final Integer height) {
114    this.height = height;
115  }
116
117  /**
118   * Picture width in pixels
119   *
120   * @return Picture width in pixels
121   */
122  @java.lang.SuppressWarnings("all")
123  public Integer getWidth() {
124    return this.width;
125  }
126
127  /**
128   * Picture width in pixels
129   *
130   */
131  @java.lang.SuppressWarnings("all")
132  public void setWidth(final Integer width) {
133    this.width = width;
134  }
135}


text:
title: "getMessageGetter"
parent: "@messageformat/react"
grand_parent: API Reference
---

# getMessageGetter() function

Given a `MessageContext` instance, returns a message getter function, which may have a preset root id path, locale, and/or base parameters for message functions.

The returned function takes two parameters `(msgId, msgParams)`, which will extend any values set by the hook's arguments.

Signature:

```typescript
export declare function getMessageGetter(context: MessageContext, rootId?: string | string[], { baseParams, locale }?: MessageGetterOptions): (id?: string | string[] | undefined, params?: any) => any;
```

## Parameters

|  Parameter | Type | Description |
|  --- | --- | --- |
|  context | [MessageContext](./react.messagecontext.md) | The MessageContext instance |
|  rootId | string \| string\[\] | The key or key path of the message or message object. If empty or [], matches the root of the messages object |
|  { baseParams, locale } | MessageGetterOptions |  |

Returns:

(id?: string \| string\[\] \| undefined, params?: any) => any


text:
require File.expand_path('../test_helper', File.dirname(__FILE__))

describe Ing::Command do

  def dummy_command_class
    Class.new do
      attr_reader :options
      def initialize(options); @options = options; end
      def dummy; end
    end
  end

  def dummy_command_class_with_specify_options
    Class.new do
      def self.specify_options(expect); end
      attr_reader :options
      def initialize(options); @options = options; end
      def dummy; end
    end
  end

  def dummy_command_proc
    x = Proc.new { }
    def x.dummy; end
    x
  end

  #-----------------------------------------------------------------------------
  describe ".new" do

    describe "when only command class passed" do
      subject { Ing::Command.new dummy_command_class }

      it "should have command_meth == :call" do
        assert_equal :call, subject.command_meth
      end

      it "should have options == {}" do
        assert_equal Hash.new, subject.options
      end

      it "should have args == []" do
        assert_equal [], subject.args
      end
    end

    describe "when command class and options hash passed" do
      subject       { Ing::Command.new dummy_command_class, options }
      let(:options) { {:one => 1, :two => 2} }

      it "should have command_meth == :call" do
        assert_equal :call, subject.command_meth
      end

      it "should have options == passed options" do
        assert_equal options, subject.options
      end

      it "should have args == []" do
        assert_equal [], subject.args
      end
    end

    describe "when command class and method passed" do
      subject    { Ing::Command.new dummy_command_class, meth, *args }
      let(:meth) { "dummy" }
      let(:args) { ["one", "two"] }

      it "should have command_meth == passed method" do
        assert_equal meth.to_sym, subject.command_meth
      end

      it "should have options == {}" do
        assert_equal Hash.new, subject.options
      end

      it "should have args == remaining args" do
        assert_equal args, subject.args
      end
    end

    describe "when command proc and method passed" do
      subject    { Ing::Command.new dummy_command_proc, meth, *args }
      let(:meth) { "dummy" }
      let(:args) { ["one", "two"] }

      it "should have command_meth == passed method" do
        assert_equal meth.to_sym, subject.command_meth
      end

      it "should have options == {}" do
        assert_equal Hash.new, subject.options
      end

      it "should have args == remaining args" do
        assert_equal args, subject.args
      end
    end

    describe "when command class and non-public-instance-method arg passed" do
      subject    { Ing::Command.new dummy_command_class, arg, *args }
      let(:arg)  { "remove_instance_variable" }
      let(:args) { ["one", "two"] }

      it "should have command_meth == :call" do
        assert_equal :call, subject.command_meth
      end

      it "should have options == {}" do
        assert_equal Hash.new, subject.options
      end

      it "should have args == all passed args" do
        assert_equal [arg] + args, subject.args
      end
    end

    describe "when command proc and non-public-method arg passed" do
      subject    { Ing::Command.new dummy_command_proc, arg, *args }
      let(:arg)  { "extended" }
      let(:args) { ["one", "two"] }

      it "should have command_meth == :call" do
        assert_equal :call, subject.command_meth
      end

      it "should have options == {}" do
        assert_equal Hash.new, subject.options
      end

      it "should have args == all passed args" do
        assert_equal [arg] + args, subject.args
      end
    end

    describe "when command class and option arg passed" do
      subject    { Ing::Command.new dummy_command_class, arg, *args }
      let(:arg)  { "--nonsense" }
      let(:args) { ["one", "two"] }

      it "should have command_meth == :call" do
        assert_equal :call, subject.command_meth
      end

      it "should have options == {}" do
        assert_equal Hash.new, subject.options
      end

      it "should have args == all passed args" do
        assert_equal [arg] + args, subject.args
      end
    end

    describe "when command proc and option arg passed" do
      subject    { Ing::Command.new dummy_command_proc, arg, *args }
      let(:arg)  { "--help" }
      let(:args) { ["one", "two"] }

      it "should have command_meth == :call" do
        assert_equal :call, subject.command_meth
      end

      it "should have options == {}" do
        assert_equal Hash.new, subject.options
      end

      it "should have args == all passed args" do
        assert_equal [arg] + args, subject.args
      end
    end

  end

  #-----------------------------------------------------------------------------
  describe "#instance" do
    subject             { Ing::Command.new command_class }
    let(:command_class) { dummy_command_class }

    it "should return an instance of the passed class" do
      assert_kind_of command_class, subject.instance
    end

    describe "and passed class defines specify_options" do

      def mock_parser_given(args, ret={})
        parser = MiniTest::Mock.new
        parser.expect(:parser,nil)
        parser.expect(:"parse!",ret,[args])
        parserclass = MiniTest::Mock.new
        parserclass.expect(:new, parser)
        parserclass
      end

      def expecting_parser_given(args, ret={})
        Ing::Command.stub(:parser, mock_parser_given(args, ret)) do |stub|
          #puts stub.parser.inspect
          yield
        end
      end

# These don't work because `parse_options!` is indivisible from `instance`
# and you need an unstubbed :command_class for `parse_options!`
#
#      def mock_command_constructor_given(opts)
#        cmd = MiniTest::Mock.new
#        cmd.expect(:new,nil,[opts])
#        cmd
#      end
#
#      def expecting_command_constructor_given(ing_cmd, opts)
#        ing_cmd.stub(:command_class,
#                     mock_command_constructor_given(opts)) do |stub|
#          #puts stub.command_class.inspect
#          yield
#        end
#      end

      subject { Ing::Command.new command_class, *args }
      let(:command_class) { dummy_command_class_with_specify_options }
      let(:args)          { ["one", "two", "three"] }

      it "should interact with parser as expected" do
        expecting_parser_given(args) do
          subject.instance
        end
      end

      describe "and an option hash is passed as the last arg" do
        subject              { Ing::Command.new command_class, *args, options }
        let(:command_class)  { dummy_command_class_with_specify_options }
        let(:args)           { ["--two", "2", "--four", "4", "--three", "1"] }
        let(:options)        { {:one => 1, :two => 2, :three => 3} }
        let(:parsed_options) { {:two => 2, :four => 4, :three => 1} }

        it "should merge passed options into the options parsed from other args" do
          expecting_parser_given(args, parsed_options) do
            merged_options = parsed_options.merge(options)
            it = subject.instance
            # note dummy.options returns what it was passed in constructor
            assert_equal merged_options, it.options
          end
        end

      end

    end

  end

  #-----------------------------------------------------------------------------
  describe "#execute" do

    def mock_instance_sent(meth, args=[])
      inst = MiniTest::Mock.new
      inst.expect(:send, nil, [meth] + args)
      inst
    end

    def expecting_instance_sent(ing_cmd, meth, args=[])
      ing_cmd.stub(:instance, mock_instance_sent(meth, args)) do |stub|
        #puts stub.instance.inspect
        yield
      end
    end

    describe "when only command class passed" do
      subject { Ing::Command.new dummy_command_class }

      it "instance should receive :call and no args" do
        subject.instance
        expecting_instance_sent(subject, :call) do
          subject.execute
        end
      end

    end

    describe "when command class and options hash passed" do
      subject       { Ing::Command.new dummy_command_class, options }
      let(:options) { {:one => 1, :two => 2} }

      it "instance should receive :call and no args" do
        subject.instance
        expecting_instance_sent(subject, :call) do
          subject.execute
        end
      end

    end

    describe "when command class and method passed with args" do
      subject    { Ing::Command.new dummy_command_class, meth, *args }
      let(:meth) { "dummy" }
      let(:args) { ["one", "two"] }

      it "instance should receive passed method and args" do
        subject.instance
        expecting_instance_sent(subject, meth.to_sym, args) do
          subject.execute
        end
      end

    end

    describe "when command proc and method passed" do
      subject    { Ing::Command.new dummy_command_proc, meth, *args }
      let(:meth) { "dummy" }
      let(:args) { ["one", "two"] }

      it "instance should receive passed method, args, and empty options hash" do
        subject.instance
        expecting_instance_sent(subject, meth.to_sym, args + [{}]) do
          subject.execute
        end
      end

    end

    describe "when command proc and options hash passed" do
      subject       { Ing::Command.new dummy_command_proc, options }
      let(:options) { {:one => 1, :two => 2} }

      it "instance should receive :call and passed options hash" do
        subject.instance
        expecting_instance_sent(subject, :call, [options]) do
          subject.execute
        end
      end

    end

  end

end


text:
#!/usr/bin/env node

var sys = require('util')
  , fs = require('fs')
  , sh = require('shelljs')
  , extend = require('extend')
  , exec = require('child_process').exec
  , lessWatchCompilerUtils = require('./lib/lessWatchCompilerUtils.js')
  , cwd = sh.pwd()
  , data
  , mainFilePath = undefined;

// See if folder cwd contains
fs.exists(cwd+'/less-watch-compiler.config.json', function(exists) {
  if (exists) {
    data = fs.readFileSync(cwd+'/less-watch-compiler.config.json')
    var customConfig = JSON.parse(data);
    extend(true, lessWatchCompilerUtils.config, customConfig)
  }
  init();
});

// Check to see if we have the correct number of arguments
var argvs = process.argv.slice(2);

function init(){
  // Here's where we setup the watch function
  try{
    lessWatchCompilerUtils.config.watchFolder = argvs[0] || lessWatchCompilerUtils.config.defaults.watchFolder;
    lessWatchCompilerUtils.config.outputFolder = argvs[1] || lessWatchCompilerUtils.config.defaults.outputFolder;
    lessWatchCompilerUtils.config.mainFile = argvs[2] || lessWatchCompilerUtils.config.defaults.mainFile;
  }
  catch(e){}

  if (argvs[0] == "test-only") return;

  // console.log("Watch Folder: "+lessWatchCompilerUtils.config.watchFolder)
  // console.log("Output Folder: "+lessWatchCompilerUtils.config.outputFolder)
  /*
    3rd parameter is optional, but once you define it, then we will just compile
    the main and generate as "{main_file_name}.css". All the files that has been
    referenced from the main one will be minified into it.
    Assuming the 3rd is "main.less"
    - input folder: src
    src
        main.less (import aux.less)
        aux.less
    - output folder: dist
    dist
        main.css

    Otherwise, it will behave as previously:
    Assuming the 3rd is empty
    - input folder: src
    src
        main.less (import aux.less)
        aux.less
    - output folder: dist
    dist
        main.css
        aux.css
  */
  if ( !lessWatchCompilerUtils.config.watchFolder || !lessWatchCompilerUtils.config.outputFolder ){
    console.log('Missing arguments. Example:');
    console.log('\tnode less-watch-compiler.js FOLDER_TO_WATCH FOLDER_TO_OUTPUT');
    console.log('\tExample 1: To watch all files under the folder "less" and compile all into a folder "css".');
    console.log('\t\t less-watch-compiler less css');
    process.exit(1);
  }
  if (lessWatchCompilerUtils.config.mainFile) {
      mainFilePath = [lessWatchCompilerUtils.config.watchFolder, lessWatchCompilerUtils.config.mainFile].join('/');
  }
  console.log('Watching directory for file changes.');
  console.log('');
  lessWatchCompilerUtils.watchTree(
    lessWatchCompilerUtils.config.watchFolder,
    {interval: 200, ignoreDotFiles: true, filter:lessWatchCompilerUtils.filterFiles},
    function (f, curr, prev) {
      if (typeof f == 'object' && prev === null && curr === null) {
        // Finished walking the tree
        return;
      } else if (curr.nlink === 0) {
        // f was removed
        console.log(f +' was removed.')
      } else {
        // f is a new file or changed
        console.log('The file: ' + f + ' was changed. Recompiling CSS at ' + lessWatchCompilerUtils.getDateTime());
        lessWatchCompilerUtils.compileCSS(mainFilePath || f);
      }
    },
    function(f){
       lessWatchCompilerUtils.compileCSS(mainFilePath || f);
    }
  );
}