text:
package redis.commands

import redis._
import scala.concurrent.Future
import redis.api.strings._
import redis.api._

trait Strings extends Request {

  def append[V: ByteStringSerializer](key: String, value: V): Future[Long] =
    send(Append(key, value))

  def bitcount(key: String): Future[Long] =
    send(Bitcount(key))

  def bitcount(key: String, start: Long, end: Long): Future[Long] =
    send(BitcountRange(key, start, end))

  def bitopAND(destkey: String, keys: String*): Future[Long] =
    bitop(AND, destkey, keys: _*)

  def bitopOR(destkey: String, keys: String*): Future[Long] =
    bitop(OR, destkey, keys: _*)

  def bitopXOR(destkey: String, keys: String*): Future[Long] =
    bitop(XOR, destkey, keys: _*)

  def bitopNOT(destkey: String, key: String): Future[Long] =
    bitop(NOT, destkey, key)

  def bitop(operation: BitOperator, destkey: String, keys: String*): Future[Long] =
    send(Bitop(operation, destkey, keys))

  def bitpos(key: String, bit: Long, start: Long = 0, end: Long = -1): Future[Long] =
    send(Bitpos(key, bit, start, end))

  def decr(key: String): Future[Long] =
    send(Decr(key))

  def decrby(key: String, decrement: Long): Future[Long] =
    send(Decrby(key, decrement))

  def get[R: ByteStringDeserializer](key: String): Future[Option[R]] =
    send(Get(key))

  def getbit(key: String, offset: Long): Future[Boolean] =
    send(Getbit(key, offset))

  def getrange[R: ByteStringDeserializer](key: String, start: Long, end: Long): Future[Option[R]] =
    send(Getrange(key, start, end))

  def getset[V: ByteStringSerializer, R: ByteStringDeserializer](key: String, value: V): Future[Option[R]] =
    send(Getset(key, value))

  def incr(key: String): Future[Long] =
    send(Incr(key))

  def incrby(key: String, increment: Long): Future[Long] =
    send(Incrby(key, increment))

  def incrbyfloat(key: String, increment: Double): Future[Option[Double]] =
    send(Incrbyfloat(key, increment))

  def mget[R: ByteStringDeserializer](keys: String*): Future[Seq[Option[R]]] =
    send(Mget(keys))

  def mset[V: ByteStringSerializer](keysValues: Map[String, V]): Future[Boolean] =
    send(Mset(keysValues))

  def msetnx[V: ByteStringSerializer](keysValues: Map[String, V]): Future[Boolean] =
    send(Msetnx(keysValues))

  def psetex[V: ByteStringSerializer](key: String, milliseconds: Long, value: V): Future[Boolean] =
    send(Psetex(key, milliseconds, value))

  def set[V: ByteStringSerializer](key: String, value: V,
                                   exSeconds: Option[Long] = None,
                                   pxMilliseconds: Option[Long] = None,
                                   NX: Boolean = false,
                                   XX: Boolean = false): Future[Boolean] = {
    send(Set(key, value, exSeconds, pxMilliseconds, NX, XX))
  }

  def setbit(key: String, offset: Long, value: Boolean): Future[Boolean] =
    send(Setbit(key, offset, value))

  def setex[V: ByteStringSerializer](key: String, seconds: Long, value: V): Future[Boolean] =
    send(Setex(key, seconds, value))

  def setnx[V: ByteStringSerializer](key: String, value: V): Future[Boolean] =
    send(Setnx(key, value))

  def setrange[V: ByteStringSerializer](key: String, offset: Long, value: V): Future[Long] =
    send(Setrange(key, offset, value))

  def strlen(key: String): Future[Long] =
    send(Strlen(key))

}


text:
namespace TraktApiSharp.Requests.Base
{
    using Interfaces.Base;
    using System.Net.Http;

    internal abstract class ADeleteRequest : ARequest, IDeleteRequest
    {
        public override AuthorizationRequirement AuthorizationRequirement => AuthorizationRequirement.Required;

        public sealed override HttpMethod Method => HttpMethod.Delete;
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Snippets;
using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets;
using Microsoft.VisualStudio.Shell;

namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets
{
    // HACK: The Export attribute (as ISnippetInfoService) is used by EditorTestApp to create this
    // SnippetInfoService on the UI thread.
    [Export(typeof(ISnippetInfoService))]
    [ExportLanguageService(typeof(ISnippetInfoService), LanguageNames.CSharp), Shared]
    internal class CSharpSnippetInfoService : AbstractSnippetInfoService
    {
        // #region and #endregion when appears in the completion list as snippets
        // we should format the snippet on commit.
        private readonly ISet<string> _formatTriggeringSnippets = new HashSet<string>(new string[] { "#region", "#endregion" });

        [ImportingConstructor]
        [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
        public CSharpSnippetInfoService(
            IThreadingContext threadingContext,
            SVsServiceProvider serviceProvider,
            IAsynchronousOperationListenerProvider listenerProvider)
            : base(threadingContext, serviceProvider, Guids.CSharpLanguageServiceId, listenerProvider)
        {
        }

        public override bool ShouldFormatSnippet(SnippetInfo snippetInfo)
            => _formatTriggeringSnippets.Contains(snippetInfo.Shortcut);
    }
}


text:
public class Main {
  public static void main(String[] args) {
    assertEquals(0x80000000, doShiftInt(1));
    assertEquals(0x8000000000000000L, doShiftLong(1L));
  }

  public static int doShiftInt(int value) {
    return value << 0xFFFF;
  }

  public static long doShiftLong(long value) {
    return value << 0xFFFF;
  }

  public static void assertEquals(int a, int b) {
    if (a != b) {
      throw new Error("Expected " + a + ", got " + b);
    }
  }

  public static void assertEquals(long a, long b) {
    if (a != b) {
      throw new Error("Expected " + a + ", got " + b);
    }
  }
}


text:
package nl.nn.adapterframework.pipes;

import nl.nn.adapterframework.configuration.ConfigurationException;
import nl.nn.adapterframework.configuration.ConfigurationWarnings;

/**
 * Extension of the {@link XmlSwitch XmlSwitch}: an xml switch that can use parameters. The parameters
 * will be used to set them on the transformer instance.
 * @author Johan Verrips
 * @version $Id$
 * @deprecated please use plain XmlSwitch, that now supports parameters too (since 4.2d)
 */
public class XmlParamSwitch extends XmlSwitch {

	public void configure() throws ConfigurationException {
		ConfigurationWarnings configWarnings = ConfigurationWarnings.getInstance();
		String msg = getLogPrefix(null)+"The class ["+getClass().getName()+"] has been deprecated. Please change to ["+getClass().getSuperclass().getName()+"]";
		configWarnings.add(log, msg);
		super.configure();
	}
}


text:
package net.sf.antcontrib.cpptasks;
import net.sf.antcontrib.cpptasks.arm.ADSCCompiler;
import net.sf.antcontrib.cpptasks.borland.BorlandCCompiler;
import net.sf.antcontrib.cpptasks.borland.BorlandResourceCompiler;
import net.sf.antcontrib.cpptasks.compaq.CompaqVisualFortranCompiler;
import net.sf.antcontrib.cpptasks.compiler.Compiler;
import net.sf.antcontrib.cpptasks.devstudio.DevStudioCCompiler;
import net.sf.antcontrib.cpptasks.devstudio.DevStudio2005CCompiler;
import net.sf.antcontrib.cpptasks.devstudio.DevStudioMIDLCompiler;
import net.sf.antcontrib.cpptasks.devstudio.DevStudioResourceCompiler;
import net.sf.antcontrib.cpptasks.gcc.GccCCompiler;
import net.sf.antcontrib.cpptasks.gcc.WindresResourceCompiler;
import net.sf.antcontrib.cpptasks.hp.aCCCompiler;
import net.sf.antcontrib.cpptasks.ibm.VisualAgeCCompiler;
import net.sf.antcontrib.cpptasks.intel.IntelLinux32CCompiler;
import net.sf.antcontrib.cpptasks.intel.IntelLinux64CCompiler;
import net.sf.antcontrib.cpptasks.intel.IntelWin32CCompiler;
import net.sf.antcontrib.cpptasks.intel.IntelWin64CCompiler;
import net.sf.antcontrib.cpptasks.mozilla.XpidlCompiler;
import net.sf.antcontrib.cpptasks.os390.OS390CCompiler;
import net.sf.antcontrib.cpptasks.os400.IccCompiler;
import net.sf.antcontrib.cpptasks.sun.C89CCompiler;
import net.sf.antcontrib.cpptasks.sun.ForteCCCompiler;
import net.sf.antcontrib.cpptasks.ti.ClxxCCompiler;
import net.sf.antcontrib.cpptasks.trolltech.MetaObjectCompiler;
import net.sf.antcontrib.cpptasks.trolltech.UserInterfaceCompiler;
import net.sf.antcontrib.cpptasks.openwatcom.OpenWatcomCCompiler;
import net.sf.antcontrib.cpptasks.openwatcom.OpenWatcomFortranCompiler;

import org.apache.tools.ant.types.EnumeratedAttribute;
/**
 * Enumeration of supported compilers
 *
 *

Supported compilers

 *

 * gcc (default)
 * GCC C++ compiler
 *

 *

 * g++
 * GCC C++ compiler
 *

 *

 * c++
 * GCC C++ compiler
 *

 *

 * g77
 * GNU FORTRAN compiler
 *

 *

 * msvc
 * Microsoft Visual C++
 *

 *

 * msvc8
 * Microsoft Visual C++ 8
 *

 *

 * bcc
 * Borland C++ Compiler
 *

 *

 * msrc
 * Microsoft Resource Compiler
 *

 *

 * brc
 * Borland Resource Compiler
 *

 *

 * df
 * Compaq Visual Fortran Compiler
 *

 *

 * midl
 * Microsoft MIDL Compiler
 *

 *

 * icl
 * Intel C++ compiler for Windows (IA-32)
 *

 *

 * ecl
 * Intel C++ compiler for Windows (IA-64)
 *

 *

 * icc
 * Intel C++ compiler for Linux (IA-32)
 *

 *

 * ecc
 * Intel C++ compiler for Linux (IA-64)
 *

 *

 * CC
 * Sun ONE C++ compiler
 *

 *

 * aCC
 * HP aC++ C++ Compiler
 *

 *

 * os390
 * OS390 C Compiler
 *

 *

 * os400
 * Icc Compiler
 *

 *

 * sunc89
 * Sun C89 C Compiler
 *

 *

 * xlC
 * VisualAge C Compiler
 *

 *

 * cl6x
 * TI TMS320C6000 Optimizing Compiler
 *

 *

 * cl55
 * TI TMS320C55x Optimizing C/C++ Compiler
 *

 *

 * armcpp
 * ARM 32-bit C++ compiler
 *

 *

 * armcc
 * ARM 32-bit C compiler
 *

 *

 * tcpp
 * ARM 16-bit C++ compiler
 *

 *

 * tcc
 * ARM 16-bit C compiler
 *

 *      *

 * uic
 * Qt user interface compiler
 *

 *

 * moc
 * Qt meta-object compiler
 *

 *

 * xpidl
 * Mozilla xpidl compiler (creates .h and .xpt files).
 *

 *

 * wcl
 * OpenWatcom C/C++ compiler (experimental)
 *

 *

 * wfl
 * OpenWatcom FORTRAN compiler (experimental)
 *

 *

 * windres
 * GNU windres resource compiler
 *

 *

 *
 * @author Curt Arnold
 *
 */
public class CompilerEnum extends EnumeratedAttribute {
    private final static ProcessorEnumValue[] compilers = new ProcessorEnumValue[]{
            new ProcessorEnumValue("gcc", GccCCompiler.getInstance()),
            new ProcessorEnumValue("g++", GccCCompiler.getGppInstance()),
            new ProcessorEnumValue("c++", GccCCompiler.getCppInstance()),
            new ProcessorEnumValue("g77", GccCCompiler.getG77Instance()),
            new ProcessorEnumValue("msvc", DevStudioCCompiler.getInstance()),
            new ProcessorEnumValue("msvc8", DevStudio2005CCompiler.getInstance()),
            new ProcessorEnumValue("bcc", BorlandCCompiler.getInstance()),
            new ProcessorEnumValue("msrc", DevStudioResourceCompiler
                    .getInstance()),
            new ProcessorEnumValue("brc", BorlandResourceCompiler.getInstance()),
            new ProcessorEnumValue("df", CompaqVisualFortranCompiler
                    .getInstance()),
            new ProcessorEnumValue("midl", DevStudioMIDLCompiler.getInstance()),
            new ProcessorEnumValue("icl", IntelWin32CCompiler.getInstance()),
            new ProcessorEnumValue("ecl", IntelWin64CCompiler.getInstance()),
            new ProcessorEnumValue("icc", IntelLinux32CCompiler.getInstance()),
            new ProcessorEnumValue("ecc", IntelLinux64CCompiler.getInstance()),
            new ProcessorEnumValue("CC", ForteCCCompiler.getInstance()),
            new ProcessorEnumValue("aCC", aCCCompiler.getInstance()),
            new ProcessorEnumValue("os390", OS390CCompiler.getInstance()),
            new ProcessorEnumValue("os400", IccCompiler.getInstance()),
            new ProcessorEnumValue("sunc89", C89CCompiler.getInstance()),
            new ProcessorEnumValue("xlC", VisualAgeCCompiler.getInstance()),
            new ProcessorEnumValue("cl6x", ClxxCCompiler.getCl6xInstance()),
            new ProcessorEnumValue("cl55", ClxxCCompiler.getCl55Instance()),
            new ProcessorEnumValue("armcc", ADSCCompiler.getArmCC()),
            new ProcessorEnumValue("armcpp", ADSCCompiler.getArmCpp()),
            new ProcessorEnumValue("tcc", ADSCCompiler.getThumbCC()),
            new ProcessorEnumValue("tcpp", ADSCCompiler.getThumbCpp()),
            // GCC Cross Compilers
            new ProcessorEnumValue(
                    "sparc-sun-solaris2-gcc",
                    net.sf.antcontrib.cpptasks.gcc.cross.sparc_sun_solaris2.GccCCompiler
                            .getInstance()),
            new ProcessorEnumValue(
                    "sparc-sun-solaris2-g++",
                    net.sf.antcontrib.cpptasks.gcc.cross.sparc_sun_solaris2.GccCCompiler
                            .getGppInstance()),
            new ProcessorEnumValue(
                    "sparc-sun-solaris2-c++",
                    net.sf.antcontrib.cpptasks.gcc.cross.sparc_sun_solaris2.GccCCompiler
                            .getCppInstance()),
            new ProcessorEnumValue(
                    "sparc-sun-solaris2-g77",
                    net.sf.antcontrib.cpptasks.gcc.cross.sparc_sun_solaris2.GccCCompiler
                            .getG77Instance()),
            // GCC Cross Compilers
            new ProcessorEnumValue("gcc-cross",
                    net.sf.antcontrib.cpptasks.gcc.cross.GccCCompiler
                            .getInstance()),
            new ProcessorEnumValue("g++-cross",
                    net.sf.antcontrib.cpptasks.gcc.cross.GccCCompiler
                            .getGppInstance()),
            new ProcessorEnumValue("c++-cross",
                    net.sf.antcontrib.cpptasks.gcc.cross.GccCCompiler
                            .getCppInstance()),
            new ProcessorEnumValue("g77-cross",
                    net.sf.antcontrib.cpptasks.gcc.cross.GccCCompiler
                            .getG77Instance()),
			new ProcessorEnumValue("uic", UserInterfaceCompiler.getInstance()),
			new ProcessorEnumValue("moc", MetaObjectCompiler.getInstance()),
			new ProcessorEnumValue("xpidl", XpidlCompiler.getInstance()),
			new ProcessorEnumValue("wcl", OpenWatcomCCompiler.getInstance()),
			new ProcessorEnumValue("wfl", OpenWatcomFortranCompiler.getInstance()),
            new ProcessorEnumValue("windres", WindresResourceCompiler.getInstance())
                            };
    public Compiler getCompiler() {
        return (Compiler) compilers[getIndex()].getProcessor();
    }
    public String[] getValues() {
        return ProcessorEnumValue.getValues(compilers);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/messagesLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/selectableItemBackground"
    android:clickable="true"
    android:focusable="true"
    android:paddingBottom="@dimen/medium_margin"
    android:paddingLeft="@dimen/medium_margin"
    android:paddingRight="@dimen/medium_margin"
    android:paddingTop="@dimen/medium_margin">

    <ImageView
        android:id="@+id/userImage"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:backgroundTint="@color/colorPrimaryDark"
        android:contentDescription="@string/profile_picture"
        android:src="@drawable/ic_account_circle_black_24dp" />

    <TextView
        android:id="@+id/userStatusBack"
        android:layout_width="16dp"
        android:layout_height="16dp"
        android:layout_alignBottom="@+id/userImage"
        android:layout_alignRight="@+id/userImage"
        android:background="@drawable/circle_user_connection_status" />

    <TextView
        android:id="@+id/userStatus"
        android:layout_width="12dp"
        android:layout_height="12dp"
        android:layout_alignBottom="@+id/userImage"
        android:layout_alignRight="@+id/userImage"
        android:layout_marginBottom="2dp"
        android:layout_marginRight="2dp"
        android:background="@drawable/circle_user_connection_status" />

    <TextView
        android:id="@+id/username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/default_margin"
        android:text="Username"
        android:textSize="20sp"
        android:textStyle="bold"
        android:layout_centerVertical="true"
        android:layout_toEndOf="@+id/userImage" />

</RelativeLayout>


text:
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_TEXT_DATE_TIME_FORMAT_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_TEXT_DATE_TIME_FORMAT_H_

#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"

namespace blink {

// DateTimeFormat parses date time format defined in Unicode Technical
// standard 35, Locale Data Markup Language (LDML)[1].
// [1] https://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns
class PLATFORM_EXPORT DateTimeFormat {
  STATIC_ONLY(DateTimeFormat);

 public:
  enum FieldType {
    kFieldTypeInvalid,
    kFieldTypeLiteral,

    // Era: AD
    kFieldTypeEra = 'G',

    // Year: 1996
    kFieldTypeYear = 'y',
    kFieldTypeYearOfWeekOfYear = 'Y',
    kFieldTypeExtendedYear = 'u',
    kFieldTypeYearCyclicName = 'U',
    kFieldTypeYearRelatedGregorian = 'r',

    // Quater: Q2
    kFieldTypeQuater = 'Q',
    kFieldTypeQuaterStandAlone = 'q',

    // Month: September
    kFieldTypeMonth = 'M',
    kFieldTypeMonthStandAlone = 'L',

    // Week: 42
    kFieldTypeWeekOfYear = 'w',
    kFieldTypeWeekOfMonth = 'W',

    // Day: 12
    kFieldTypeDayOfMonth = 'd',
    kFieldTypeDayOfYear = 'D',
    kFieldTypeDayOfWeekInMonth = 'F',
    kFieldTypeModifiedJulianDay = 'g',

    // Week Day: Tuesday
    kFieldTypeDayOfWeek = 'E',
    kFieldTypeLocalDayOfWeek = 'e',
    kFieldTypeLocalDayOfWeekStandAlon = 'c',

    // Period: AM or PM
    kFieldTypePeriod = 'a',
    kFieldTypePeriodAmPmNoonMidnight = 'b',
    kFieldTypePeriodFlexible = 'B',

    // Hour: 7
    kFieldTypeHour12 = 'h',
    kFieldTypeHour23 = 'H',
    kFieldTypeHour11 = 'K',
    kFieldTypeHour24 = 'k',

    // Minute: 59
    kFieldTypeMinute = 'm',

    // Second: 12
    kFieldTypeSecond = 's',
    kFieldTypeFractionalSecond = 'S',
    kFieldTypeMillisecondsInDay = 'A',

    // Zone: PDT
    kFieldTypeZone = 'z',
    kFieldTypeZoneLocalized = 'O',
    kFieldTypeNonLocationZone = 'v',
    kFieldTypeZoneId = 'V',
    kFieldTypeRFC822Zone = 'Z',
    kFieldTypeZoneIso8601Z = 'X',
    kFieldTypeZoneIso8601 = 'x',
  };

  class TokenHandler {
    STACK_ALLOCATED();

   public:
    TokenHandler() = default;
    TokenHandler(const TokenHandler&) = delete;
    TokenHandler& operator=(const TokenHandler&) = delete;
    virtual ~TokenHandler() = default;
    virtual void VisitField(FieldType, int number_of_pattern_characters) = 0;
    virtual void VisitLiteral(const String&) = 0;
  };

  // Returns true if succeeded, false if failed.
  static bool Parse(const String&, TokenHandler&);
  static void QuoteAndappend(const String&, StringBuilder&);
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_TEXT_DATE_TIME_FORMAT_H_


text:
_specview-tutorial

Specview tutorial
=======================================

Presentation
------------

Specview is a tool for 1-D spectral visualization and analysis of astronomical spectra.
It is written in Java and can be run anywhere Java is supported.
Specview is capable of reading all the Hubble Space Telescope spectral data formats, as well as data from several other instruments (such as IUE, FUSE, ISO, FORS and SDSS),
preview spectra from MAST, and data from generic FITS and ASCII tables.
It can also read data from Virtual Observatory servers, and read and write spectrogram data in Virtual Observatory SED format.
It can also read files in the SPC Galactic format used in the chemistry field.

The complete list of supported spectra is available `here <http://specview.stsci.edu/javahelp/Ingest.html#Supported_file_formats>`_

Installation
------------

The application is available for the following operating systems :

- `OSX <http://specview.stsci.edu/download/spv_macos_2_17_4.dmg>`_
- `Linux/Unix <http://specview.stsci.edu/download/spv_unix_2_17_4.sh>`_
- `Windows <http://specview.stsci.edu/download/spv_windows_2_17_4.exe>`_

Once you have downloaded and installed the application, launch it and the main window will appear :

.. image:: images/main_frame.png

A network connection is required for the following tutorial to work.

Tutorial description
--------------------

In this tutorial, we will learn how to identify lines in Specview using the VAMDC infrastructure and how to exchange data with a Virtual Observatory protocol called SAMP.
The example is about the identification of absorption lines produced by diffuse interstellar clouds on the line of sight towards a bright Be Star.

Task 1 : Looking for a spectrum using Simple Spectra Access (SSA)
-----------------------------------------------------------------

Open the "File" -> "Read for VO" Menu.

Look for `FUSE <http://archive.stsci.edu/fuse/>`_ spectra available for HD 110432 (use the service providing UV and EUV data), find and open the spectrum.
You will have to use the name resolver to find the object position (either the `SIMBAD <http://simbad.u-strasbg.fr/simbad/>`_ CADC or ESO one).

There are 2 FUSE services, we will look for data into thone whose description is "Far Ultraviolet Spectroscopic Explorer (#EUV#UV#)"
There should be only one available spectrum, below is the result you should get :

.. image:: images/fuse_spectrum.png

Task 2 : Looking for available lines
------------------------------------

Once the spectrum has been loaded, zoom on the area between 1073 and 1083 Angstroms. We will work on 2 H2 absorption lines whose positions are 1074.3 and 1081.26 Angstroms respectively.

Click the "Line IDs" button to open the search interface.
Here there you can either look for data in local files contained in a Specview directory. Or you can
search in databases that implemented `VAMDC standards <http://www.vamdc.eu/documents/standards/#data-access-protocol-query-language-and-dictionaries>`_ to expose their data.

We will only use VAMDC data in this tutorial so you can deselect the "Use local" checkbox.

.. image:: images/line_gui.png

You must now configure the data sources in which you want to look for data. Click on the configuration button in the upper left corner of the window.

Here you will find a complete list of all the databases available in the VAMDC architecture.
We are studying a FUSE spectrum showing strong H2 absorption lines in the far UV due to a diffuse interstellar cloud between the star HD 110432 and us.
So we want to select a database containing H2 lines in the far UV.
Select the database called "Spectroscopy of Atoms and Molecules" (`Sesam <http://sesam.obspm.fr>`_).
The choice you have made in this window will be saved so the next time you launch Specview, you won't have to configure it again.

Look for data available for H2 with a wavelength between 1073 and 1075 Angstroms.There are a lot of available lines in this interval.

.. image:: images/lines.png

However it is possible to get something more precise by specifying a value for the lower level energy.
In diffuse interstellar clouds, except for specific conditions, the temperature is relatively cool (60 K) so most of the H2 is in its first ro-vibrationnal levels.
We are going to select only line from levels lower or equal to v=0 J=7. We can restrict our research to a temperature below 6000K, which leads to a lower level energy between 0 and 4000 cm-1.

Do the same request with a lower level energy comprised in this interval.

.. image:: images/lines_1074_withlowerenergy.png

Now the lines we were looking for are way easier to find. Most of the lines we found in Sesam corresponds exactly to absorption lines on the spectrum.
You can notice a total absorption between 1076.9 and 1077.7 Angstroms and between 1078.84 and 1079.2 Angstroms indicating that numerous transitions occurs at those wavelength.

The information concerning the quantum numbers of the levels are not yet available in Specview. But you can look for those transitions on the `Sesam website <http://sesam.obspm.fr>`_.

Once everything has been plotted, you should get the following spectrum :

.. image:: images/result_hd110432.png

Here is the list of identified levels :

+------------+-------------+-----------------------+
|Lower Level | Upper Level | Wavelength (Angstroms)|
+============+=============+=======================+
| X v=0 J=4  |  B v=3 J=3  |        1074.31        |
+------------+-------------+-----------------------+
| X v=0 J=5  |  B v=3 J=6  |        1075.24        |
+------------+-------------+-----------------------+
| X v=0 J=0  |  B v=2 J=1  |        1077.14        |
+------------+-------------+-----------------------+
| X v=0 J=1  |  B v=2 J=2  |        1077.70        |
+------------+-------------+-----------------------+
| X v=0 J=1  |  B v=2 J=0  |        1078.92        |
+------------+-------------+-----------------------+
| X v=0 J=2  |  B v=2 J=3  |        1079.22        |
+------------+-------------+-----------------------+
| X v=0 J=2  |  B v=2 J=1  |        1081.26        |
+------------+-------------+-----------------------+
| X v=0 J=3  |  B v=2 J=4  |        1081.71        |
+------------+-------------+-----------------------+

Task 3 : Using Simple Application Messaging Protocol in Specview
----------------------------------------------------------------

SAMP, the `Simple Application Messaging Protocol <http://www.ivoa.net/documents/SAMP/>`_, is a standard for allowing software tools to exchange control and data information,
thus facilitating tool interoperability, and so allowing users to treat separately developed applications as an integrated suite.
An example of an operation that SAMP might facilitate is passing a source catalogue from one GUI application to another,
and subsequently allowing sources marked by the user in one of those applications to be visible as such in the other.

To exchange data between applications with Samp, a hub is required. A hub is a process that will listen to Samp messages sent by all the Samp enabled applications
and redirect them to the correct target.

During this tutorial we will look for a spectrum on a website and send it to Specview using the Samp protocol.
The spectrum will be find on the `Auroral Planetary Imaging and Spectroscopy website <http://lesia.obspm.fr/apis/>`_ (APIS).
This database contains various types of data derived from spectro-imaging auroral observations of the outer planets (Jupiter, Saturn and Uranus) acquired by the Hubble Space Telescope in the Far-UV.

To look for data in the APIs database, a login and a password are necessary. They will be provided during the session.

Click on "Search for data" and enter the login/password. You will arrive on this page :

.. image:: images/apis.png

Here, look for available spectroscopic data for Jupiter. You will get a list of observations. For each one there will be either an image, that you can send to `Aladin <http://aladin.u-strasbg.fr/>`_ and a spectrum
that you can send to Specview.

When Specview is started, a Samp Hub is automatically launched if none is currently running. If there is already one, it will simply connect to it.

Let's choose the following observation :

- Target : Jupiter
- Start date : 1997-07-04
- Start time : 09:31:47
- Int. time : 700.19613 s
- Instrument : HST / STIS
- Obs. type: SPECTROSCOPIC
- Grating / slit :  G140L / 52X0.5
- Dataset : o43ba2h4q

Below is an example of how to interpret APIs 2D spectra for Saturn. The slit receives photons from all the planet diameter.
We can see that Lyman alpha can be found everywhere. Then various other emission lines can be seen on the southern aurora.

.. image:: images/apis_saturne.png

Click on "Display with Specview" under the original data. A message will ask you to authorize the connection, choose "Yes".
The following window will appear, asking you how to integrate the spectrum.
5 about center means ± 5 lines from the center of the 2D spectrum y axis.
1 and 1201 are the first and last lines along the y axis.

.. image::  images/apis_samp_window.png

Click on the "Go" button on the "All lines" line. You will get the following spectrum :

.. image:: images/apis_jupiter.png


text:
module Ridley
  class SearchResource < Ridley::Resource
    class << self
      # @param [String] query_string
      #
      # @option options [String] :sort
      #   a sort string such as 'name DESC'
      # @option options [Integer] :rows
      #   how many rows to return
      # @option options [Integer] :start
      #   the result number to start from
      #
      # @return [Hash]
      def build_query(query_string, options = {})
        {}.tap do |query_opts|
          query_opts[:q]     = query_string unless query_string.nil?
          query_opts[:sort]  = options[:sort] unless options[:sort].nil?
          query_opts[:rows]  = options[:rows] unless options[:rows].nil?
          query_opts[:start] = options[:start] unless options[:start].nil?
        end
      end

      # Builds and returns a query parameter string for the search API
      #
      # @param [String] query_string
      #
      # @option options [String] :sort
      #   a sort string such as 'name DESC'
      # @option options [Integer] :rows
      #   how many rows to return
      # @option options [Integer] :start
      #   the result number to start from
      #
      # @example
      #   build_param_string("*:*", rows: 5) #=> "?q=*:*&rows=5"
      #
      # @return [String]
      def build_param_string(query_string, options = {})
        query = build_query(query_string, options)
        param = "?q=#{escape(query[:q])}"
        param += "&sort=#{escape(query[:sort])}" if query[:sort]
        param += "&start=#{escape(query[:start])}" if query[:start]
        param += "&rows=#{escape(query[:rows])}" if query[:rows]
        param
      end

      # @param [#to_s] index
      #
      # @return [String]
      def query_uri(index)
        "#{resource_path}/#{index}"
      end

      private

        def escape(str)
          str && URI.escape(str.to_s)
        end
    end

    set_resource_path "search"

    # Returns an array of possible search indexes to be search on
    #
    # @param [Ridley::Client] client
    #
    # @example
    #
    #   Search.indexes(client) => [ :client, :environment, :node, :role ]
    #
    # @return [Array<String, Symbol>]
    def indexes
      request(:get, self.class.resource_path).collect { |name, _| name }
    end

    # Executes the built up query on the search's client
    #
    # @param [#to_sym, #to_s] index
    # @param [#to_s] query_string
    #
    # @option options [String] :sort
    #   a sort string such as 'name DESC'
    # @option options [Integer] :rows
    #   how many rows to return
    # @option options [Integer] :start
    #   the result number to start from
    #
    # @example
    #   Search.new(client, :role)
    #   search.run =>
    #     {
    #       total: 1,
    #       start: 0,
    #       rows: [
    #         {
    #           name: "ridley-test-role",
    #           default_attributes: {},
    #           json_class: "Chef::Role",
    #           env_run_lists: {},
    #           run_list: [],
    #           description: "a test role for Ridley!",
    #           chef_type: "role",
    #           override_attributes: {}
    #         }
    #       ]
    #     }
    #
    # @return [Array<ChefObject>, Hash]
    def run(index, query_string, resources_registry, options = {})
      query_uri = self.class.query_uri(index)
      query     = self.class.build_query(query_string, options)

      handle_response(index, resources_registry, request(:get, query_uri, query))
    end

    # Perform a partial search on the Chef server
    #
    # @param [#to_sym, #to_s] index
    # @param [#to_s] query_string
    # @param [Array] attributes
    #   an array of strings in dotted hash notation representing the attributes to return
    #
    # @option options [String] :sort
    #   a sort string such as 'name DESC'
    # @option options [Integer] :rows
    #   how many rows to return
    # @option options [Integer] :start
    #   the result number to start from
    #
    # @return [Array<ChefObject>, Hash]
    def partial(index, query_string, attributes, resources_registry, options = {})
      query_uri    = self.class.query_uri(index)
      param_string = self.class.build_param_string(query_string, options)
      body         = build_partial_body(index, attributes)

      handle_partial(index, resources_registry, request(:post, "#{query_uri}#{param_string}", JSON.generate(body)))
    end

    private

      def build_partial_body(index, attributes)
        chef_id = chef_id_for_index(index)

        Hash.new.tap do |body|
          body[chef_id] = [ chef_id ] if chef_id

          if index.to_sym == :node
            body['cloud.public_hostname'] = [ 'cloud', 'public_hostname' ]
            body['cloud.public_ip4v']     = [ 'cloud', 'public_ip4v' ]
            body['cloud.provider']        = [ 'cloud', 'provider' ]
            body['fqdn']                  = [ 'fqdn' ]
            body['ipaddress']             = [ 'ipaddress' ]
          end

          attributes.collect { |attr| body[attr] = attr.split('.') }
        end
      end

      def chef_id_for_index(index)
        chef_id = index.to_sym == :node ? Ridley::NodeObject.chef_id : nil
      end

      def handle_partial(index, registry, response)
        chef_id = chef_id_for_index(index)

        case index.to_sym
        when :node
          response[:rows].collect do |item|
            attributes = Hash.new
            item[:data].each do |key, value|
              next if key.to_s == chef_id.to_s
              attributes.deep_merge!(Hash.from_dotted_path(key, value))
            end
            registry[:node_resource].new(name: item[:data][chef_id], automatic: attributes)
          end
        else
          response[:rows]
        end
      end

      def handle_response(index, registry, response)
        case index.to_sym
        when :node
          response[:rows].collect { |row| NodeObject.new(registry[:node_resource], row) }
        when :role
          response[:rows].collect { |row| RoleObject.new(registry[:role_resource], row) }
        when :client
          response[:rows].collect { |row| ClientObject.new(registry[:client_resource], row) }
        when :environment
          response[:rows].collect { |row| EnvironmentObject.new(registry[:environment_resource], row) }
        else
          response[:rows]
        end
      end
  end
end


text:
package org.apache.ibatis.jdbc;

import static org.junit.jupiter.api.Assertions.*;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.apache.ibatis.BaseDataTest;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.hsqldb.jdbc.JDBCConnection;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;

class PooledDataSourceTest extends BaseDataTest {

  @Test
  void shouldProperlyMaintainPoolOf3ActiveAnd2IdleConnections() throws Exception {
    PooledDataSource ds = createPooledDataSource(JPETSTORE_PROPERTIES);
    try {
      runScript(ds, JPETSTORE_DDL);
      ds.setDefaultAutoCommit(false);
      ds.setDriverProperties(new Properties() {
        {
          setProperty("username", "sa");
          setProperty("password", "");
        }
      });
      ds.setPoolMaximumActiveConnections(3);
      ds.setPoolMaximumIdleConnections(2);
      ds.setPoolMaximumCheckoutTime(10000);
      ds.setPoolPingConnectionsNotUsedFor(1);
      ds.setPoolPingEnabled(true);
      ds.setPoolPingQuery("SELECT * FROM PRODUCT");
      ds.setPoolTimeToWait(10000);
      ds.setLogWriter(null);
      List<Connection> connections = new ArrayList<>();
      for (int i = 0; i < 3; i++) {
        connections.add(ds.getConnection());
      }
      assertEquals(3, ds.getPoolState().getActiveConnectionCount());
      for (Connection c : connections) {
        c.close();
      }
      assertEquals(2, ds.getPoolState().getIdleConnectionCount());
      assertEquals(4, ds.getPoolState().getRequestCount());
      assertEquals(0, ds.getPoolState().getBadConnectionCount());
      assertEquals(0, ds.getPoolState().getHadToWaitCount());
      assertEquals(0, ds.getPoolState().getAverageOverdueCheckoutTime());
      assertEquals(0, ds.getPoolState().getClaimedOverdueConnectionCount());
      assertEquals(0, ds.getPoolState().getAverageWaitTime());
      assertNotNull(ds.getPoolState().toString());
    } finally {
      ds.forceCloseAll();
    }
  }

  @Test
  void shouldNotFailCallingToStringOverAnInvalidConnection() throws Exception {
    PooledDataSource ds = createPooledDataSource(JPETSTORE_PROPERTIES);
    Connection c = ds.getConnection();
    c.close();
    c.toString();
  }

  @Test
  void ShouldReturnRealConnection() throws Exception {
    PooledDataSource ds = createPooledDataSource(JPETSTORE_PROPERTIES);
    Connection c = ds.getConnection();
    JDBCConnection realConnection = (JDBCConnection) PooledDataSource.unwrapConnection(c);
    c.close();
  }

  @Disabled("See the comments")
  @Test
  void shouldReconnectWhenServerKilledLeakedConnection() throws Exception {
    // See #748
    // Requirements:
    // 1. MySQL JDBC driver dependency.
    // 2. MySQL server instance with the following.
    //  - CREATE DATABASE `test`;
    //  - SET GLOBAL wait_timeout=3;
    // 3. Tweak the connection info below.
    final String URL = "jdbc:mysql://localhost:3306/test";
    final String USERNAME = "admin";
    final String PASSWORD = "";

    PooledDataSource ds = new PooledDataSource();
    ds.setDriver("com.mysql.jdbc.Driver");
    ds.setUrl(URL);
    ds.setUsername(USERNAME);
    ds.setPassword(PASSWORD);
    ds.setPoolMaximumActiveConnections(1);
    ds.setPoolMaximumIdleConnections(1);
    ds.setPoolTimeToWait(1000);
    ds.setPoolMaximumCheckoutTime(2000);
    ds.setPoolPingEnabled(true);
    ds.setPoolPingQuery("select 1");
    ds.setDefaultAutoCommit(true);
    // MySQL wait_timeout * 1000 or less. (unit:ms)
    ds.setPoolPingConnectionsNotUsedFor(1000);

    Connection con = ds.getConnection();
    executeQuery(con);
    // Simulate connection leak by not closing.
    // con.close();

    // Wait for disconnected from mysql...
    Thread.sleep(TimeUnit.SECONDS.toMillis(3));

    con.close();

    // Should return usable connection.
    con = ds.getConnection();
    executeQuery(con);
    con.close();
  }

  private void executeQuery(Connection con) throws SQLException {
    try (PreparedStatement st = con.prepareStatement("select 1");
         ResultSet rs = st.executeQuery()) {
      while (rs.next()) {
        assertEquals(1, rs.getInt(1));
      }
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" docBase="KITDM_LOCATION/webdav" path="/webdav">
<Realm className="org.apache.catalina.realm.LockOutRealm">
<Realm className="edu.kit.dama.tomcat.KITDMJdbcRealm"
	driverName="org.postgresql.Driver"
        connectionName="DB_USER"
        connectionPassword="DB_PASSWORD"
        connectionURL="jdbc:postgresql://DB_HOST:DB_PORT/DB_NAME"/>
</Realm>
</Context>


text:
<?php

/**
 * This file is part of cocur/page-bundle.
 *
 * (c) 2013 Florian Eckerstorfer <florian@eckerstorfer.co>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Cocur\Bundle\PageBundle\ContentCompiler;

/**
 * PlainCompiler
 *
 * @package    cocur/page-bundle
 * @subpackage ContentCompiler
 * @author     Florian Eckerstorfer <florian@eckerstorfer.co>
 * @copyright  2013 Florian Eckerstorfer
 * @license    http://opensource.org/licenses/MIT The MIT License
 * @link       http://cocur.florian.ec Cocur Website
 */
class PlainCompiler implements CompilerInterface
{
    /**
     * {@inheritDoc}
     */
    public function compile($input)
    {
        return nl2br($input);
    }

    /**
     * {@inheritDoc}
     */
    public function getFormats()
    {
        return [ 'txt' ];
    }
}


text:
<?php
require_once 'config.php';
?>

<meta name="viewport" content="width-device-width,initial-scale=1.0, maximum-scale=1.0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

Demo to provide a responsive Pay with Amazon button

Please do not use this in live integrations, this is for demo purposes only.

Logout


text:
@(piece: _root_.infra.piece.image.ImagePiece)

@import _root_.play.api.Play.current
@import _root_.infra.piece.core.Pieces.fileStorage

        @if(piece.title.isDefined) {

@piece.title.get

        }


text: VIEW ALL


text:
using ViewTester.Api;
using ViewTester.Helpers;

namespace ViewTester
{
    class Program
    {
        static void Main()
        {
            DataHelper.RegisterContextDefinitions();

            var mainHandlers = new MainHandlers();
            mainHandlers.Register();
        }
    }
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.1"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Shopify SDK for Unity: Shopify.UIToolkit.Shops.Generic.GenericMultiProductShop Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

Shopify SDK for Unity

Shopify

UIToolkit

Shops

Generic

GenericMultiProductShop

Public Member Functions |
Public Attributes |
Properties |
List of all members

Shopify.UIToolkit.Shops.Generic.GenericMultiProductShop Class Reference

Inheritance diagram for Shopify.UIToolkit.Shops.Generic.GenericMultiProductShop:

  <map id="Shopify.UIToolkit.Shops.Generic.GenericMultiProductShop_map" name="Shopify.UIToolkit.Shops.Generic.GenericMultiProductShop_map">
<area href="interface_shopify_1_1_u_i_toolkit_1_1_i_multi_product_shop.html" alt="Shopify.UIToolkit.IMultiProductShop" shape="rect" coords="356,56,702,80"/>
<area href="interface_shopify_1_1_u_i_toolkit_1_1_shops_1_1_generic_1_1_i_generic_multi_product_shop.html" alt="Shopify.UIToolkit.Shops.Generic.IGenericMultiProductShop" shape="rect" coords="712,56,1058,80"/>
<area href="interface_shopify_1_1_u_i_toolkit_1_1_i_shop.html" alt="Shopify.UIToolkit.IShop" shape="rect" coords="356,0,702,24"/>
  </map>

Public Member Functions

void 	InitializeViews ()

void 	Show ()

void 	Hide ()

void 	ViewProductDetails (Product product, ProductVariant[] variants)

void 	OpenCart ()

void 	GoBack ()

void 	AddItemToCart (ProductVariant variant, Product product)

void 	UpdateCartQuantityForVariant (ProductVariant variant, Product product, long quantity)

void 	CanCheckoutWithNativePay (CanCheckoutWithNativePayCallback callback)

void 	PerformWebCheckout ()

void 	PerformNativeCheckout ()

void 	LoadMoreProducts ()

Public Attributes

Animator 	Animator

CartView 	CartViewPrefab

ProductListView 	ProductListViewPrefab

ProductDetailsView 	ProductDetailsViewPrefab

ViewSwitcher 	ViewSwitcher

CartBadgeView 	BadgeView

Button 	CloseButton

Button 	BackButton

Animator 	LoadingAnimator

Properties

ProductCache 	ProductCache [get]

 Properties inherited from Shopify.UIToolkit.Shops.Generic.IGenericMultiProductShop

ProductCache 	ProductCache [get]

The documentation for this class was generated from the following file:

Assets/Shopify/UIToolkit/Shops/Generic/Classes/GenericMultiProductShop.cs

<address class="footer">

</address>


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Echinocactus castaneoides Cels ex Salm-Dyck

### Remarks
null


text:
```plantuml
Bob->Alice : hello
```

```plantuml
Alice -> Bob: Authentication Request
Bob --> Alice: Authentication Response

Alice -> Bob: Another authentication Request
Alice <-- Bob: Another authentication Response
```

```java
class Some {
  public int stuff() {
    return 42;
  }
}
```

```plantuml
@startuml
participant participant as Foo
actor       actor       as Foo1
boundary    boundary    as Foo2
control     control     as Foo3
entity      entity      as Foo4
database    database    as Foo5
collections collections as Foo6
queue       queue       as Foo7
Foo -> Foo1 : To actor
Foo -> Foo2 : To boundary
Foo -> Foo3 : To control
Foo -> Foo4 : To entity
Foo -> Foo5 : To database
Foo -> Foo6 : To collections
Foo -> Foo7: To queue
@enduml
```


text:
package org.openestate.io.immobiliare_it.xml.types;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * LandSizeUnitType.
 *
 * @author Andreas Rudolph
 * @since 1.0
 */
public enum LandSizeUnitType {
    HA("ha"),
    M2("m2"),
    SFT("sft");

    @SuppressWarnings("unused")
    private final static Logger LOGGER = LoggerFactory.getLogger(LandSizeUnitType.class);
    private final String xmlValue;

    LandSizeUnitType(String xmlValue) {
        this.xmlValue = xmlValue;
    }

    public String getXmlValue() {
        return xmlValue;
    }

    public static LandSizeUnitType fromXmlValue(String xmlValue) {
        for (LandSizeUnitType val : LandSizeUnitType.values()) {
            if (val.xmlValue.equalsIgnoreCase(xmlValue)) return val;
        }
        return null;
    }
}


text:
'use strict';
import { t } from '../utils/i18n';
import { roadNetEditMax as rnConfMax } from '../config';

export const roadNetEditMax = rnConfMax;
export const roadNetEditMaxDisplay = `${rnConfMax / Math.pow(1024, 2)}MB`;

// These constants need to be returned as the result of a function because, the
// translations need to be computed based on the current language. Otherwise
// they'd always be returned in English.
export const getfFileTypesMatrix = () => ({
  'admin-bounds': {
    display: t('Administrative Boundaries'),
    description: t('Boundaries for the administrative areas for which analysis is generated.'),
    helpPath: 'http://ruralaccess.info/setting-up-a-project/admin-boundaries/'
  },
  origins: {
    display: t('Population data'),
    description: t('Population point data that will be used as origins.'),
    helpPath: 'http://ruralaccess.info/setting-up-a-project/population/'
  },
  poi: {
    display: t('Points of Interest'),
    description: t('The POI used as destinations. Each scenario supports multiple types.'),
    helpPath: 'http://ruralaccess.info/setting-up-a-project/poi/'
  },
  'road-network': {
    display: t('Road Network'),
    description: t('The road network data used for routing.'),
    helpPath: 'http://ruralaccess.info/setting-up-a-project/road-network/'
  },
  profile: {
    display: t('Profile'),
    description: t('A lua file with the OSRM Profile.'),
    helpPath: 'http://ruralaccess.info/setting-up-a-project/osrm-profile/'
  }
});

export const getProjectStatusMatrix = () => ({
  active: t('Active'),
  pending: t('Draft')
});

export const getPoiOsmTypes = () => ([
  {
    key: 'health',
    value: t('Health facilities')
  },
  {
    key: 'education',
    value: t('Education facilities')
  },
  {
    key: 'financial',
    value: t('Financial institutions')
  }
]);


text:
__version__ = '0.1'
import requests
import json

class OrganizationManager(object):

	def __init__(self, host, port=8000):
		self._host = host
		self._port = port
		self._hostURL = 'http://' + host + ':' + port

	def create_dictionary_from_input_string(self, inputstring):
		input_array = inputstring.split(',')
		json_payload_list = {}
		for keyval in input_array:
			keyval_array = keyval.split(':')
			if len(keyval_array) == 2:
				key = keyval_array[0]
				key = key.lower().strip().replace(" ","_")
				value = keyval_array[1]
				json_payload_list[key] = value.strip()
		return json_payload_list

	def create_organization(self, access_token,name,address,tax_registration,tax_commissionar):
		url = self._hostURL +'/api/organizations'
		json_payload_list = {}
		json_payload_list['name'] = name
		json_payload_list['address'] = address
		json_payload_list['tax_registration'] = tax_registration
		json_payload_list['tax_commissionar'] = tax_commissionar
		print(json_payload_list)
		call_headers = {'Authorization': 'Bearer '+ access_token}
		r = requests.post(url, json=json_payload_list, headers=call_headers)
		r.raise_for_status()
		server_response = r.json()
		print server_response

	def get_organization_id(self, access_token):
		url = self._hostURL +'/api/organizations'
		call_headers = {'Authorization': 'Bearer '+ access_token}
		r = requests.get(url, headers=call_headers)
		r.raise_for_status()
		server_response = r.json()
		print server_response
		return server_response['organization']['id']

	def request_organization_membership(self, access_token,org_id):
		url = self._hostURL +'/api/organizations/membership'
		json_payload_list = {}
		json_payload_list['org_id'] = org_id
		json_payload_list['action'] = 'addrequest'
		print(json_payload_list)
		call_headers = {'Authorization': 'Bearer '+ access_token}
		r = requests.post(url, json=json_payload_list, headers=call_headers)
		r.raise_for_status()
		server_response = r.json()
		print server_response

	def approve_organization_membership(self, access_token,user_id):
		url = self._hostURL +'/api/organizations/membership'
		json_payload_list = {}
		json_payload_list['user_id'] = user_id
		json_payload_list['action'] = 'approve'
		print(json_payload_list)
		call_headers = {'Authorization': 'Bearer '+ access_token}
		r = requests.post(url, json=json_payload_list, headers=call_headers)
		r.raise_for_status()
		server_response = r.json()
		print server_response

	def get_pending_membership_state(self, access_token):
		url = self._hostURL +'/api/organizations/membership'
		json_payload_list = {}
		json_payload_list['status'] = 'addrequest'
		print(json_payload_list)
		call_headers = {'Authorization': 'Bearer '+ access_token}
		r = requests.get(url, json=json_payload_list, headers=call_headers)
		r.raise_for_status()
		server_response = r.json()
		return server_response

	def approve_organization_membership_for_all(self, access_token):
		pending_membership_state = self.get_pending_membership_state(access_token)
		print pending_membership_state['pending']
		for i in pending_membership_state['pending']:
			print 'Approving Membership For Id: ' + str(i['user_id'])
			self.approve_organization_membership(access_token, i['user_id'])

	def update_organization(self, access_token,name,address,tax_registration,tax_commissionar):
		url = self._hostURL +'/api/organizations'
		json_payload_list = {}
		json_payload_list['name'] = name
		json_payload_list['address'] = address
		json_payload_list['tax_registration'] = tax_registration
		json_payload_list['tax_commissionar'] = tax_commissionar
		print(json_payload_list)
		call_headers = {'Authorization': 'Bearer '+ access_token}
		r = requests.put(url, json=json_payload_list, headers=call_headers)
		r.raise_for_status()
		server_response = r.json()
		print server_response


text:
brandymint-fontello
===================


text:
import React, { useContext } from 'react';
import { Connector as BaseConnector } from '@visx/annotation';
import { ConnectorProps as BaseConnectorProps } from '@visx/annotation/lib/components/Connector';
import DataContext from '../../context/DataContext';

export type AnnotationConnectorProps = BaseConnectorProps;

/** AnnotationConnector which provides color from theme. */
export default function AnnotationConnector(props: AnnotationConnectorProps) {
  const { theme } = useContext(DataContext);
  return <BaseConnector stroke={theme?.axisStyles.x.bottom.axisLine.stroke} {...props} />;
}


text:
<?php

if(!defined("IN_SB")){echo "You should not be here. Only follow links!";die();}

global $theme, $userbank;

$sid = (int)$_GET['id'];

// Access on that server?
$servers = $GLOBALS['db']->GetAll("SELECT `server_id`, `srv_group_id` FROM ".DB_PREFIX."_admins_servers_groups WHERE admin_id = ". $userbank->GetAid());
$access = false;
foreach($servers as $server)
{
    if($server['server_id'] == $sid)
    {
        $access = true;
        break;
    }
    if($server['srv_group_id'] > 0)
    {
        $servers_in_group = $GLOBALS['db']->GetAll("SELECT `server_id` FROM ".DB_PREFIX."_servers_groups WHERE group_id = ". (int)$server['srv_group_id']);
        foreach($servers_in_group as $servig)
        {
            if($servig['server_id'] == $sid)
            {
                $access = true;
                break 2;
            }
        }
    }
}

$theme->assign('id', $sid);
$theme->assign('permission_rcon', ($access && $userbank->HasAccess(SM_RCON . SM_ROOT)));
$theme->left_delimiter = '-{';
$theme->right_delimiter = '}-';

$theme->display('page_admin_servers_rcon.tpl');

$theme->left_delimiter = '{';
$theme->right_delimiter = '}';
?>


text:
<?php

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use App\Http\Requests\Request;

class CqFormRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'rolename' => 'required|max:64',
            'classes' => 'required',
            'duty' => 'required',
            'rank' => 'numeric',
            'artifact' => 'numeric',
        ];
    }

    public function messages()
    {
        return [
            'rolename.required' => ':attribute 角色昵称没填!',
            'classes.required' => '职业专精没填!',
            'duty.required' => '亲,职责没选',
            'rank.numeric' => '金币必须为数字',
            'artifact.numeric' => '等级必须为数字',
        ]; // TODO: Change the autogenerated stub
    }

    public function customAtrribute(){

    }

}


text:
package com.raizlabs.android.dbflow.processor.definition.method;

import com.raizlabs.android.dbflow.processor.ClassNames;
import com.raizlabs.android.dbflow.processor.definition.TableDefinition;
import com.raizlabs.android.dbflow.processor.definition.column.ColumnDefinition;
import com.raizlabs.android.dbflow.processor.utils.ModelUtils;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;

import javax.lang.model.element.Modifier;

/**
 * Description: Writes a Model into a ForeignKeyContainer for convenience.
 */
public class ForeignKeyContainerMethod implements MethodDefinition {

    private final TableDefinition tableDefinition;

    public ForeignKeyContainerMethod(TableDefinition tableDefinition) {
        this.tableDefinition = tableDefinition;
    }

    @Override
    public MethodSpec getMethodSpec() {

        CodeBlock.Builder codeBuilder = CodeBlock.builder();
        codeBuilder.addStatement("$T $L = new $T<>($T.class)", ClassNames.FOREIGN_KEY_CONTAINER,
                ModelUtils.getVariable(true), ClassNames.FOREIGN_KEY_CONTAINER, tableDefinition.elementClassName);
        for (ColumnDefinition columnDefinition : tableDefinition.getPrimaryColumnDefinitions()) {
            codeBuilder.add(columnDefinition.getForeignKeyContainerMethod(tableDefinition.getPropertyClassName()));
        }
        codeBuilder.addStatement("return $L", ModelUtils.getVariable(true));

        return MethodSpec.methodBuilder("toForeignKeyContainer")
                .addAnnotation(Override.class)
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                .addParameter(tableDefinition.elementClassName, ModelUtils.getVariable(false))
                .addCode(codeBuilder.build())
                .returns(ParameterizedTypeName.get(ClassNames.FOREIGN_KEY_CONTAINER, tableDefinition.elementClassName))
                .build();
    }
}


text:
using DragonSpark.Compose;
using DragonSpark.Model.Operations;
using System.Threading.Tasks;

namespace DragonSpark.Application.Security.Identity.MultiFactor;

sealed class ConfiguredAwareKey<T> : ISelecting<UserInput<T>, string> where T : IdentityUser
{
	public static ConfiguredAwareKey<T> Default { get; } = new();

	ConfiguredAwareKey() : this(Key<T>.Default) {}

	readonly ISelecting<UserInput<T>, string> _previous;

	public ConfiguredAwareKey(ISelecting<UserInput<T>, string> previous) => _previous = previous;

	public async ValueTask<string> Get(UserInput<T> parameter)
	{
		var previous = await _previous.Await(parameter);
		if (string.IsNullOrEmpty(previous))
		{
			var (manager, user) = parameter;
			var updated = await manager.FindByIdAsync(await manager.GetUserIdAsync(user).ConfigureAwait(false))
			                           .ConfigureAwait(false);
			await manager.ResetAuthenticatorKeyAsync(updated).ConfigureAwait(false);
			return await _previous.Await(parameter);
		}

		return previous;
	}
}


text:
<assembly
	xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
	<id>bundle</id>
	<formats>
		<format>zip</format>
	</formats>

	<files>
		<file>
			<source>${basedir}/src/main/templates/start.sh</source>
			<outputDirectory></outputDirectory>
			<fileMode>755</fileMode>
			<filtered>true</filtered>
		</file>
		<file>
			<source>${basedir}/src/main/templates/start.bat</source>
			<outputDirectory></outputDirectory>
			<fileMode>755</fileMode>
			<filtered>true</filtered>
		</file>
		<file>
			<source>${project.build.directory}/${artifactId}-${version}-bin.jar</source>
			<outputDirectory></outputDirectory>
			<destName>${artifactId}.jar</destName>
		</file>

	</files>

	<fileSets>
		<fileSet>
			<directory>${basedir}/src/main/templates</directory>
			<outputDirectory></outputDirectory>
			<excludes>
				<exclude>start.sh</exclude>
			</excludes>
		</fileSet>
		<fileSet>
			<directory>${basedir}/src/main/templates</directory>
			<outputDirectory></outputDirectory>
			<excludes>
				<exclude>start.bat</exclude>
			</excludes>
		</fileSet>
		<fileSet>
			<directory>${basedir}/src/main/templates</directory>
			<outputDirectory></outputDirectory>
		</fileSet>
		<fileSet>
			<directory>${project.build.directory}</directory>
			<outputDirectory></outputDirectory>
			<includes>
				<include>${artifactId}-bin.jar</include>
			</includes>
		</fileSet>
		<fileSet>
			<directory>${basedir}</directory>
			<outputDirectory></outputDirectory>
			<includes>
				<include>README.md</include>
				<include>LICENSE.txt</include>
				<include>NOTICE.txt</include>
				<include>CHANGELOG.txt</include>
			</includes>
		</fileSet>
	</fileSets>
</assembly>


text:
Introduction to Time Series Insights.

# Time Series Insights Samples

You can explore the time series insights APIs (using the client library) using the samples project.

## Creating the time series insights client

To create a new time series insights client, you need the endpoint to an Azure Time Series Insights instance and supply credentials.
In the sample below, you can set `TsiEndpoint`, `TenantId`, `ClientId`, and `ClientSecret` as command-line arguments.
The client requires an instance of [TokenCredential](https://docs.microsoft.com/dotnet/api/azure.core.tokencredential?view=azure-dotnet).
In this samples, we illustrate how to use one derived class: ClientSecretCredential.

```C# Snippet:TimeSeriesInsightsSampleCreateServiceClientWithClientSecret
// DefaultAzureCredential supports different authentication mechanisms and determines the appropriate credential type based of the environment it is executing in.
// It attempts to use multiple credential types in an order until it finds a working credential.
var tokenCredential = new DefaultAzureCredential();

var client = new TimeSeriesInsightsClient(
    tsiEndpoint,
    tokenCredential);
```


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

namespace NMF.Expressions.Linq
{
    internal class BalancingStrategyProvider<T, TChunk> : IChunkBalancingStrategyProvider<T, TChunk>
    {
        private readonly IChunkBalancingStrategyProvider _provider;

        public BalancingStrategyProvider(IChunkBalancingStrategyProvider provider)
        {
            _provider = provider ?? new NoBalancingStrategy();
        }

        public IChunkBalancingStrategy<T, TChunk> CreateStrategy( IObservableChunk<T, TChunk> observableChunk )
        {
            return _provider.CreateStrategy( observableChunk );
        }
    }
}


text:
"""Setup credentials (.env) and application variables (config.yml)"""
import os
import yaml

class Config(object):
    """All configuration for this app is loaded here"""
    def __init__(self, **opts):
        if (os.environ.get('ENV') != 'prod'):  # We are not in Heroku
            self.init_environment()

        """Allow variables assigned in config.yml available the following variables
           via properties"""
        self.path = opts.get('path', os.path.abspath(os.path.dirname(__file__)))
        with open(self.path + '/config.yml') as stream:
            config = yaml.load(stream)
            self._debug_mode = config['debug_mode']
            self._port = config['port']

    @staticmethod
    def init_environment():
        """Allow variables assigned in .env available using
           os.environ.get('VAR_NAME')"""
        base_path = os.path.abspath(os.path.dirname(__file__))
        if os.path.exists(base_path + '/.env'):
            for line in open(base_path + '/.env'):
                var = line.strip().split('=')
                if len(var) == 2:
                    os.environ[var[0]] = var[1]

    @property
    def debug_mode(self):
        return self._debug_mode

    @property
    def port(self):
        return self._port


text:
layout: page
title: Cabrera Foundation Award Ceremony
date: 2016-05-24
author: Edward Little
tags: weekly links, java
status: published
summary: Ut accumsan ante sed libero aliquet.
banner: images/banner/leisure-02.jpg
booking:
  startDate: 04/07/2016
  endDate: 04/08/2016
  ctyhocn: BRITNHX
  groupCode: CFAC
published: true
---
Praesent accumsan, mi quis luctus lobortis, dolor augue ullamcorper massa, eu convallis lacus nisl eu neque. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc a leo sit amet est ultrices aliquet. Suspendisse faucibus feugiat scelerisque. Duis id finibus velit. Donec dignissim ultrices eros. Maecenas id quam bibendum ante laoreet ultrices et eget augue. Donec facilisis a risus at congue. Aliquam aliquet, lacus vel porta facilisis, tortor libero tincidunt risus, vitae consequat purus dolor eu sem.
Phasellus nec molestie odio. Aliquam rhoncus neque at erat faucibus vulputate. Maecenas congue eget est vitae mollis. Duis sagittis lectus nec cursus imperdiet. Sed placerat, dui ac interdum interdum, nulla augue malesuada orci, vulputate ullamcorper mauris eros in massa. Etiam sit amet feugiat nunc. Quisque dignissim imperdiet auctor.

1 Proin quis velit quis nulla ullamcorper faucibus nec ac quam
1 Pellentesque consequat tortor ut magna ullamcorper, vitae condimentum turpis imperdiet
1 Maecenas vitae odio ultrices, tincidunt dui vel, tincidunt tellus
1 Aenean at erat sit amet quam volutpat sodales
1 Vivamus sit amet neque finibus, pharetra justo id, maximus neque.

Nulla facilisi. Integer ac nunc erat. Vivamus rhoncus fermentum nunc sit amet auctor. Aenean eget imperdiet sapien. Donec tincidunt viverra ipsum. Fusce ut congue leo, non bibendum mi. Nulla vel feugiat enim. Curabitur erat dui, condimentum in euismod sit amet, dapibus vel libero. Duis blandit, diam sed maximus convallis, mi erat rutrum sapien, ut bibendum lacus ex non justo. Vestibulum pretium est tellus, vel rhoncus justo ornare et. Maecenas eros quam, aliquam ac dolor et, pulvinar tristique quam. Pellentesque pellentesque magna eget sollicitudin accumsan.


text:
import Donut from './Donut';
import PercentageDonut from './PercentageDonut';

export default {
  Donut,
  PercentageDonut,
};


text:
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';

import { HttpClientTestingModule } from '@angular/common/http/testing';
import { LessorFormComponent } from './lessor-form.component';

describe('LessorFormComponent', () => {
  let component: LessorFormComponent;
  let fixture: ComponentFixture<LessorFormComponent>;

  beforeEach(
    async(() => {
      TestBed.configureTestingModule({
        schemas: [NO_ERRORS_SCHEMA],
        imports: [HttpClientTestingModule, ReactiveFormsModule],
        declarations: [LessorFormComponent]
      }).compileComponents();
    })
  );

  beforeEach(() => {
    fixture = TestBed.createComponent(LessorFormComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});


text:
layout: post
date: 2017-05-24
title: "Pronovias PROSA 2016 Sleeveless Chapel Train Mermaid/Trumpet Open Back"
category: Pronovias
tags: [Pronovias,Mermaid/Trumpet,Open Back,V-neck,Chapel Train,Sleeveless,2016,Tulle]
---
### Pronovias PROSA
Just **$379.99**
### 2016  Sleeveless Chapel Train Mermaid/Trumpet Open Back

BRANDS	Pronovias

Silhouette	Mermaid/Trumpet

Trend	Open Back

Neckline	V-neck

Hemline/Train	Chapel Train

Sleeve	Sleeveless

Years	2016

Fabric	Tulle

Buy it: [https://www.readybrides.com/en/pronovias/4212-pronovias-prosa.html](https://www.readybrides.com/en/pronovias/4212-pronovias-prosa.html)


text:
/// <reference path="fourslash.ts" />

// @module: commonjs
// @esModuleInterop: true

// @Filename: /node_modules/@types/react-dom/package.json
//// { "name": "react-dom", "version": "1.0.0", "types": "./index.d.ts" }

// @Filename: /node_modules/@types/react-dom/index.d.ts
//// import * as React from "react";
//// export function render(): void;

// @Filename: /node_modules/@types/react/package.json
//// { "name": "react", "version": "1.0.0", "types": "./index.d.ts" }

// @Filename: /node_modules/@types/react/index.d.ts
//// import "./other";
//// export declare function useState(): void;

// @Filename: /node_modules/@types/react/other.d.ts
//// export declare function useRef(): void;

// @Filename: /packages/a/node_modules/react/package.json
//// { "name": "react", "version": "1.0.1", "types": "./index.d.ts" }

// @Filename: /packages/a/node_modules/react/index.d.ts
//// export declare function useState(): void;

// @Filename: /packages/a/index.ts
//// import "react-dom";
//// import "react";

// @Filename: /packages/a/foo.ts
//// useState/**/

goTo.marker("");
verify.completions({
  marker: "",
  exact: completion.globalsPlus([{
    name: "useState",
    source: "react",
    sourceDisplay: "react",
    hasAction: true,
    sortText: completion.SortText.AutoImportSuggestions,
  }]),
  preferences: {
    includeCompletionsForModuleExports: true,
    allowIncompleteCompletions: true,
  },
});


text:
using UnityEngine;
using UnityEngine.Networking;

namespace Assets.Scripts.Networking
{
    class LobbyControllerResetter : MonoBehaviour
    {
        bool first = true;

        private void OnEnable()
        {
            if (!first)
            {
                NetworkLobbyController.instance.ResetNetworkState();
                first = false;
            }
        }
    }
}


text:
package org.apache.bcel.generic;

/**
 * LSUB - Substract longs
 *
Stack: ..., value1.word1, value1.word2, value2.word1, value2.word2 ->

 *        ..., result.word1, result.word2
 *
 * @version $Id: LSUB.java 386056 2006-03-15 11:31:56Z tcurdt $
 * @author  M. Dahm
 */
public class LSUB extends ArithmeticInstruction {

    public LSUB() {
        super(org.apache.bcel.Constants.LSUB);
    }

    /**
     * Call corresponding visitor method(s). The order is:
     * Call visitor methods of implemented interfaces first, then
     * call methods according to the class hierarchy in descending order,
     * i.e., the most specific visitXXX() call comes last.
     *
     * @param v Visitor object
     */
    public void accept( Visitor v ) {
        v.visitTypedInstruction(this);
        v.visitStackProducer(this);
        v.visitStackConsumer(this);
        v.visitArithmeticInstruction(this);
        v.visitLSUB(this);
    }
}


text:
package org.knowm.xchange.dto.meta;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
import java.math.BigDecimal;

public class CurrencyMetaData implements Serializable {

  @JsonProperty("scale")
  private final int scale;

  /** Withdrawal fee */
  @JsonProperty("withdrawal_fee")
  private BigDecimal withdrawalFee;

  /**
   * Constructor
   *
   * @param scale
   */
  public CurrencyMetaData(
      @JsonProperty("scale") int scale, @JsonProperty("withdrawal_fee") BigDecimal withdrawalFee) {
    this.scale = scale;
    this.withdrawalFee = withdrawalFee;
  }

  public int getScale() {
    return scale;
  }

  public BigDecimal getWithdrawalFee() {
    return withdrawalFee;
  }

  @Override
  public String toString() {
    return "CurrencyMetaData [" + "scale=" + scale + ", withdrawalFee=" + withdrawalFee + "]";
  }
}


text:
#import \"mycanvas.h\"
#import <QuartzCore/QuartzCore.h>
#import \"ViewController.h\"

@implementation mycanvas
@synthesize path,x,y,mouseSwipped,color;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }

	colors_.selectedSegmentIndex=8;
    return self;
}

//Initial
-(void)touchBegan {
    path = CGPathCreateMutable();
}

//Moved line
-(void)touchMoved {
    CGPathMoveToPoint(path,NULL,x,y);
    CGPathAddLineToPoint(path,NULL,x,y);

}

//Touched screen
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

	mouseSwipped = NO;
	UITouch *touch = [touches anyObject];

	if([touch tapCount]==3){

		self.image = nil;
		return;
	}

	lastPoint = [touch locationInView:self];
	lastPoint.y -= 10;

}

//Draw line
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
	mouseSwipped = YES;

	UITouch *touch = [touches anyObject];
	CGPoint currentPoint = [touch locationInView:self];
	currentPoint.y -= 10;

	UIGraphicsBeginImageContext(self.frame.size);
	[self.image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
	CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
	CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);

		CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0);

	if(colors_.selectedSegmentIndex==0)CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);//r
	if(colors_.selectedSegmentIndex==1)CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.3, 0.1, 1.0);//o
	if(colors_.selectedSegmentIndex==2)CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 1.0, 0.0, 1.0);//y
	if(colors_.selectedSegmentIndex==3)CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.4, 0.4, 1.0);//g
	if(colors_.selectedSegmentIndex==4)CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.6, 6.0, 1.0);//b
	if(colors_.selectedSegmentIndex==5)CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.3, 0.5, 1.0);//i
	if(colors_.selectedSegmentIndex==6)CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.5, 1.0, 1.0);//v

	if(colors_.selectedSegmentIndex==7)CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0);//b;

	CGContextBeginPath(UIGraphicsGetCurrentContext());
	CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
	CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
	CGContextStrokePath(UIGraphicsGetCurrentContext());
	self.image = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();

	lastPoint = currentPoint;

}

//End line
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

	UITouch *touch = [touches anyObject];

	if([touch tapCount]==3){

		self.image = nil;
		return;
	}

	if(!mouseSwipped) {
		UIGraphicsBeginImageContext(self.frame.size);
		[self.image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
		CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
		CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);

		CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0);

		if(colors_.selectedSegmentIndex==0)CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);//r
		if(colors_.selectedSegmentIndex==1)CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.3, 0.1, 1.0);//o
		if(colors_.selectedSegmentIndex==2)CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 1.0, 0.0, 1.0);//y
		if(colors_.selectedSegmentIndex==3)CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.4, 0.4, 1.0);//g
		if(colors_.selectedSegmentIndex==4)CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.6, 6.0, 1.0);//b
		if(colors_.selectedSegmentIndex==5)CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.3, 0.5, 1.0);//i
		if(colors_.selectedSegmentIndex==6)CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.5, 1.0, 1.0);//v

		if(colors_.selectedSegmentIndex==7)CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0);//b;

		CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
		CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
		CGContextStrokePath(UIGraphicsGetCurrentContext());
		CGContextFlush(UIGraphicsGetCurrentContext());
		self.image = UIGraphicsGetImageFromCurrentImageContext();
		UIGraphicsEndImageContext();
	}
}

@end


text:
namespace cc {

TEST(ShaderTest, HighpThresholds) {
  // The test context always uses a mediump precision of 10 bits which
  // corresponds to a native highp threshold of 2^10 = 1024
  scoped_ptr<TestWebGraphicsContext3D> stub_context =
    TestWebGraphicsContext3D::Create();
  TestGLES2Interface stub_gl(stub_context.get());

  int threshold_cache = 0;
  int threshold_min;
  gfx::Point closePoint(512, 512);
  gfx::Size smallSize(512, 512);
  gfx::Point farPoint(2560, 2560);
  gfx::Size bigSize(2560, 2560);

  threshold_min = 0;
  EXPECT_EQ(TexCoordPrecisionMedium, TexCoordPrecisionRequired(
      &stub_gl, &threshold_cache, threshold_min, closePoint));
  EXPECT_EQ(TexCoordPrecisionMedium, TexCoordPrecisionRequired(
      &stub_gl, &threshold_cache, threshold_min, smallSize));
  EXPECT_EQ(TexCoordPrecisionHigh, TexCoordPrecisionRequired(
      &stub_gl, &threshold_cache, threshold_min, farPoint));
  EXPECT_EQ(TexCoordPrecisionHigh, TexCoordPrecisionRequired(
      &stub_gl, &threshold_cache, threshold_min, bigSize));

  threshold_min = 3000;
  EXPECT_EQ(TexCoordPrecisionMedium, TexCoordPrecisionRequired(
      &stub_gl, &threshold_cache, threshold_min, closePoint));
  EXPECT_EQ(TexCoordPrecisionMedium, TexCoordPrecisionRequired(
      &stub_gl, &threshold_cache, threshold_min, smallSize));
  EXPECT_EQ(TexCoordPrecisionMedium, TexCoordPrecisionRequired(
      &stub_gl, &threshold_cache, threshold_min, farPoint));
  EXPECT_EQ(TexCoordPrecisionMedium, TexCoordPrecisionRequired(
      &stub_gl, &threshold_cache, threshold_min, bigSize));
}

}  // namespace cc


text:
using System.Linq;
using Orchard;
using Orchard.DisplayManagement.Descriptors;
using Orchard.Environment.Extensions;
using Orchard.UI.Resources;
using CloudBust.Resources.Services;
using Orchard.Environment;
using Orchard.UI.Admin;

namespace CloudBust.Resources.Shapes
{
    [OrchardFeature("CloudBust.Resources.IziModal")]
    public class IziModalShapes : IShapeTableProvider
    {
        private readonly Work<WorkContext> _workContext;
        private readonly IIziModalService _izimodalService;
        public IziModalShapes(Work<WorkContext> workContext, IIziModalService izimodalService)
        {
            _workContext = workContext;
            _izimodalService = izimodalService;
        }

        public void Discover(ShapeTableBuilder builder)
        {
            builder.Describe("HeadLinks")
                .OnDisplaying(shapeDisplayingContext =>
                {
                    if (!_izimodalService.GetAutoEnable()) return;
                    if (!_izimodalService.GetAutoEnableAdmin())
                    {
                        var request = _workContext.Value.HttpContext.Request;
                        if (AdminFilter.IsApplied(request.RequestContext))
                        {
                            return;
                        }
                    }

                        var resourceManager = _workContext.Value.Resolve<IResourceManager>();
                        var scripts = resourceManager.GetRequiredResources("stylesheet");

                        string includecss = "IziModal";
                        var currentIziModal = scripts
                                .Where(l => l.Name == includecss)
                                .FirstOrDefault();

                        if (currentIziModal == null)
                        {
                            // temp untill we fix the logic
                            resourceManager.Require("stylesheet", includecss).AtHead();

                        }

                });

            builder.Describe("HeadScripts")
                .OnDisplaying(shapeDisplayingContext =>
                {
                    if (!_izimodalService.GetAutoEnable()) return;
                    if (!_izimodalService.GetAutoEnableAdmin())
                    {
                        var request = _workContext.Value.HttpContext.Request;
                        if (AdminFilter.IsApplied(request.RequestContext))
                        {
                            return;
                        }
                    }

                    var resourceManager = _workContext.Value.Resolve<IResourceManager>();
                    var scripts = resourceManager.GetRequiredResources("script");

                    string includejs = "IziModal";
                    var currentIziModal = scripts
                            .Where(l => l.Name == includejs)
                            .FirstOrDefault();

                    if (currentIziModal == null)
                    {
                        resourceManager.Require("script", includejs).AtFoot();
                    }

                });
        }
    }
}


text:
import {bindable, inject, BindingEngine, customElement, processContent, TargetInstruction } from 'aurelia-framework';
import {GridColumn} from './grid-column';
import {ViewCompiler, ViewSlot, ViewResources, Container} from 'aurelia-framework';

@customElement('grid')
@processContent(function(viewCompiler, viewResources, element, instruction) {
	// Do stuff
	var result = processUserTemplate(element);
	instruction.gridColumns = result.columns;
	instruction.rowAttrs = result.rowAttrs;

	return true;
})
@inject(Element, ViewCompiler, ViewResources, Container, TargetInstruction, BindingEngine)
export class Grid {

	/* == Styling == */
	@bindable gridHeight = 0;

	/* == Options == */

	// Initial load flag (for client side)
	@bindable initialLoad = false;

	// Filtering
	@bindable showColumnFilters = false;
	@bindable serverFiltering = false;
	@bindable filterDebounce = 500;

	// Pagination
	@bindable serverPaging = false;
	@bindable pageable = true;
	@bindable pageSize = 10;
	@bindable page = 1;
	@bindable pagerSize = 10;

	@bindable showPageSizeBox = true;
	@bindable showPagingSummary = true;
	@bindable showFirstLastButtons = true;
	@bindable showJumpButtons = true;

	@bindable pageSizes = [10, 25, 50];

	firstVisibleItem = 0;
	lastVisibleItem = 0;

	pageNumber = 1;

	// Sortination
	@bindable serverSorting = false;
	@bindable sortable = true;
	sortProcessingOrder = []; // Represents which order to apply sorts to each column
	sorting = {};

	// Burnination?
	Trogdor = true;

	// Column defs
	@bindable autoGenerateColumns;
	@bindable showColumnHeaders = true;
	columnHeaders = [];
	columns = [];

	// Selection
	@bindable selectable = false;
	@bindable selectedItem = null;

	// Misc
	@bindable noRowsMessage = "";

	// Data ....
	@bindable autoLoad = true;
	loading = false;
	@bindable loadingMessage = "Loading...";

	// Read
	@bindable read = null;
	@bindable onReadError = null;

	// Tracking
	cache = [];
	data = [];
	count = 0;

	// Subscription handling
	unbinding = false;

	// Visual
	// TODO: calc scrollbar width using browser
	scrollBarWidth = 16;

	// Templating
	viewSlot;
	rowTemplate;
	rowAttrs;

	// Services
	viewCompiler;
	viewResources;
	container;
	bindingEngine;

	constructor(element, vc, vr, container, targetInstruction, bindingEngine) {
		this.element = element;
		this.viewCompiler = vc;
		this.viewResources = vr;
		this.container = container;
		this.bindingEngine = bindingEngine;

		var behavior = targetInstruction.behaviorInstructions[0];
		this.columns = behavior.gridColumns;
		this.rowAttrs = behavior.rowAttrs;
	}

	/* === Lifecycle === */
	attached() {
		this.gridHeightChanged();

		if(this.autoLoad)
		    this.refresh();
	}

	bind(executionContext) {

		// Listen for window resize so we can re-flow the grid layout
		this.resizeListener = window.addEventListener('resize', this.syncColumnHeadersWithColumns.bind(this));

		this["$parent"] = executionContext;

		// Ensure the grid settings
		// If we can page on the server and we can't server sort, we can't sort locally
		if(this.serverPaging && !this.serverSorting)
			this.sortable = false;

		// The table body element will host the rows
		var tbody = this.element.querySelector("table>tbody");
		this.viewSlot = new ViewSlot(tbody, true, this);

		// Get the row template too and add a repeater/class
		var row = tbody.querySelector("tr");

		this.addRowAttributes(row);

		this.rowTemplate = document.createDocumentFragment();
		this.rowTemplate.appendChild(row);

		this.buildTemplates();
	}

	addRowAttributes(row) {
		row.setAttribute("repeat.for", "$item of data");
		row.setAttribute("class", "${ $item === $parent.selectedItem ? 'info' : '' }");
		// TODO: Do we allow the user to customise the row template or just
		// provide a callback?
		// Copy any user specified row attributes to the row template
		for (var prop in this.rowAttrs) {
     		if (this.rowAttrs.hasOwnProperty(prop)) {
		 		row.setAttribute(prop, this.rowAttrs[prop]);
      		}
		}
	}

	buildTemplates() {

		// Create a fragment we will manipulate the DOM in
		var rowTemplate = this.rowTemplate.cloneNode(true);
		var row = rowTemplate.querySelector("tr");

		// Create the columns
		 this.columns.forEach(c => {
			var td = document.createElement("td");

			// Set attributes
			for (var prop in c) {
	    		if (c.hasOwnProperty(prop)) {

	    			if(prop == "template")
	    				td.innerHTML = c[prop];
	    			else
		    			td.setAttribute(prop, c[prop]);
	        	}
			}

			row.appendChild(td);
		});

		// Now compile the row template
		var view = this.viewCompiler.compile(rowTemplate, this.viewResources).create(this.container);
		// Templating 17.x changes the API
		// ViewFactory.create() no longer takes a binding context (2nd parameter)
		// Instead, must call view.bind(context)
		view.bind(this);

		// based on viewSlot.swap() from templating 0.16.0
		let removeResponse = this.viewSlot.removeAll();

	  if (removeResponse instanceof Promise) {
	    removeResponse.then(() => this.viewSlot.add(view));
	  }

	  this.viewSlot.add(view);

	  // code above replaces the following call
		//this.viewSlot.swap(view);
		this.viewSlot.attached();

		// HACK: why is the change handler not firing for noRowsMessage?
		this.noRowsMessageChanged();
	}

	unbind() {
		this.unbinding = true;
		window.removeEventListener('resize', this.resizeListener);
		this.dontWatchForChanges();
	}

	/* === Column handling === */
	addColumn(col) {

		// No-sort if grid is not sortable
		if(!this.sortable)
			col.nosort = true;

		this.columns.push(col);
	}

	/* === Paging === */
	pageChanged(page, oldValue) {

		if(page === oldValue) return;

		this.pageNumber = Number(page);
		this.refresh();
	}

	pageSizeChanged(newValue, oldValue) {

		if(newValue === oldValue) return;

		//this.pageChanged(1);
		this.updatePager();
	}

	filterSortPage(data) {
		// Applies filter, sort then page
		// 1. First filter the data down to the set we want, if we are using local data
		var tempData = data;

		if(this.showColumnFilters && !this.serverFiltering)
			tempData = this.applyFilter(tempData);

		// Count the data now before the sort/page
		this.count = tempData.length;

		// 2. Now sort the data
		if(this.sortable && !this.serverSorting)
			tempData = this.applySort(tempData);

		// 3. Now apply paging
		if(this.pageable && !this.serverPaging)
			tempData = this.applyPage(tempData);

		this.data = tempData;

		this.updatePager();

		this.watchForChanges();

		setTimeout(this.syncColumnHeadersWithColumns.bind(this), 0);
	}

	applyPage(data) {
		var start = (Number(this.pageNumber) - 1) * Number(this.pageSize);
		data = data.slice(start, start + Number(this.pageSize));

		return data;
	}

	updatePager() {
		if(this.pager)
			this.pager.update(this.pageNumber, Number(this.pageSize), Number(this.count));

		this.firstVisibleItem = (this.pageNumber - 1) * Number(this.pageSize) + 1;
		this.lastVisibleItem = Math.min((this.pageNumber) * Number(this.pageSize), this.count);
	}

	/* === Sorting === */
	fieldSorter(fields) {
	    return function (a, b) {
	        return fields
	            .map(function (o) {
	                var dir = 1;
	                if (o[0] === '-') {
	                   dir = -1;
	                   o = o.substring(1);
	                }
	                if (a[o] > b[o]) return dir;
	                if (a[o] < b[o]) return -(dir);
	                return 0;
	            })
	            .reduce(function firstNonZeroValue (p,n) {
	                return p ? p : n;
	            }, 0);
	    };
	}

	pageSizesChanged() {
		this.refresh();
	}

	sortChanged(field) {

		// Determine new sort
		var newSort = undefined;

		// Figure out which way this field should be sorting
	    switch(this.sorting[field]) {
	    	case "asc":
	    			newSort = "desc";
	    		break;
	    		case "desc":
	    			newSort = "";
	    		break;
	    		default:
	    			newSort = "asc";
	    		break;
	    }

	    this.sorting[field] = newSort;

	    // If the sort is present in the sort stack, slice it to the back of the stack, otherwise just add it
	    var pos = this.sortProcessingOrder.indexOf(field);

	    if(pos > -1)
	    	this.sortProcessingOrder.splice(pos, 1);

		this.sortProcessingOrder.push(field);

	    // Apply the new sort
		this.refresh();
	}

	applySort(data) {

		// Format the sort fields
		var fields = [];

		// Get the fields in the "sortingORder"
		for (var i = 0; i < this.sortProcessingOrder.length; i++) {
			var sort = this.sortProcessingOrder[i];

			for(var prop in this.sorting) {
				if(sort == prop && this.sorting[prop] !== "")
					fields.push(this.sorting[prop] === "asc" ? (prop) : ("-" + prop));
			}
		};

		// If server sort, just refresh
		data = data.sort(this.fieldSorter(fields));

		return data;
	}

	/* === Filtering === */
	applyFilter(data) {
		return data.filter((row) => {
			var include = true;

			for (var i = this.columns.length - 1; i >= 0; i--) {
				var col = this.columns[i];

				if(col.filterValue !== "" && row[col.field].toString().indexOf(col.filterValue) === -1) {
					include = false;
				}
			}

			return include;
		});
	}

	getFilterColumns() {
		var cols = {};

		for (var i = this.columns.length - 1; i >= 0; i--) {
			var col = this.columns[i];

			if(col.filterValue !== "")
				cols[col.field] = col.filterValue;
		}

		return cols;
	}

	debounce(func, wait) {
	    var timeout;

	    // the debounced function
	    return function() {

	        var context = this,
	            args = arguments;

	        // nulls out timer and calls original function
	        var later = function() {
	            timeout = null;
	            func.apply(context, args);
	        };

	        // restart the timer to call last function
	        clearTimeout(timeout);
	        timeout = setTimeout(later, wait);
	    };
	}

	updateFilters() {
		// Debounce

		if(!this.debouncedUpdateFilters) {
			this.debouncedUpdateFilters = this.debounce(this.refresh.bind(this), this.filterDebounce || 100);
		}

		this.debouncedUpdateFilters();
	}

	/* === Data === */
	refresh() {

		// If we have any server side stuff we need to get the data first
		this.dontWatchForChanges();

		if(this.serverPaging || this.serverSorting || this.serverFiltering || !this.initialLoad)
			this.getData();
		else
			this.filterSortPage(this.cache);

	}

	getData() {
		if(!this.read)
			throw new Error("No read method specified for grid");

		this.initialLoad = true;

		// TODO: Implement progress indicator
		this.loading = true;

		// Try to read from the data adapter
		this.read({
			sorting: this.sorting,
			paging: { page: this.pageNumber, size: Number(this.pageSize) },
			filtering: this.getFilterColumns()
		})
		.then((result) => {

			// Data should be in the result so grab it and assign it to the data property
			this.handleResult(result);

			this.loading = false;
		}, (result) => {
			// Something went terribly wrong, notify the consumer
			if(this.onReadError)
				this.onReadError(result);

			this.loading = false;
		});
	}

	handleResult(result) {

		// TODO: Check valid stuff was returned
		var data = result.data;

		// Is the data being paginated on the client side?
		// TODO: Work out when we should we use the cache... ever? If it's local data
		if(this.pageable && !this.serverPaging && !this.serverSorting && !this.serverFiltering) {
			// Cache the data
			this.cache = result.data;
			this.filterSortPage(this.cache);
		} else {
			this.data = result.data;
			this.filterSortPage(this.data);
		}

	    this.count = result.count;

	    // Update the pager - maybe the grid options should contain an update callback instead of reffing the
	    // pager into the current VM?
	    this.updatePager();
	}

	watchForChanges() {

		this.dontWatchForChanges();

		// Guard against data refresh events hitting after the user does anything that unloads the grid

		if(!this.unbinding)
		    // We can update the pager automagically
		    this.subscription = this.bindingEngine
		        .collectionObserver(this.cache)
		        .subscribe((splices) => {
					this.refresh();
		        });
	}

	dontWatchForChanges() {
		if(this.subscription)
			this.subscription.dispose();
	}

	/* === Selection === */

	select(item) {
		if(this.selectable)
			this.selectedItem = item;

		return true;
	}

	/* === Change handlers === */
	noRowsMessageChanged() {
		this.showNoRowsMessage = this.noRowsMessage !== "";
	}

	gridHeightChanged() {

		// TODO: Make this a one off
		var cont = this.element.querySelector(".grid-content-container");

		if(this.gridHeight > 0) {
			cont.setAttribute("style", "height:" + this.gridHeight + "px");
		} else {
			cont.removeAttribute("style");
		}
	}

	/* === Visual === */
	syncColumnHeadersWithColumns() {
		// Get the header row
		var headers = this.element.querySelectorAll("table>thead>tr:first-child>th");
		var filters = this.element.querySelectorAll("table>thead>tr:last-child>th");

		// Get the first row from the data if there is one...
		var cells = this.element.querySelectorAll("table>tbody>tr:first-child>td");

		for (var i = headers.length - 1; i >= 0; i--) {
			var header = headers[i];
			var filter = filters[i];
			var cell = cells[i];

			if(cell && header && filter) {
				var overflow = this.isBodyOverflowing();
				var tgtWidth = cell.offsetWidth + (i == headers.length - 1 && overflow ? this.scrollBarWidth : 0);

				// Make the header the same width as the cell...
				header.setAttribute("style", "width: " + tgtWidth + "px");
				filter.setAttribute("style", "width: " + tgtWidth + "px");
			}
		};
	}

	isBodyOverflowing() {
		var body = this.element.querySelector(".grid-content-container");
		return body.offsetHeight < body.scrollHeight || body.offsetWidth < body.scrollWidth;
	}
}

function processUserTemplate(element) {

	var cols = [];

	// Get any col tags from the content
	var rowElement = element.querySelector("grid-row");
	var columnElements = Array.prototype.slice.call(rowElement.querySelectorAll("grid-col"));

	columnElements.forEach(c => {
		var attrs = Array.prototype.slice.call(c.attributes), colHash = {};
		attrs.forEach(a => colHash[a.name] = a.value);

		var col = new GridColumn(colHash, c.innerHTML);

		cols.push(col);
	});

	// Pull any row attrs into a hash object
	var rowAttrs = {};
	var attrs = Array.prototype.slice.call(rowElement.attributes);
	attrs.forEach(a => rowAttrs[a.name] = a.value);

	return { columns: cols, rowAttrs: rowAttrs };
}


text:
@interface ASPOSEAddNewDocumentResponse : ASPOSEBaseResponse

@property(nonatomic, strong) ASPOSEHrefToDocument<Optional> *link;
@property(nonatomic, strong) NSArray<ASPOSEEmailProperty, Optional> *properties;
@property(nonatomic, strong) ASPOSEEmailCommonInfo<Optional> *document;

@end


text:
package com.openDams.bean;

public class RecordType {
	public final static int SCHEME_CONCEPT = 1;
	public final static int CONCEPT = 2;
	public final static int ARCHIVE = 3;
	public final static int RECORD = 4;
	public final static int COLLECTION = 5;
	public RecordType() {
	}
}


text:
#include "tensorflow/contrib/gdr/gdr_server_lib.h"

#include "grpc/support/alloc.h"
#include "tensorflow/contrib/gdr/gdr_collective_executor_mgr.h"
#include "tensorflow/contrib/gdr/gdr_memory_manager.h"
#include "tensorflow/contrib/gdr/gdr_rendezvous_mgr.h"
#include "tensorflow/contrib/gdr/gdr_worker.h"
#include "tensorflow/core/common_runtime/collective_rma_local.h"
#include "tensorflow/core/distributed_runtime/collective_param_resolver_distributed.h"
#include "tensorflow/core/distributed_runtime/device_resolver_distributed.h"

namespace tensorflow {

GdrServer::GdrServer(const ServerDef& server_def, Env* env)
    : GrpcServer(server_def, env) {
  string host;
  string port;
  for (const auto& job : server_def.cluster().job()) {
    if (job.name() == server_def.job_name()) {
      auto iter = job.tasks().find(server_def.task_index());
      if (iter != job.tasks().end()) {
        const std::vector<string> hostname_port =
            str_util::Split(iter->second, ':');
        if (hostname_port.size() == 2) {
          host = hostname_port[0];
          port = hostname_port[1];
        }
      }
    }
  }
  remote_memory_manager_ = std::unique_ptr<RemoteMemoryManager>(
      CreateRemoteMemoryManager(host, port));
}

GdrServer::~GdrServer() {}

Status GdrServer::Init() {
  RendezvousMgrCreationFunction rendezvous_mgr_func =
      [this](const WorkerEnv* env) {
        return new GdrRendezvousMgr(env, remote_memory_manager_.get());
      };
  WorkerCreationFunction worker_func = [this](WorkerEnv* env,
                                              const ConfigProto& config) {
    return std::unique_ptr<GdrWorker>(
        new GdrWorker(env, config, remote_memory_manager_.get()));
  };
  CollectiveMgrCreationFunction collective_mgr_func =
      [this](const ConfigProto& config, const WorkerEnv* env,
             WorkerCacheInterface* worker_cache) {
        string unused;
        string default_worker_name;
        DeviceNameUtils::SplitDeviceName(
            env->device_mgr->ListDevices()[0]->name(), &default_worker_name,
            &unused);

        std::unique_ptr<DeviceResolverDistributed> dev_resolver(
            new DeviceResolverDistributed(env->device_mgr, worker_cache,
                                          default_worker_name));
        std::unique_ptr<CollectiveParamResolverDistributed> param_resolver(
            new CollectiveParamResolverDistributed(
                config, env->device_mgr, dev_resolver.get(), worker_cache,
                default_worker_name));
        return new GdrCollectiveExecutorMgr(
            config, env->device_mgr, std::move(dev_resolver),
            std::move(param_resolver), worker_cache, default_worker_name,
            remote_memory_manager_.get());
      };
  TF_RETURN_IF_ERROR(remote_memory_manager_->Init());

  GrpcServerOptions opts;
  opts.rendezvous_mgr_func = rendezvous_mgr_func;
  opts.collective_mgr_func = collective_mgr_func;
  opts.worker_func = worker_func;
  return GrpcServer::Init(opts);
}

Status GdrServer::Start() {
  {
    mutex_lock l(mu_);
    gdr_thread_.reset(worker_env()->env->StartThread(
        ThreadOptions(), "TF_gdr_service",
        [this] { remote_memory_manager_->Run(); }));
  }
  return GrpcServer::Start();
}

Status GdrServer::Stop() {
  remote_memory_manager_->Stop();
  return GrpcServer::Stop();
}

Status GdrServer::Join() {
  {
    mutex_lock l(mu_);
    gdr_thread_.reset();
  }
  return GrpcServer::Join();
}

/* static */
Status GdrServer::Create(const ServerDef& server_def, Env* env,
                         std::unique_ptr<ServerInterface>* out_server) {
  std::unique_ptr<GdrServer> ret(
      new GdrServer(server_def, env == nullptr ? Env::Default() : env));
  TF_RETURN_IF_ERROR(ret->Init());
  *out_server = std::move(ret);
  return Status::OK();
}

namespace {

class GdrServerFactory : public ServerFactory {
 public:
  bool AcceptsOptions(const ServerDef& server_def) override {
    return server_def.protocol() == "grpc+gdr";
  }

  Status NewServer(const ServerDef& server_def,
                   std::unique_ptr<ServerInterface>* out_server) override {
    return GdrServer::Create(server_def, Env::Default(), out_server);
  }
};

// Registers a `ServerFactory` for `GdrServer` instances.
class GdrServerRegistrar {
 public:
  GdrServerRegistrar() {
    gpr_allocation_functions alloc_fns;
    memset(&alloc_fns, 0, sizeof(alloc_fns));
    alloc_fns.malloc_fn = port::Malloc;
    alloc_fns.realloc_fn = port::Realloc;
    alloc_fns.free_fn = port::Free;
    gpr_set_allocation_functions(alloc_fns);
    ServerFactory::Register("GDR_SERVER", new GdrServerFactory());
  }
};
static GdrServerRegistrar registrar;

}  // namespace
}  // namespace tensorflow