text:
import * as assert from "assert";
import * as graphene from "../src";
import { IAlgorithm, MechanismType } from "../src/mech";
import config from "./config";
import { isSoftHSM, isThalesNShield } from "./helpers";

context("AES", () => {
  let mod: graphene.Module;
  let slot: graphene.Slot;
  let session: graphene.Session;
  let secretKey: graphene.Key;

  const MSG = "1234567890123456";

  before(() => {
    mod = graphene.Module.load(config.init.lib, config.init.libName);
    mod.initialize();
    slot = mod.getSlots(config.controlValues.slot.slotIndex);
    session = slot.open();
    session.login(config.init.pin);
    if (config.init.vendor) {
      graphene.Mechanism.vendor(config.init.vendor);
    }

    secretKey = session.generateKey(graphene.KeyGenMechanism.AES, {
      keyType: graphene.KeyType.AES,
      valueLen: 192 / 8,
      encrypt: true,
      decrypt: true,
      sign: true,
      verify: true,
      wrap: true,
      unwrap: true,
      derive: true,
      token: false,
    });
  });

  after(() => {
    if (session) {
      session.logout();
    }
    mod.finalize();
  });

  function testGenerate(size: number) {
    return session.generateKey(graphene.KeyGenMechanism.AES, {
      keyType: graphene.KeyType.AES,
      valueLen: size / 8,
      encrypt: true,
      decrypt: true,
      sign: true,
      verify: true,
      wrap: true,
      unwrap: true,
      derive: true,
      token: false,
    });
  }

  it("generate AES 128", () => {
    testGenerate(128);
  });

  it("generate AES 192", () => {
    testGenerate(192);
  });

  it("generate AES 256", () => {
    testGenerate(256);
  });

  function testEncryptDecrypt(key: graphene.Key, alg: MechanismType) {
    const cipher = session.createCipher(alg, key);
    let enc = cipher.update(MSG);
    enc = Buffer.concat([enc, cipher.final()]);
    const decipher = session.createDecipher(alg, key, enc.length);
    const dec = decipher.update(enc);
    assert.strictEqual(Buffer.concat([dec, decipher.final()]).toString(), MSG, "Correct");
  }

  function testWrapUnwrap(key: graphene.Key, alg: MechanismType, sKey: graphene.Key) {
    const wKey = session.wrapKey(alg, key, sKey);
    const uKey = session.unwrapKey(alg, key, wKey, {
      class: graphene.ObjectClass.SECRET_KEY,
      keyType: graphene.KeyType.AES,
      token: false,
      valueLen: 256 / 8,
      encrypt: true,
      decrypt: true,
    });
    assert.strictEqual(!!uKey.handle, true);
  }

  it("AesCBC encrypt/decrypt", () => {
    testEncryptDecrypt(
      secretKey,
      { name: "AES_CBC", params: Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) });
  });

  it("AesCBC wrap/unwrap", () => {
    if (isSoftHSM(mod)) { return; }
    testWrapUnwrap(
      secretKey,
      { name: "AES_CBC", params: Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) },
      secretKey);
  });

  it("AesCBC derive", () => {
    const derivedKey = session.deriveKey(
      {
        name: "AES_CBC_ENCRYPT_DATA",
        params: new graphene.AesCbcEncryptDataParams(
          Buffer.from("1234567890abcdef"),
          Buffer.from("12345678901234567890123456789012"),
        ),
      },
      secretKey,
      {
        class: graphene.ObjectClass.SECRET_KEY,
        keyType: graphene.KeyType.AES,
        private: false,
        encrypt: true,
        decrypt: true,
        sensitive: false,
        extractable: true,
        valueLen: 32,
      },
    );

    assert.strictEqual(!!derivedKey, true);
  });

  it("AesCBCPad encrypt/decrypt", () => {
    testEncryptDecrypt(
      secretKey,
      { name: "AES_CBC_PAD", params: Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) });
  });

  it("AesGCM encrypt/decrypt default", () => {
    if (isThalesNShield(mod)) { return; }

    let params = new graphene.AesGcmParams(Buffer.from("123456789012"));
    if (isSoftHSM(mod)) {
      params = new graphene.AesGcm240Params(Buffer.from("123456789012"));
    }
    testEncryptDecrypt(
      secretKey,
      { name: "AES_GCM", params });
  });

  it("AesGCM encrypt/decrypt with additionalData", () => {
    if (isThalesNShield(mod)) { return; }

    let params = new graphene.AesGcmParams(Buffer.from("123456789012"), Buffer.from("additional data"));
    if (isSoftHSM(mod)) {
      params = new graphene.AesGcm240Params(Buffer.from("123456789012"), Buffer.from("additional data"));
    }
    testEncryptDecrypt(
      secretKey,
      {
        name: "AES_GCM",
        params,
      });
  });

});


text:
<?php

namespace OrganizationsORM;

use OrganizationsORM\om\BaseLovedaytestPeer;

/**
 * Skeleton subclass for performing query and update operations on the 'lovedaytest' table.
 *
 *
 *
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 * @package    propel.generator.organizations
 */
class LovedaytestPeer extends BaseLovedaytestPeer {

} // LovedaytestPeer

redpajama_set_name: RedPajamaGithub


text:
#if __IOS__ || __MACOS__
using System;
using Metal;

namespace SkiaSharp
{
	public class GRMtlBackendContext : IDisposable
	{
		public IMTLDevice Device { get; set; }

		public IMTLCommandQueue Queue { get; set; }

		protected virtual void Dispose (bool disposing)
		{
		}

		public void Dispose ()
		{
			Dispose (disposing: true);
			GC.SuppressFinalize (this);
		}
	}
}
#endif


text:
<readable><title>207275121_ee4dfa0bf2</title><content>
A brown dog running in a yard .
A dog runs on the grass in a yard , a gazebo in the background .
A dog trotting through someone 's yard .
A large brown dog is running through a grassy backyard .
Large brown dog runs through a large grassy area .
</content></readable>


text:
package net.sourceforge.mayfly.evaluation;

import net.sourceforge.mayfly.MayflyInternalException;
import net.sourceforge.mayfly.evaluation.condition.Condition;
import net.sourceforge.mayfly.evaluation.select.Evaluator;
import net.sourceforge.mayfly.util.ImmutableList;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @internal
 * Rows that we might return as part of evaluating.
 * That is, they may have aliases applied, or
 * various things other than just a cell in
 * each column.
 */
public class ResultRows implements Iterable<ResultRow> {

    private final ImmutableList<ResultRow> rows;

    public ResultRows(ResultRow singleRow) {
        this(ImmutableList.singleton(singleRow));
    }

    public ResultRows() {
        this(new ImmutableList());
    }

    public ResultRows(ImmutableList<ResultRow> rows) {
        this.rows = rows;
    }

    public int rowCount() {
        return rows.size();
    }

    public ResultRow row(int index) {
        return rows.get(index);
    }

    public Iterator<ResultRow> iterator() {
        return rows.iterator();
    }

    public ImmutableList asList() {
        return rows;
    }

    public ResultRows with(ResultRow row) {
        return new ResultRows(rows.with(row));
    }

    public ResultRows select(Condition condition) {
        return select(condition, Evaluator.NO_SUBSELECT_NEEDED);
    }

    public ResultRows select(Condition condition, Evaluator evaluator) {
        ResultRows selected = new ResultRows();
        for (ResultRow row : rows) {
            if (condition.evaluate(row, evaluator)) {
                selected = selected.with(row);
            }
        }
        return selected;
    }

    public ResultRows join(ResultRows right) {
        List result = new ArrayList();
        for (Iterator leftIterator = iterator(); leftIterator.hasNext();) {
            ResultRow leftRow = (ResultRow) leftIterator.next();
            for (Iterator rightIterator = right.iterator(); rightIterator.hasNext();) {
                ResultRow rightRow = (ResultRow) rightIterator.next();
                result.add(leftRow.combine(rightRow));
            }
        }
        return new ResultRows(new ImmutableList(result));
    }

    public ResultRow singleRow() {
        if (rowCount() != 1) {
            throw new MayflyInternalException("expected one row, got " + rowCount());
        }
        return row(0);
    }

    public String debugString() {
        StringBuilder out = new StringBuilder();
        out.append("row count = " + rowCount() + "\n");
        for (ResultRow row : rows) {
            out.append(row.debugString());
        }
        return out.toString();
    }

}


text:
import React, {Component} from 'react';
import classnames from 'classnames';

import PortalForm from './PortalForm.js';

class NewPortal extends Component {
  render() {
    return (

          My Portals

/

New Portal

          Create a New Portal

        <PortalForm
          submitText="Create Portal"
          goToMyPortals={this.props.goToMyPortals}
          csrf={this.props.csrf}
        />

    );
  }
}

export default NewPortal;


text:
#ifndef _alexa_service_h_
#define _alexa_service_h_

#ifdef __cplusplus
extern "C" {
#endif

#include    <string.h>
#include    "cjson/cjson.h"
#include    "list.h"
#include    "sys_log.h"

#include    "alexa_platform.h"
#include    "alexa_base.h"

typedef struct alexa_service alexa_service;

#include    "alexa_context.h"
#include    "alexa_speechrecognizer.h"
#include    "alexa_speechsynthesizer.h"
#include    "alexa_alerts.h"
#include    "alexa_audioplayer.h"
#include    "alexa_playbackcontroller.h"
#include    "alexa_speaker.h"
#include    "alexa_system.h"
#include    "alexa_setting.h"
#include    "alexa_directive.h"
#include    "alexa_event.h"

#include    "alexa_auth.h"
#include    "alexa_http2.h"

struct alexa_service{
    struct alexa_http2* http2;
    //SpeechRecognizer
    struct alexa_speechrecognizer* sr;

    //SpeechSynthesizer
    struct alexa_speechsynthesizer* ss;

    //Alerts
    struct alexa_alerts* alerts;

    //AudioPlayer
    struct alexa_audioplayer* ap;

    //PlayerController
    struct alexa_playbackcontroller* pc;

    //Speaker
    struct alexa_speaker* speaker;

    //System
    struct alexa_system* system;

    struct alexa_directive* directive;

    struct alexa_event* event;
};

struct alexa_service* alexa_service_init(void);

void alexa_service_process(struct alexa_service* as, struct alexa_http2* http2);

void alexa_service_done(struct alexa_service* as);

struct alexa_event* alexa_service_get_event(struct alexa_service* as);

void alexa_service_wakeup(void);

#ifdef __cplusplus
}
#endif

#endif

/*******************************************************************************
    END OF FILE
*******************************************************************************/


text:
package org.apache.samza.table.descriptors;

import java.util.Map;

import org.apache.samza.annotation.InterfaceStability;
import org.apache.samza.application.StreamApplication;
import org.apache.samza.application.TaskApplication;
import org.apache.samza.application.descriptors.StreamApplicationDescriptor;
import org.apache.samza.config.Config;
import org.apache.samza.context.TaskContext;
import org.apache.samza.operators.MessageStream;
import org.apache.samza.operators.functions.InitableFunction;
import org.apache.samza.table.Table;
import org.apache.samza.task.InitableTask;

/**
 * A {@link TableDescriptor} can be used for specifying Samza and implementation-specific properties of a {@link Table}.
 *

 * Table properties provided in configuration override corresponding properties specified using a descriptor.
 *

 * This is the base descriptor for a table. Use a implementation-specific descriptor (e.g. RocksDBTableDescriptor) to
 * use it in the application. For example:
 *
{@code
 * RocksDbTableDescriptor tableDescriptor = new RocksDbTableDescriptor("table",
 *         KVSerde.of(new IntegerSerde(), new StringSerde("UTF-8")))
 *     .withBlockSize(1024)
 *     .withConfig("some-key", "some-value");
 * }
 *

 * For High Level API {@link StreamApplication}s, use {@link StreamApplicationDescriptor#getTable(TableDescriptor)} to
 * obtain the corresponding {@link Table} instance that can be used with the {@link MessageStream} operators like
 * {@link MessageStream#sendTo(Table)}. Alternatively, use {@link TaskContext#getTable(String)} in
 * {@link InitableFunction#init} to get the table instance for use within operator functions. For Low Level API
 * {@link TaskApplication}s, use {@link TaskContext#getTable(String)} in {@link InitableTask#init} to get the
 * table instance for use within the Task.
 *
 * @param <K> the type of the key in this table
 * @param <V> the type of the value in this table
 * @param <D> the type of the concrete table descriptor
 */
@InterfaceStability.Unstable
public interface TableDescriptor<K, V, D extends TableDescriptor<K, V, D>> {

  /**
   * Get the id of the table
   * @return id of the table
   */
  String getTableId();

  /**
   * Generate configuration for this table descriptor, the generated configuration
   * should be the complete configuration for this table that can be directly
   * included in the job configuration.
   *
   * Note: although the serdes may have already been set in this instance, their
   * corresponding configuration needs to be generated centrally for consistency
   * and efficiency reasons. Therefore the serde configuration for this table
   * is expected to have already been generated and stored in the {@code jobConfig}.
   *
   * @param jobConfig job configuration
   * @return table configuration
   */
  Map<String, String> toConfig(Config jobConfig);
}


text:
Showing image previews
======================

This is a full working example of one way to add image previews to your create and
edit views in SonataAdmin.

Pre-requisites
--------------

- you have already got the image files on a server somewhere and have a helper
  method to retrieve a publicly visible URL for that image, in this example that
  method is called ``Image::getWebPath()``
- you have already set up an Admin to edit the object that contains the images,
  now you want to add the previews. In this example that class is called
  ``ImageAdmin``

.. note::

    There is a separate cookbook recipe to demonstrate how to upload images
    (and other files) using SonataAdmin.

The recipe
----------

You can use Symfony 'help' and 'help_html' options to put raw HTML into any given form field.
We are going to use this functionality to embed an image tag when an image exists.

To do this we need to:

- get access to the ``Image`` instance from within ``ImageAdmin``
- create an image tag based on the Image's URL
- add a 'help' and 'help_html' option to a field on the Image form to display the image tag

For the sake of this example we will use some basic CSS to restrict the size of
the preview image (we are not going to generate and save special thumbnails).

Basic example - for single layer Admins
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

If we are working directly with our ``ImageAdmin`` class then getting hold of
the ``Image`` instance can be done by calling ``$this->getSubject()``. Since
we are manipulating form fields we do this from within ``ImageAdmin::configureFormFields()``::

    final class ImageAdmin extends AbstractAdmin
    {
        protected function configureFormFields(FormMapper $formMapper)
        {
            // get the current Image instance
            $image = $this->getSubject();

            // use $fileFormOptions so we can add other options to the field
            $fileFormOptions = ['required' => false];
            if ($image && ($webPath = $image->getWebPath())) {
                // get the container so the full path to the image can be set
                $container = $this->getConfigurationPool()->getContainer();
                $fullPath = $container->get('request_stack')->getCurrentRequest()->getBasePath().'/'.$webPath;

                // add a 'help' option containing the preview's img tag
                $fileFormOptions['help'] = '';
                $fileFormOptions['help_html'] = true;
            }

            $formMapper
                ->add('file', 'file', $fileFormOptions)
            ;
        }
    }

We then use CSS to restrict the max size of the image:

.. code-block:: css

    img.admin-preview {
        max-height: 200px;
        max-width: 200px;
    }

And that is all there is to it!

However, this method does not work when the ``ImageAdmin`` can be embedded in other
Admins using the ``Sonata\\AdminBundle\\Form\\Type\\AdminType`` field type. For that we need...

Advanced example - works with embedded Admins
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

When one Admin is embedded in another Admin, ``$this->getSubject()`` does not return the
instance under management by the embedded Admin. Instead we need to detect that our
Admin class is embedded and use a different method::

    final class ImageAdmin extends AbstractAdmin
    {
        protected function configureFormFields(FormMapper $formMapper)
        {
            if($this->hasParentFieldDescription()) { // this Admin is embedded
                // $getter will be something like 'getlogoImage'
                $getter = 'get' . $this->getParentFieldDescription()->getFieldName();

                // get hold of the parent object
                $parent = $this->getParentFieldDescription()->getAdmin()->getSubject();
                if ($parent) {
                    $image = $parent->$getter();
                } else {
                    $image = null;
                }
            } else {
                $image = $this->getSubject();
            }

            // use $fileFormOptions so we can add other options to the field
            $fileFormOptions = ['required' => false];
            if ($image && ($webPath = $image->getWebPath())) {
                // add a 'help' option containing the preview's img tag
                $fileFormOptions['help'] = '';
                $fileFormOptions['help_html'] = true;
            }

            $formMapper
                ->add('file', 'file', $fileFormOptions)
            ;
        }
    }

As you can see, the only change is how we retrieve set ``$image`` to the relevant Image instance.
When our ImageAdmin is embedded we need to get the parent object first then use a getter to
retrieve the Image. From there on, everything else is the same.

Notes
-----

If you have more than one level of embedding Admins this will (probably) not work. If you know of
a more generic solution, please fork and update this recipe on GitHub. Similarly, if there are any
errors or typos (or a much better way to do this) get involved and share your insights for the
benefit of everyone.


text:
import numpy as np
from math import pi,cos,sin
import matplotlib.pyplot as plt
import matplotlib.animation as animation

if __name__ == '__main__':
    curr = np.array([[[0,1],[0,1]],[[2,1],[3,1]]])
    # set up figure and animation
    fig = plt.figure()
    ax = fig.add_subplot(111, aspect='equal', autoscale_on=False,
                         xlim=(-3, 3), ylim=(-3, 3))
    ax.grid()
    # dots to go on the plot
    dots, = ax.plot([], 'bo', ms=6)
    print(curr[0])

    def init():
        """initialize animation"""
        dots.set_data([], [])
        return dots,

    def animate(i):
        """perform animation step"""
        dots.set_data(np.transpose([[1,2],[2,2],[3,3]]))
        print(curr)
        return dots,

    # choose the interval based on dt and the time to animate one step
    from time import time
    t0 = time()
    animate(0)
    t1 = time()
    # interval = 1000 * dt - (t1 - t0)
    interval = 2*(t1 - t0)

    ani = animation.FuncAnimation(fig, animate, frames=3,
                                  interval=interval,
                                  blit=True,
                                  init_func=init,
                                  repeat=False,
                                  )

    # save the animation as an mp4.  This requires ffmpeg or mencoder to be
    # installed.  The extra_args ensure that the x264 codec is used, so that
    # the video can be embedded in html5.  You may need to adjust this for
    # your system: for more information, see
    # http://matplotlib.sourceforge.net/api/animation_api.html
    #ani.save('double_pendulum.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

    plt.show()


text:
package monix.reactive.observers.buffers

import monix.execution.Ack
import monix.execution.Ack.{Continue, Stop}
import monix.execution.internal.collection.JSArrayQueue
import monix.execution.internal.math.nextPowerOf2
import scala.util.control.NonFatal
import monix.reactive.observers.{BufferedSubscriber, Subscriber}

import scala.concurrent.{Future, Promise}
import scala.util.{Failure, Success}

/** Shared internals between [[BackPressuredBufferedSubscriber]] and
  * [[BatchedBufferedSubscriber]].
  */
private[observers] abstract class AbstractBackPressuredBufferedSubscriber[A,R]
  (out: Subscriber[R], _size: Int)
  extends BufferedSubscriber[A] {

  require(_size > 0, "bufferSize must be a strictly positive number")
  private[this] val bufferSize = nextPowerOf2(_size)

  private[this] val em = out.scheduler.executionModel
  implicit final val scheduler = out.scheduler

  private[this] var upstreamIsComplete = false
  private[this] var downstreamIsComplete = false
  private[this] var errorThrown: Throwable = null
  private[this] var isLoopActive = false
  private[this] var backPressured: Promise[Ack] = null
  private[this] var lastIterationAck: Future[Ack] = Continue
  protected val queue = JSArrayQueue.unbounded[A]

  final def onNext(elem: A): Future[Ack] = {
    if (upstreamIsComplete || downstreamIsComplete)
      Stop
    else if (elem == null) {
      onError(new NullPointerException("Null not supported in onNext"))
      Stop
    }
    else backPressured match {
      case null =>
        if (queue.length < bufferSize) {
          queue.offer(elem)
          pushToConsumer()
          Continue
        } else {
          backPressured = Promise[Ack]()
          queue.offer(elem)
          pushToConsumer()
          backPressured.future
        }
      case promise =>
        queue.offer(elem)
        pushToConsumer()
        promise.future
    }
  }

  final def onError(ex: Throwable): Unit = {
    if (!upstreamIsComplete && !downstreamIsComplete) {
      errorThrown = ex
      upstreamIsComplete = true
      pushToConsumer()
    }
  }

  final def onComplete(): Unit = {
    if (!upstreamIsComplete && !downstreamIsComplete) {
      upstreamIsComplete = true
      pushToConsumer()
    }
  }

  private def pushToConsumer(): Unit =
    if (!isLoopActive) {
      isLoopActive = true
      scheduler.execute(consumerRunLoop)
    }

  protected def fetchNext(): R

  private[this] val consumerRunLoop = new Runnable {
    def run(): Unit = fastLoop(lastIterationAck, 0)

    private final def signalNext(next: R): Future[Ack] =
      try {
        val ack = out.onNext(next)
        // Tries flattening the Future[Ack] to a
        // synchronous value
        if (ack == Continue || ack == Stop)
          ack
        else ack.value match {
          case Some(Success(success)) =>
            success
          case Some(Failure(ex)) =>
            downstreamSignalComplete(ex)
            Stop
          case None =>
            ack
        }
      } catch {
        case ex if NonFatal(ex) =>
          downstreamSignalComplete(ex)
          Stop
      }

    private def downstreamSignalComplete(ex: Throwable = null): Unit = {
      downstreamIsComplete = true
      try {
        if (ex != null) out.onError(ex)
        else out.onComplete()
      } catch {
        case err if NonFatal(err) =>
          scheduler.reportFailure(err)
      }
    }

    private final def goAsync(next: R, ack: Future[Ack]): Unit = {
      ack.onComplete {
        case Success(Continue) =>
          val nextAck = signalNext(next)
          val isSync = ack == Continue || ack == Stop
          val nextFrame = if (isSync) em.nextFrameIndex(0) else 0
          fastLoop(nextAck, nextFrame)

        case Success(Stop) =>
          // ending loop
          downstreamIsComplete = true
          isLoopActive = false

        case Failure(ex) =>
          // ending loop
          isLoopActive = false
          downstreamSignalComplete(ex)
      }
    }

    private def stopStreaming(): Unit = {
      downstreamIsComplete = true
      isLoopActive = false
      if (backPressured != null) {
        backPressured.success(Stop)
        backPressured = null
      }
    }

    private final def fastLoop(prevAck: Future[Ack], startIndex: Int): Unit = {
      var ack = if (prevAck == null) Continue else prevAck
      var isFirstIteration = ack == Continue
      var nextIndex = startIndex
      var streamErrors = true

      try while (isLoopActive && !downstreamIsComplete) {
        val next = fetchNext()

        if (next != null) {
          if (nextIndex > 0 || isFirstIteration) {
            isFirstIteration = false

            ack match {
              case Continue =>
                ack = signalNext(next)
                if (ack == Stop) {
                  stopStreaming()
                  return
                } else {
                  val isSync = ack == Continue
                  nextIndex = if (isSync) em.nextFrameIndex(nextIndex) else 0
                }

              case Stop =>
                stopStreaming()
                return

              case async =>
                goAsync(next, ack)
                return
            }
          }
          else {
            goAsync(next, ack)
            return
          }
        }
        else {
          // Ending loop
          if (backPressured != null) {
            backPressured.success(if (upstreamIsComplete) Stop else Continue)
            backPressured = null
          }

          streamErrors = false
          if (upstreamIsComplete)
            downstreamSignalComplete(errorThrown)

          lastIterationAck = ack
          isLoopActive = false
          return
        }
      }
      catch {
        case ex if NonFatal(ex) =>
          if (streamErrors) downstreamSignalComplete(ex)
          else scheduler.reportFailure(ex)
          lastIterationAck = Stop
          isLoopActive = false
      }
    }
  }
}


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.

package com.intellij.util;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Disposer;
import com.intellij.util.concurrency.AppExecutorUtil;
import org.jetbrains.annotations.Nullable;

import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author mike
 */
@SuppressWarnings("NonPrivateFieldAccessedInSynchronizedContext")
abstract class Timed<T> implements Disposable {
  private static final Logger LOG = Logger.getInstance("#com.intellij.util.Timed");
  private static final Map<Timed, Boolean> ourReferences = Collections.synchronizedMap(new WeakHashMap<>());
  protected static final int SERVICE_DELAY = 60;

  private int myLastCheckedAccessCount;
  int myAccessCount;
  protected T myT;
  private boolean myPolled;

  Timed(@Nullable final Disposable parentDisposable) {
    if (parentDisposable != null) {
      Disposer.register(parentDisposable, this);
    }
  }

  @Override
  public synchronized void dispose() {
    final Object t = myT;
    myT = null;
    if (t instanceof Disposable) {
      Disposer.dispose((Disposable)t);
    }

    remove();
  }

  protected final void poll() {
    if (!myPolled) {
      ourReferences.put(this, Boolean.TRUE);
      myPolled = true;
    }
  }

  protected final void remove() {
    ourReferences.remove(this);
    myPolled = false;
    myLastCheckedAccessCount = 0;
    myAccessCount = 0;
  }

  protected synchronized boolean isLocked() {
    return false;
  }

  protected synchronized boolean checkLocked() {
    return isLocked();
  }

  static {
    AppExecutorUtil.getAppScheduledExecutorService().scheduleWithFixedDelay(() -> {
      try {
        disposeTimed();
      }
      catch (Throwable e) {
        LOG.error(e);
      }
    }, SERVICE_DELAY, SERVICE_DELAY, TimeUnit.SECONDS);
  }

  public synchronized boolean isCached() {
    return myT != null;
  }

  static void disposeTimed() {
    final Timed[] references = ourReferences.keySet().toArray(new Timed[0]);
    for (Timed timed : references) {
      if (timed == null) continue;
      synchronized (timed) {
        if (timed.myLastCheckedAccessCount == timed.myAccessCount && !timed.checkLocked()) {
          Disposer.dispose(timed);
        }
        else {
          timed.myLastCheckedAccessCount = timed.myAccessCount;
        }
      }
    }
  }
}


text:
/**
 * Created by khjan on 2017-05-07.
 */
import {Directive, Attribute, Output, EventEmitter, Input} from "@angular/core";

@Directive({
    selector : '[alertMsg]',
    host : { '(click)' : 'onMouseClick()'}
})
export class AlertDirective{
    constructor(@Attribute('staticValue') private staticValue : String) {}

    @Output() outputProperty = new EventEmitter<Object>();

    onMouseClick(){
        let msg : Object = {
            'msg' : '지시자입니다',
            'static' : this.staticValue,
            'imput' : this._inputValue
        };
        this.outputProperty.emit(msg);
    }

    _inputValue : string;
    @Input() set inputValue(status : string){
        this._inputValue = status;
    }
}


text:
using namespace search::expression;
using namespace search::aggregation;

namespace search::grouping {

GroupEngine::GroupEngine(const GroupingLevel * request, size_t level, GroupEngine * nextEngine, bool frozen) :
    Collect(request->getGroupPrototype()),
    _request(request),
    _nextEngine(nextEngine),
    _idByteSize(0),
    _ids(),
    _idScratch(),
    _rank(),
    _groupBacking(),
    _level(level),
    _frozen(frozen)
{
    if ((request != NULL) && (level > 0)) {
        _idScratch.reset(request->getExpression().getResult()->clone());
    } else {
        _idScratch.reset(new NullResultNode());
    }
    _idByteSize = _idScratch->getRawByteSize();
}

GroupEngine::~GroupEngine()
{
    if (_idByteSize) {
        for (size_t i(0), m(_ids.size()/_idByteSize); i < m; i++) {
            _idScratch->destroy(&_ids[getIdBase(GroupRef(i))]);
        }
    }
    for (size_t i(0), m(_groupBacking.size()); i < m; i++) {
        delete _groupBacking[i];
    }
}

GroupRef GroupEngine::group(Children & children, uint32_t docId, double rank)
{
    const ExpressionTree &selector = _request->getExpression();
    if (!selector.execute(docId, rank)) {
        throw std::runtime_error("Does not know how to handle failed select statements");
    }
    const ResultNode &selectResult = *selector.getResult();
    Children::iterator found = children.find(selectResult);
    GroupRef gr;
    if (found == children.end()) {
        if (_request->allowMoreGroups(children.size())) {
            gr = createGroup(selectResult);
            _rank.push_back(rank);
            children.insert(gr);
        } else {
            return gr;
        }
    } else {
        gr = *found;
    }

    if (_nextEngine != NULL) {
        _nextEngine->group(*_groupBacking[gr], docId, rank);
    }

    return gr;
}

void GroupEngine::group(uint32_t docId, double rank)
{
    if (_nextEngine != NULL) {
        _nextEngine->group(*_groupBacking[0], docId, rank);
    }
}

void GroupEngine::merge(Children &, const GroupEngine &)
{
}

void GroupEngine::merge(const GroupEngine & b)
{
    if (_nextEngine != NULL) {
        _nextEngine->merge(*_groupBacking[0], *b._nextEngine);
    }
}

std::unique_ptr<GroupEngine::Children>
GroupEngine::createChildren() {
    return std::unique_ptr<Children>(new Children(0, GroupHash(*this), GroupEqual(*this)));
}

#if 0
int GroupEngine::cmpRank(GroupRef a, GroupRef b) const
{
#if 0
    return cmpAggr(a, b);
#else
#if 0
    int diff(cmpAggr(a, b));
    return diff
               ? diff
               : ((_rank[a] > _rank[b])
                   ? -1
                   : ((_rank[a] < _rank[b]) ? 1 : 0));
#else
    return (_rank[a] > _rank[b])
               ? -1
               : ((_rank[a] < _rank[b]) ? 1 : 0);
#endif
#endif
}
#endif

GroupRef GroupEngine::createGroup(const search::expression::ResultNode & v)
{
    GroupRef gr(_idByteSize ? _ids.size()/_idByteSize : 0);
    _ids.resize(getIdBase(GroupRef(gr + 1)));
    uint8_t * base(&_ids[getIdBase(gr)]);
    v.create(base);
    v.encode(base);
    if (_nextEngine != NULL) {
        _groupBacking.push_back(_nextEngine->createChildren().release());
    }
    return gr;
}

GroupRef
GroupEngine::createFullGroup(const search::expression::ResultNode & v)
{
    GroupRef gr(GroupEngine::createGroup(v));
    createCollectors(gr);
    return gr;
}

namespace {
class RadixAccess {
public:
    RadixAccess(const uint64_t * v) : _radix(v) { }
    uint64_t operator () (size_t i) const { return _radix[i]; }
private:
    const uint64_t * _radix;
};
}

Group::UP GroupEngine::getGroup(GroupRef ref) const
{
    Group::UP p(new Group(_request->getGroupPrototype()));
    Group & g(*p);
    g.setId(getGroupId(ref));
    g.setRank(_rank[ref]);
    if (_nextEngine != NULL) {
        const Children & ch(*_groupBacking[ref]);
        std::vector<GroupRef> v(ch.size());
        {
            size_t i(0);
            for (Children::const_iterator it(ch.begin()), mt(ch.end()); it != mt; it++) {
                v[i++] = *it;
            }
        }
        uint64_t maxN(_nextEngine->_request->getPrecision());
        if (maxN < v.size()) {
#if 0
            std::sort(v.begin(), v.end(), GroupRankLess(*_nextEngine));
#else
            size_t radixSorted;
            if (_nextEngine->hasSpecifiedOrder()) {
                uint64_t * radixCache = new uint64_t[v.size()];
                if (_nextEngine->isPrimarySortKeyAscending()) {
                    for (size_t i(0); i < v.size(); i++) {
                        radixCache[i] = _nextEngine->radixAggrAsc(GroupRef(i));
                    }
                } else {
                    for (size_t i(0); i < v.size(); i++) {
                        radixCache[i] = _nextEngine->radixAggrDesc(GroupRef(i));
                    }
                }
                radixSorted = ShiftBasedRadixSorter<GroupRef, RadixAccess, GroupRankLess, 56>::
                    radix_sort(RadixAccess(radixCache), GroupRankLess(*_nextEngine), &v[0], v.size(), 16, maxN);
                delete [] radixCache;
            } else {
                radixSorted = ShiftBasedRadixSorter<GroupRef, GroupRankRadix, GroupRankLess, 56>::
                    radix_sort(GroupRankRadix(*_nextEngine), GroupRankLess(*_nextEngine), &v[0], v.size(), 16, maxN);
            }
            assert(radixSorted >= maxN);
            assert(radixSorted <= v.size());
            v.resize(radixSorted);
            std::sort(v.begin(), v.end(), GroupRankLess(*_nextEngine));
#endif
            v.resize(maxN);
        }
        std::sort(v.begin(), v.end(), GroupIdLess(*_nextEngine));
        for (size_t i(0); i < v.size(); i++) {
            g.addChild(_nextEngine->getGroup(v[i]));
        }
    }
    getCollectors(ref, g);
    return p;
}

GroupRef
GroupEngine::preFillEngine(const Group & r, size_t depth)
{
    GroupRef gr;
    if (depth >= _level) {
        gr = (r.hasId())
                 ? createFullGroup(r.getId())
                 : createFullGroup(NullResultNode());
        _rank.push_back(r.getRank());
        if (_nextEngine != NULL) {
            Children & ch(*_groupBacking[gr]);
            for (size_t i(0), m(r.getChildrenSize()); i < m; i++) {
                GroupRef tmp = _nextEngine->preFillEngine(r.getChild(i), depth);
                if (tmp.valid()) {
                    ch.insert(tmp);
                }
            }
        }
        preFill(gr, r);
    }
    return gr;
}

}

// this function was added by ../../forcelink.sh
void forcelink_file_searchlib_grouping_groupengine() {}


text:
using System.Management.Automation;
using SharePointPnP.PowerShell.CmdletHelpAttributes;
using OfficeDevPnP.Core.Utilities;

namespace SharePointPnP.PowerShell.Commands
{
    [Cmdlet(VerbsCommunications.Send, "SPOMail")]
    [CmdletHelp("Sends an email using the Office 365 SMTP Service",
        Category = CmdletHelpCategory.Utilities)]
    [CmdletExample(
        Code = @"PS:> Send-SPOMail -To address@tenant.sharepointonline.com -Subject test -Body test",
        Remarks = @"Sends an e-mail using the SharePoint SendEmail method using the current context. E-mail is sent from the system account and can only be sent to accounts in the same tenant", SortOrder = 1)]
    [CmdletExample(
        Code = @"PS:> Send-SPOMail -To address@contoso.com -Subject test -Body test -From me@tenant.onmicrosoft.com -Password xyz",
        Remarks = @"Sends an e-mail via Office 365 SMTP and requires from address and password. E-mail is sent from the from user and can be sent to both internal and external addresses.", SortOrder = 2)]
    public class SendMail : SPOWebCmdlet
    {
        [Parameter(Mandatory = false)]
        public string Server = "smtp.office365.com";

        [Parameter(Mandatory = false, HelpMessage = "If using from address, you also have to provide a password")]
        public string From;

        [Parameter(Mandatory = false, HelpMessage = "If using a password, you also have to provide the associated from address")]
        public string Password;

        [Parameter(Mandatory = true)]
        public string[] To;

        [Parameter(Mandatory = false)]
        public string[] Cc;

        [Parameter(Mandatory = true)]
        public string Subject;

        [Parameter(Mandatory = true)]
        public string Body;

        protected override void ExecuteCmdlet()
        {
            if (string.IsNullOrWhiteSpace(Password) && string.IsNullOrWhiteSpace(From))
            {
                MailUtility.SendEmail(this.ClientContext, To, Cc, Subject, Body);
            }
            else
            {
                MailUtility.SendEmail(Server, From, Password, To, Cc, Subject, Body);
            }
        }
    }
}


text:
import os
import sys

from django.db.backends import BaseDatabaseClient

class DatabaseClient(BaseDatabaseClient):
    executable_name = 'mysql'

    def runshell(self):
        settings_dict = self.connection.settings_dict
        args = [self.executable_name]
        db = settings_dict['OPTIONS'].get('db', settings_dict['NAME'])
        user = settings_dict['OPTIONS'].get('user', settings_dict['USER'])
        passwd = settings_dict['OPTIONS'].get('passwd', settings_dict['PASSWORD'])
        host = settings_dict['OPTIONS'].get('host', settings_dict['HOST'])
        port = settings_dict['OPTIONS'].get('port', settings_dict['PORT'])
        defaults_file = settings_dict['OPTIONS'].get('read_default_file')
        # Seems to be no good way to set sql_mode with CLI.

        if defaults_file:
            args += ["--defaults-file=%s" % defaults_file]
        if user:
            args += ["--user=%s" % user]
        if passwd:
            args += ["--password=%s" % passwd]
        if host:
            if '/' in host:
                args += ["--socket=%s" % host]
            else:
             	args += ["--host=%s" % host]
        if port:
            args += ["--port=%s" % port]
        if db:
            args += [db]

        if os.name == 'nt':
            sys.exit(os.system(" ".join(args)))
        else:
            os.execvp(self.executable_name, args)


text:
package task.service.lvs.dto;

import java.io.Serializable;

public class RestaurantDto implements Serializable
{
    private Integer restaurantId;
    private String  restaurant;

    public RestaurantDto(Integer restaurantId, String restaurant)
    {
        this.restaurantId = restaurantId;
        this.restaurant = restaurant;
    }

    public Integer getRestaurantId()
    {
        return restaurantId;
    }

    public void setRestaurantId(Integer restaurantId)
    {
        this.restaurantId = restaurantId;
    }

    public String getRestaurant()
    {
        return restaurant;
    }

    public void setRestaurant(String restaurant)
    {
        this.restaurant = restaurant;
    }
}


text:
from __future__ import with_statement
from cms.admin.forms import PageForm
from cms.api import create_page
from cms.models import Page, Title
from cms.models.placeholdermodel import Placeholder
from cms.models.pluginmodel import CMSPlugin
from cms.plugins.text.models import Text
from cms.sitemaps import CMSSitemap
from cms.test_utils.testcases import (CMSTestCase, URL_CMS_PAGE,
    URL_CMS_PAGE_ADD)
from cms.test_utils.util.context_managers import (LanguageOverride,
    SettingsOverride)
from cms.utils.page_resolver import get_page_from_request
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.http import HttpRequest, HttpResponse, HttpResponseNotFound
import datetime
import os.path
from cms.utils.page import is_valid_page_slug

class PagesTestCase(CMSTestCase):

    def test_add_page(self):
        """
        Test that the add admin page could be displayed via the admin
        """
        superuser = self.get_superuser()
        with self.login_user_context(superuser):
            response = self.client.get(URL_CMS_PAGE_ADD)
            self.assertEqual(response.status_code, 200)

    def test_create_page(self):
        """
        Test that a page can be created via the admin
        """
        page_data = self.get_new_page_data()

        superuser = self.get_superuser()
        with self.login_user_context(superuser):
            response = self.client.post(URL_CMS_PAGE_ADD, page_data)
            self.assertRedirects(response, URL_CMS_PAGE)
            title = Title.objects.get(slug=page_data['slug'])
            self.assertNotEqual(title, None)
            page = title.page
            page.published = True
            page.save()
            self.assertEqual(page.get_title(), page_data['title'])
            self.assertEqual(page.get_slug(), page_data['slug'])
            self.assertEqual(page.placeholders.all().count(), 2)

            # were public instanes created?
            title = Title.objects.drafts().get(slug=page_data['slug'])

    def test_slug_collision(self):
        """
        Test a slug collision
        """
        page_data = self.get_new_page_data()
        # create first page
        superuser = self.get_superuser()
        with self.login_user_context(superuser):
            response = self.client.post(URL_CMS_PAGE_ADD, page_data)
            self.assertRedirects(response, URL_CMS_PAGE)

            #page1 = Title.objects.get(slug=page_data['slug']).page
            # create page with the same page_data

            response = self.client.post(URL_CMS_PAGE_ADD, page_data)

            if settings.i18n_installed:
                self.assertEqual(response.status_code, 302)
                # did we got right redirect?
                self.assertEqual(response['Location'].endswith(URL_CMS_PAGE), True)
            else:
                self.assertEqual(response.status_code, 200)
                self.assertEqual(response['Location'].endswith(URL_CMS_PAGE_ADD), True)
            # TODO: check for slug collisions after move
            # TODO: check for slug collisions with different settings

    def test_slug_collisions_api_1(self):
        """ Checks for slug collisions on sibling pages - uses API to create pages
        """
        with SettingsOverride(CMS_MODERATOR=False):
            page1 = create_page('test page 1', 'nav_playground.html', 'en',
                                published=True)
            page1_1 = create_page('test page 1_1', 'nav_playground.html', 'en',
                                  published=True, parent=page1, slug="foo")
            page1_2 = create_page('test page 1_2', 'nav_playground.html', 'en',
                                  published=True, parent=page1, slug="foo")
            # both sibling pages has same slug, so both pages has an invalid slug
            self.assertFalse(is_valid_page_slug(page1_1,page1_1.parent,"en",page1_1.get_slug("en"),page1_1.site))
            self.assertFalse(is_valid_page_slug(page1_2,page1_2.parent,"en",page1_2.get_slug("en"),page1_2.site))

    def test_slug_collisions_api_2(self):
        """ Checks for slug collisions on root (not home) page and a home page child - uses API to create pages
        """
        with SettingsOverride(CMS_MODERATOR=False):
            page1 = create_page('test page 1', 'nav_playground.html', 'en',
                                published=True)
            page1_1 = create_page('test page 1_1', 'nav_playground.html', 'en',
                                  published=True, parent=page1, slug="foo")
            page2 = create_page('test page 1_1', 'nav_playground.html', 'en',
                                  published=True, slug="foo")
            # Home page child has an invalid slug, while root page is ok. Root wins!
            self.assertFalse(is_valid_page_slug(page1_1,page1_1.parent,"en",page1_1.get_slug("en"),page1_1.site))
            self.assertTrue(is_valid_page_slug(page2,page2.parent,"en",page2.get_slug("en"),page2.site))

    def test_slug_collisions_api_3(self):
        """ Checks for slug collisions on children of a non root page - uses API to create pages
        """
        with SettingsOverride(CMS_MODERATOR=False):
            page1 = create_page('test page 1', 'nav_playground.html', 'en',
                                published=True)
            page1_1 = create_page('test page 1_1', 'nav_playground.html', 'en',
                                  published=True, parent=page1, slug="foo")
            page1_1_1 = create_page('test page 1_1_1', 'nav_playground.html', 'en',
                                  published=True, parent=page1_1, slug="bar")
            page1_1_2 = create_page('test page 1_1_1', 'nav_playground.html', 'en',
                                  published=True, parent=page1_1, slug="bar")
            page1_2 = create_page('test page 1_2', 'nav_playground.html', 'en',
                                  published=True, parent=page1, slug="bar")
            # Direct children of home has different slug so it's ok.
            self.assertTrue(is_valid_page_slug(page1_1,page1_1.parent,"en",page1_1.get_slug("en"),page1_1.site))
            self.assertTrue(is_valid_page_slug(page1_2,page1_2.parent,"en",page1_2.get_slug("en"),page1_2.site))
            # children of page1_1 has the same slug -> you lose!
            self.assertFalse(is_valid_page_slug(page1_1_1,page1_1_1.parent,"en",page1_1_1.get_slug("en"),page1_1_1.site))
            self.assertFalse(is_valid_page_slug(page1_1_2,page1_1_2.parent,"en",page1_1_2.get_slug("en"),page1_1_2.site))

    def test_details_view(self):
        """
        Test the details view
        """
        superuser = self.get_superuser()
        with self.login_user_context(superuser):
            response = self.client.get(self.get_pages_root())
            self.assertEqual(response.status_code, 404)
            page = create_page('test page 1', "nav_playground.html", "en")
            response = self.client.get(self.get_pages_root())
            self.assertEqual(response.status_code, 404)
            self.assertTrue(page.publish())
            create_page("test page 2", "nav_playground.html", "en",
                                           parent=page, published=True)
            homepage = Page.objects.get_home()
            self.assertTrue(homepage.get_slug(), 'test-page-1')
            response = self.client.get(self.get_pages_root())
            self.assertEqual(response.status_code, 200)

    def test_edit_page(self):
        """
        Test that a page can edited via the admin
        """
        superuser = self.get_superuser()
        with self.login_user_context(superuser):
            page_data = self.get_new_page_data()
            response = self.client.post(URL_CMS_PAGE_ADD, page_data)
            page =  Page.objects.get(title_set__slug=page_data['slug'])
            response = self.client.get('/admin/cms/page/%s/' %page.id)
            self.assertEqual(response.status_code, 200)
            page_data['title'] = 'changed title'
            response = self.client.post('/admin/cms/page/%s/' %page.id, page_data)
            self.assertRedirects(response, URL_CMS_PAGE)
            self.assertEqual(page.get_title(), 'changed title')

    def test_meta_description_and_keywords_fields_from_admin(self):
        """
        Test that description and keywords tags can be set via the admin
        """
        superuser = self.get_superuser()
        with self.login_user_context(superuser):
            page_data = self.get_new_page_data()
            page_data["meta_description"] = "I am a page"
            page_data["meta_keywords"] = "page,cms,stuff"
            response = self.client.post(URL_CMS_PAGE_ADD, page_data)
            page =  Page.objects.get(title_set__slug=page_data['slug'])
            response = self.client.get('/admin/cms/page/%s/' %page.id)
            self.assertEqual(response.status_code, 200)
            page_data['meta_description'] = 'I am a duck'
            response = self.client.post('/admin/cms/page/%s/' %page.id, page_data)
            self.assertRedirects(response, URL_CMS_PAGE)
            page = Page.objects.get(title_set__slug=page_data["slug"])
            self.assertEqual(page.get_meta_description(), 'I am a duck')
            self.assertEqual(page.get_meta_keywords(), 'page,cms,stuff')

    def test_meta_description_and_keywords_from_template_tags(self):
        from django import template
        superuser = self.get_superuser()
        with self.login_user_context(superuser):
            page_data = self.get_new_page_data()
            page_data["title"] = "Hello"
            page_data["meta_description"] = "I am a page"
            page_data["meta_keywords"] = "page,cms,stuff"
            self.client.post(URL_CMS_PAGE_ADD, page_data)
            page =  Page.objects.get(title_set__slug=page_data['slug'])
            self.client.post('/admin/cms/page/%s/' %page.id, page_data)
            t = template.Template("{% load cms_tags %}{% page_attribute title %} {% page_attribute meta_description %} {% page_attribute meta_keywords %}")
            req = HttpRequest()
            page.published = True
            page.save()
            req.current_page = page
            req.REQUEST = {}
            self.assertEqual(t.render(template.Context({"request": req})), "Hello I am a page page,cms,stuff")

    def test_copy_page(self):
        """
        Test that a page can be copied via the admin
        """
        page_a = create_page("page_a", "nav_playground.html", "en")
        page_a_a = create_page("page_a_a", "nav_playground.html", "en",
                                    parent=page_a)
        create_page("page_a_a_a", "nav_playground.html", "en", parent=page_a_a)

        page_b = create_page("page_b", "nav_playground.html", "en")
        page_b_a = create_page("page_b", "nav_playground.html", "en",
                                    parent=page_b)

        count = Page.objects.drafts().count()

        superuser = self.get_superuser()
        with self.login_user_context(superuser):
            self.copy_page(page_a, page_b_a)

        self.assertEqual(Page.objects.drafts().count() - count, 3)

    def test_language_change(self):
        superuser = self.get_superuser()
        with self.login_user_context(superuser):
            page_data = self.get_new_page_data()
            self.client.post(URL_CMS_PAGE_ADD, page_data)
            pk = Page.objects.all()[0].pk
            response = self.client.get("/admin/cms/page/%s/" % pk, {"language":"en" })
            self.assertEqual(response.status_code, 200)
            response = self.client.get("/admin/cms/page/%s/" % pk, {"language":"de" })
            self.assertEqual(response.status_code, 200)

    def test_move_page(self):
        superuser = self.get_superuser()
        with self.login_user_context(superuser):
            page_data1 = self.get_new_page_data()
            self.client.post(URL_CMS_PAGE_ADD, page_data1)
            page_data2 = self.get_new_page_data()
            self.client.post(URL_CMS_PAGE_ADD, page_data2)
            page_data3 = self.get_new_page_data()
            self.client.post(URL_CMS_PAGE_ADD, page_data3)
            page1 = Page.objects.all()[0]
            page2 = Page.objects.all()[1]
            page3 = Page.objects.all()[2]
            # move pages
            response = self.client.post("/admin/cms/page/%s/move-page/" % page3.pk, {"target": page2.pk, "position": "last-child"})
            self.assertEqual(response.status_code, 200)
            response = self.client.post("/admin/cms/page/%s/move-page/" % page2.pk, {"target": page1.pk, "position": "last-child"})
            self.assertEqual(response.status_code, 200)
            # check page2 path and url
            page2 = Page.objects.get(pk=page2.pk)
            self.assertEqual(page2.get_path(), page_data1['slug']+"/"+page_data2['slug'])
            self.assertEqual(page2.get_absolute_url(), self.get_pages_root()+page_data1['slug']+"/"+page_data2['slug']+"/")
            # check page3 path and url
            page3 = Page.objects.get(pk=page3.pk)
            self.assertEqual(page3.get_path(), page_data1['slug']+"/"+page_data2['slug']+"/"+page_data3['slug'])
            self.assertEqual(page3.get_absolute_url(), self.get_pages_root()+page_data1['slug']+"/"+page_data2['slug']+"/"+page_data3['slug']+"/")
            # publish page 1 (becomes home)
            page1 = Page.objects.get(pk=page1.pk)
            page1.publish()
            public_page1 = page1.publisher_public
            self.assertEqual(public_page1.get_path(), '')
            # check that page2 and page3 url have changed
            page2 = Page.objects.get(pk=page2.pk)
            page2.publish()
            public_page2 = page2.publisher_public
            self.assertEqual(public_page2.get_absolute_url(), self.get_pages_root()+page_data2['slug']+"/")
            page3 = Page.objects.get(pk=page3.pk)
            page3.publish()
            public_page3 = page3.publisher_public
            self.assertEqual(public_page3.get_absolute_url(), self.get_pages_root()+page_data2['slug']+"/"+page_data3['slug']+"/")
            # move page2 back to root and check path of 2 and 3
            response = self.client.post("/admin/cms/page/%s/move-page/" % page2.pk, {"target": page1.pk, "position": "right"})
            self.assertEqual(response.status_code, 200)
            page1 = Page.objects.get(pk=page1.pk)
            self.assertEqual(page1.get_path(), page_data1['slug'])
            page2 = Page.objects.get(pk=page2.pk)
            self.assertEqual(page2.get_path(), page_data2['slug'])
            page3 = Page.objects.get(pk=page3.pk)
            self.assertEqual(page3.get_path(), page_data2['slug']+"/"+page_data3['slug'])

    def test_move_page_inherit(self):
        parent = create_page("Parent", 'col_three.html', "en")
        child = create_page("Child", settings.CMS_TEMPLATE_INHERITANCE_MAGIC,
                            "en", parent=parent)
        self.assertEqual(child.get_template(), parent.get_template())
        child.move_page(parent, 'left')
        self.assertEqual(child.get_template(), parent.get_template())

    def test_add_placeholder(self):
        # create page
        page = create_page("Add Placeholder", "nav_playground.html", "en",
                           position="last-child", published=True, in_navigation=True)
        page.template = 'add_placeholder.html'
        page.save()
        url = page.get_absolute_url()
        response = self.client.get(url)
        self.assertEqual(200, response.status_code)
        path = os.path.join(settings.TEMPLATE_DIRS[0], 'add_placeholder.html')
        f = open(path, 'r')
        old = f.read()
        f.close()
        new = old.replace(
            '<!-- SECOND_PLACEHOLDER -->',
            '{% placeholder second_placeholder %}'
        )
        f = open(path, 'w')
        f.write(new)
        f.close()
        response = self.client.get(url)
        self.assertEqual(200, response.status_code)
        f = open(path, 'w')
        f.write(old)
        f.close()

    def test_sitemap_login_required_pages(self):
        """
        Test that CMSSitemap object contains only published,public (login_required=False) pages
        """
        create_page("page", "nav_playground.html", "en", login_required=True,
                    published=True, in_navigation=True)
        self.assertEqual(CMSSitemap().items().count(),0)

    def test_edit_page_other_site_and_language(self):
        """
        Test that a page can edited via the admin when your current site is
        different from the site you are editing and the language isn't available
        for the current site.
        """
        site = Site.objects.create(domain='otherlang', name='otherlang')
        # Change site for this session
        page_data = self.get_new_page_data()
        page_data['site'] = site.pk
        page_data['title'] = 'changed title'
        TESTLANG = settings.CMS_SITE_LANGUAGES[site.pk][0]
        page_data['language'] = TESTLANG
        superuser = self.get_superuser()
        with self.login_user_context(superuser):
            response = self.client.post(URL_CMS_PAGE_ADD, page_data)
            self.assertRedirects(response, URL_CMS_PAGE)
            page =  Page.objects.get(title_set__slug=page_data['slug'])
            with LanguageOverride(TESTLANG):
                self.assertEqual(page.get_title(), 'changed title')

    def test_flat_urls(self):
        with SettingsOverride(CMS_FLAT_URLS=True):
            home_slug = "home"
            child_slug = "child"
            grandchild_slug = "grandchild"
            home = create_page(home_slug, "nav_playground.html", "en",
                               published=True, in_navigation=True)
            home.publish()
            child = create_page(child_slug, "nav_playground.html", "en",
                                parent=home, published=True, in_navigation=True)
            child.publish()
            grandchild = create_page(grandchild_slug, "nav_playground.html", "en",
                                     parent=child, published=True, in_navigation=True)
            grandchild.publish()
            response = self.client.get(home.get_absolute_url())
            self.assertEqual(response.status_code, 200)
            response = self.client.get(child.get_absolute_url())
            self.assertEqual(response.status_code, 200)
            response = self.client.get(grandchild.get_absolute_url())
            self.assertEqual(response.status_code, 200)
            self.assertFalse(child.get_absolute_url() in grandchild.get_absolute_url())

    def test_templates(self):
        """
        Test the inheritance magic for templates
        """
        parent = create_page("parent", "nav_playground.html", "en")
        child = create_page("child", "nav_playground.html", "en", parent=parent)
        child.template = settings.CMS_TEMPLATE_INHERITANCE_MAGIC
        child.save()
        self.assertEqual(child.template, settings.CMS_TEMPLATE_INHERITANCE_MAGIC)
        self.assertEqual(parent.get_template_name(), child.get_template_name())
        parent.template = settings.CMS_TEMPLATE_INHERITANCE_MAGIC
        parent.save()
        self.assertEqual(parent.template, settings.CMS_TEMPLATE_INHERITANCE_MAGIC)
        self.assertEqual(parent.get_template(), settings.CMS_TEMPLATES[0][0])
        self.assertEqual(parent.get_template_name(), settings.CMS_TEMPLATES[0][1])

    def test_delete_with_plugins(self):
        """
        Check that plugins and placeholders get correctly deleted when we delete
        a page!
        """
        page = create_page("page", "nav_playground.html", "en")
        page.rescan_placeholders() # create placeholders
        placeholder = page.placeholders.all()[0]
        plugin_base = CMSPlugin(
            plugin_type='TextPlugin',
            placeholder=placeholder,
            position=1,
            language=settings.LANGUAGES[0][0]
        )
        plugin_base.insert_at(None, position='last-child', save=False)

        plugin = Text(body='')
        plugin_base.set_base_attr(plugin)
        plugin.save()
        self.assertEqual(CMSPlugin.objects.count(), 1)
        self.assertEqual(Text.objects.count(), 1)
        self.assertTrue(Placeholder.objects.count()  > 0)
        page.delete()
        self.assertEqual(CMSPlugin.objects.count(), 0)
        self.assertEqual(Text.objects.count(), 0)
        self.assertEqual(Placeholder.objects.count(), 0)

    def test_get_page_from_request_on_non_cms_admin(self):
        request = self.get_request(
            reverse('admin:sampleapp_category_change', args=(1,))
        )
        page = get_page_from_request(request)
        self.assertEqual(page, None)

    def test_get_page_from_request_on_cms_admin(self):
        page = create_page("page", "nav_playground.html", "en")
        request = self.get_request(
            reverse('admin:cms_page_change', args=(page.pk,))
        )
        found_page = get_page_from_request(request)
        self.assertTrue(found_page)
        self.assertEqual(found_page.pk, page.pk)

    def test_get_page_from_request_on_cms_admin_nopage(self):
        request = self.get_request(
            reverse('admin:cms_page_change', args=(1,))
        )
        page = get_page_from_request(request)
        self.assertEqual(page, None)

    def test_get_page_from_request_cached(self):
        mock_page = 'hello world'
        request = self.get_request(
            reverse('admin:sampleapp_category_change', args=(1,))
        )
        request._current_page_cache = mock_page
        page = get_page_from_request(request)
        self.assertEqual(page, mock_page)

    def test_get_page_from_request_nopage(self):
        request = self.get_request('/')
        page = get_page_from_request(request)
        self.assertEqual(page, None)

    def test_get_page_from_request_with_page_404(self):
        page = create_page("page", "nav_playground.html", "en", published=True)
        page.publish()
        request = self.get_request('/does-not-exist/')
        found_page = get_page_from_request(request)
        self.assertEqual(found_page, None)

    def test_get_page_without_final_slash(self):
        root = create_page("root", "nav_playground.html", "en", slug="root",
                           published=True)
        page = create_page("page", "nav_playground.html", "en", slug="page",
                           published=True, parent=root)
        root.publish()
        page.publish()
        request = self.get_request('/page')
        found_page = get_page_from_request(request)
        self.assertFalse(found_page is None)

    def test_get_page_from_request_with_page_preview(self):
        page = create_page("page", "nav_playground.html", "en")
        request = self.get_request('%s?preview' % page.get_absolute_url())
        request.user.is_staff = False
        found_page = get_page_from_request(request)
        self.assertEqual(found_page, None)
        superuser = self.get_superuser()
        with self.login_user_context(superuser):
            request = self.get_request('%s?preview&draft' % page.get_absolute_url())
            found_page = get_page_from_request(request)
            self.assertTrue(found_page)
            self.assertEqual(found_page.pk, page.pk)

    def test_get_page_from_request_on_cms_admin_with_editplugin(self):
        page = create_page("page", "nav_playground.html", "en")
        request = self.get_request(
            reverse('admin:cms_page_change', args=(page.pk,)) + 'edit-plugin/42/'
        )
        found_page = get_page_from_request(request)
        self.assertTrue(found_page)
        self.assertEqual(found_page.pk, page.pk)

    def test_get_page_from_request_on_cms_admin_with_editplugin_nopage(self):
        request = self.get_request(
            reverse('admin:cms_page_change', args=(1,)) + 'edit-plugin/42/'
        )
        page = get_page_from_request(request)
        self.assertEqual(page, None)

    def test_page_already_expired(self):
        """
        Test that a page which has a end date in the past gives a 404, not a
        500.
        """
        yesterday = datetime.date.today() - datetime.timedelta(days=1)
        with SettingsOverride(CMS_MODERATOR=False, CMS_PERMISSION=False):
            page = create_page('page', 'nav_playground.html', 'en',
                               publication_end_date=yesterday, published=True)
            resp = self.client.get(page.get_absolute_url('en'))
            self.assertEqual(resp.status_code, 404)

    def test_existing_overwrite_url(self):
        with SettingsOverride(CMS_MODERATOR=False, CMS_PERMISSION=False):
            create_page('home', 'nav_playground.html', 'en', published=True)
            create_page('boo', 'nav_playground.html', 'en', published=True)
            data = {
                'title': 'foo',
                'overwrite_url': '/boo/',
                'slug': 'foo',
                'language': 'en',
                'template': 'nav_playground.html',
                'site': 1,
            }
            form = PageForm(data)
            self.assertFalse(form.is_valid())
            self.assertTrue('overwrite_url' in form.errors)

    def test_page_urls(self):
        page1 = create_page('test page 1', 'nav_playground.html', 'en',
            published=True)

        page2 = create_page('test page 2', 'nav_playground.html', 'en',
            published=True, parent=page1)

        page3 = create_page('test page 3', 'nav_playground.html', 'en',
            published=True, parent=page2)

        page4 = create_page('test page 4', 'nav_playground.html', 'en',
            published=True)

        page5 = create_page('test page 5', 'nav_playground.html', 'en',
            published=True, parent=page4)

        self.assertEqual(page1.get_absolute_url(),
            self.get_pages_root()+'')
        self.assertEqual(page2.get_absolute_url(),
            self.get_pages_root()+'test-page-2/')
        self.assertEqual(page3.get_absolute_url(),
            self.get_pages_root()+'test-page-2/test-page-3/')
        self.assertEqual(page4.get_absolute_url(),
            self.get_pages_root()+'test-page-4/')
        self.assertEqual(page5.get_absolute_url(),
            self.get_pages_root()+'test-page-4/test-page-5/')

        page3 = self.move_page(page3, page1)
        self.assertEqual(page3.get_absolute_url(),
            self.get_pages_root()+'test-page-3/')

        page5 = self.move_page(page5, page2)
        self.assertEqual(page5.get_absolute_url(),
            self.get_pages_root()+'test-page-2/test-page-5/')

        page3 = self.move_page(page3, page4)
        self.assertEqual(page3.get_absolute_url(),
            self.get_pages_root()+'test-page-4/test-page-3/')

    def test_page_overwrite_urls(self):
        page1 = create_page('test page 1', 'nav_playground.html', 'en',
            published=True)

        page2 = create_page('test page 2', 'nav_playground.html', 'en',
            published=True, parent=page1)

        page3 = create_page('test page 3', 'nav_playground.html', 'en',
            published=True, parent=page2, overwrite_url='i-want-another-url')

        self.assertEqual(page2.get_absolute_url(),
            self.get_pages_root()+'test-page-2/')
        self.assertEqual(page3.get_absolute_url(),
            self.get_pages_root()+'i-want-another-url/')

        title2 = page2.title_set.get()
        title2.slug = 'page-test-2'
        title2.save()

        page2 = Page.objects.get(pk=page2.pk)
        page3 = Page.objects.get(pk=page3.pk)

        self.assertEqual(page2.get_absolute_url(),
            self.get_pages_root()+'page-test-2/')
        self.assertEqual(page3.get_absolute_url(),
            self.get_pages_root()+'i-want-another-url/')

        # tests a bug found in 2.2 where saving an ancestor page
        # wiped out the overwrite_url for child pages
        page2.save()
        self.assertEqual(page3.get_absolute_url(),
            self.get_pages_root()+'i-want-another-url/')

    def test_home_slug_not_accessible(self):
        with SettingsOverride(CMS_MODERATOR=False, CMS_PERMISSION=False):
            page = create_page('page', 'nav_playground.html', 'en', published=True)
            self.assertEqual(page.get_absolute_url('en'), '/')
            resp = self.client.get('/en/')
            self.assertEqual(resp.status_code, HttpResponse.status_code)
            resp = self.client.get('/en/page/')
            self.assertEqual(resp.status_code, HttpResponseNotFound.status_code)

    def test_public_home_page_replaced(self):
        """Test that publishing changes to the home page doesn't move the public version"""
        home = create_page('home', 'nav_playground.html', 'en', published = True, slug = 'home')
        self.assertEqual(Page.objects.drafts().get_home().get_slug(), 'home')
        home.publish()
        self.assertEqual(Page.objects.public().get_home().get_slug(), 'home')
        other = create_page('other', 'nav_playground.html', 'en', published = True, slug = 'other')
        other.publish()
        self.assertEqual(Page.objects.drafts().get_home().get_slug(), 'home')
        self.assertEqual(Page.objects.public().get_home().get_slug(), 'home')
        home = Page.objects.get(pk = home.id)
        home.in_navigation = True
        home.save()
        home.publish()
        self.assertEqual(Page.objects.drafts().get_home().get_slug(), 'home')
        self.assertEqual(Page.objects.public().get_home().get_slug(), 'home')

class NoAdminPageTests(CMSTestCase):
    urls = 'cms.test_utils.project.noadmin_urls'

    def setUp(self):
        admin = 'django.contrib.admin'
        noadmin_apps = [app for app in settings.INSTALLED_APPS if not app == admin]
        self._ctx = SettingsOverride(INSTALLED_APPS=noadmin_apps)
        self._ctx.__enter__()

    def tearDown(self):
        self._ctx.__exit__(None, None, None)

    def test_get_page_from_request_fakeadmin_nopage(self):
        request = self.get_request('/admin/')
        page = get_page_from_request(request)
        self.assertEqual(page, None)

class PreviousFilteredSiblingsTests(CMSTestCase):
    def test_with_publisher(self):
        home = create_page('home', 'nav_playground.html', 'en', published=True)
        home.publish()
        other = create_page('other', 'nav_playground.html', 'en', published=True)
        other.publish()
        other = Page.objects.get(pk=other.pk)
        home = Page.objects.get(pk=home.pk)
        self.assertEqual(other.get_previous_filtered_sibling(), home)
        self.assertEqual(home.get_previous_filtered_sibling(), None)

    def test_multisite(self):
        firstsite = Site.objects.create(name='first', domain='first.com')
        secondsite = Site.objects.create(name='second', domain='second.com')
        home = create_page('home', 'nav_playground.html', 'en', published=True, site=firstsite)
        home.publish()
        other = create_page('other', 'nav_playground.html', 'en', published=True, site=secondsite)
        other.publish()
        other = Page.objects.get(pk=other.pk)
        home = Page.objects.get(pk=home.pk)
        self.assertEqual(other.get_previous_filtered_sibling(), None)
        self.assertEqual(home.get_previous_filtered_sibling(), None)


text:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
	<persistence-unit name="pgUnit">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
		<properties>
			<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
			<property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
			<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/recomende"/>
			<property name="hibernate.connection.username" value="postgres"/>
			<property name="hibernate.connection.password" value="123456"/>
			<!-- Schema generation -->
			<property name="hibernate.hbm2ddl.auto" value="update"/>

			<!-- Indexing configs -->
			<property name="hibernate.search.default.directory_provider" value="org.hibernate.search.store.FSDirectoryProvider"/>
			<property name="hibernate.search.default.indexBase" value="/Users/mario/recomende/indexes"/>

			<!-- Debug Configuration -->
			<property name="hibernate.show_sql" value="false"/>
			<!--<property name="format_sql" value="true"/>-->
			<property name="hibernate.use_sql_comments" value="true"/>
		</properties>
	</persistence-unit>
</persistence>


text:
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.QueueTestAction = void 0;
const Hub = require("../../hub");
class QueueTestAction extends Hub.Action {
    constructor() {
        super(...arguments);
        this.name = "queue_action";
        this.label = "Test Queue";
        this.description = "Used to test process queue in unit tests";
        this.params = [];
        this.supportedActionTypes = [Hub.ActionType.Query];
        this.executeInOwnProcess = true;
    }
    execute(request) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                const result = JSON.parse(request.attachment.dataBuffer.toString());
                return new Hub.ActionResponse({ success: result.success });
            }
            catch (e) {
                return new Hub.ActionResponse({ success: false, message: "Nope" });
            }
        });
    }
}
exports.QueueTestAction = QueueTestAction;
if (process.env.CHILD_TEST) {
    Hub.addAction(new QueueTestAction());
}


text:
var config = require('../config');
var fs = require('fs');
var log = require('../log');
var ncp = require('ncp');
var path = require('path');
var prepare = require('../prepare');
var Q = require('q');

var eventIgnoreDuration = 150;
var wwwRoot = 'www';
var mergesRoot = 'merges';
var unknownFileId = '__sim-unknown__';

function Watcher(cssCb, nonCssCb) {
    this.cssChangedCallback = cssCb;
    this.nonCssChangedCallback = nonCssCb;
    this.ignoreEvents = {};
    this.mergesOverridePath = path.join(config.projectRoot, mergesRoot, config.platform);
    this.mergesOverrideExists = fs.existsSync(this.mergesOverridePath);
}

Watcher.prototype.startWatching = function () {
    this.wwwWatcher = fs.watch(path.join(config.projectRoot, wwwRoot), { recursive: true }, handleWwwWatcherEvent.bind(this));

    if (this.mergesOverrideExists) {
        this.mergesWatcher = fs.watch(path.join(config.projectRoot, mergesRoot, config.platform), { recursive: true }, handleMergesWatcherEvent.bind(this));
    }
};

Watcher.prototype.stopWatching = function () {
    if (this.wwwWatcher) {
        this.wwwWatcher.close();
        this.wwwWatcher = null;
    }

    if (this.mergesWatcher) {
        this.mergesWatcher.close();
        this.mergesWatcher = null;
    }
}

function handleWwwWatcherEvent(event, fileRelativePath) {
    handleWatcherEvent.bind(this)(wwwRoot, fileRelativePath);
}

function handleMergesWatcherEvent(event, fileRelativePath) {
    handleWatcherEvent.bind(this)(mergesRoot, fileRelativePath);
}

function handleWatcherEvent(root, fileRelativePath) {
    // fs.watch() will often send events more than once for the same modification, especially on Windows. A workaround is to block events generated by the same file for a short duration.
    var ignoreId = fileRelativePath || unknownFileId;

    if (this.ignoreEvents[ignoreId]) {
        return;
    }

    this.ignoreEvents[ignoreId] = true;
    setTimeout(function () {
        this.ignoreEvents[ignoreId] = false;
    }.bind(this), eventIgnoreDuration);

    if (!fileRelativePath) {
        // fs.watch() doesn't always set the fileRelativePath argument properly. If that happens, let the user know.
        log.warning('Could not reload the modified file because fs.watch() didn\'t specify which file was changed');

        return;
    }

    // Make sure the modified file is either JS, HTML or CSS
    if (!fileIsOfType(fileRelativePath, ['.html', '.css', '.js'])) {
        return;
    }

    // If the modified file is under www/, but has a merges/[platform]/ override, we don't do anything (because the running app is not using the file that was just modified).
    var isWww = root === wwwRoot;

    if (isWww && fileHasMergesOverride.bind(this)(fileRelativePath)) {
        return;
    }

    // Propagate the change to the served platform folder (either via Cordova prepare, or by copying the file directly).
    var preparePromise;
    var isCss = fileIsOfType(fileRelativePath, '.css');

    if (isCss) {
        if (config.prepareOnCssChange) {
            // Sometimes, especially on Windows, prepare will fail because the modified file is locked for a short duration after modification, so we try to prepare twice.
            preparePromise = retryAsync(prepare.execCordovaPrepare, 2);
        } else {
            var srcPathPrefix = isWww ? path.join(config.projectRoot, wwwRoot) : this.mergesOverridePath;
            var srcAbsolutePath = path.join(srcPathPrefix, fileRelativePath);
            var destAbsolutePath = path.join(config.platformRoot, fileRelativePath);

            preparePromise = copyFile(srcAbsolutePath, destAbsolutePath);
        }
    } else {
        // No need to prepare, because the server already does when app-host does a full reload.
        preparePromise = Q.resolve();
    }

    // Invoke the appropriate callback.
    preparePromise.then(function () {
        if (isCss) {
            this.cssChangedCallback(fileRelativePath);
        } else {
            this.nonCssChangedCallback(fileRelativePath);
        }
    }.bind(this)).done();
}

function fileIsOfType(fileRelativePath, ext) {
    var fileExt = path.extname(fileRelativePath).toLowerCase()

    function checkType(t) {
        return fileExt === t.toLowerCase();
    }

    if (Array.isArray(ext)) {
        return ext.reduce(function (isOfTypeSoFar, currentTypeToCheck) {
            return isOfTypeSoFar || checkType(currentTypeToCheck);
        }, false);
    }

    return checkType(ext);
}

function fileHasMergesOverride(fileRelativePath) {
    return this.mergesOverrideExists && fs.existsSync(path.join(this.mergesOverridePath, fileRelativePath));
}

function copyFile(src, dest) {
    return Q.nfcall(ncp, src, dest);
}

function retryAsync(promiseFunc, maxTries, delay, iteration) {
    delay = typeof delay === 'undefined' ? 100 : delay;
    iteration = typeof iteration === 'undefined' ? 1 : iteration;

    return promiseFunc().catch(function (err) {
        if (iteration < maxTries) {
            return Q.delay(delay).then(function () {
                return retryAsync(promiseFunc, maxTries, delay, iteration + 1);
            });
        }

        return Q.reject(err);
    });
}

exports.Watcher = Watcher;


text:
{{< tip >}}
{{< boilerplate gateway-api-future >}}
{{< boilerplate gateway-api-choose >}}

Note that this document uses the Gateway API to configure internal mesh (east-west) traffic,
i.e., not just ingress (north-south) traffic.
Configuring internal mesh traffic is an
[experimental feature](https://gateway-api.sigs.k8s.io/concepts/versioning/#release-channels-eg-experimental-standard)
of the Gateway API, currently under development and pending [upstream agreement](https://gateway-api.sigs.k8s.io/contributing/gamma/).
Make sure to install the experimental CRDs before using the Gateway API:

{{< text syntax=bash snip_id=install_experimental_crds >}}
$ kubectl kustomize "github.com/kubernetes-sigs/gateway-api/config/crd/experimental?ref={{< k8s_gateway_api_version >}}" | kubectl apply -f -
{{< /text >}}

{{< /tip >}}


text:
require.ensure([], function(require) {
require("./117.async.js");
require("./235.async.js");
require("./471.async.js");
require("./941.async.js");
});
module.exports = 942;


text:
@interface SamuraiHtmlElementText : UILabel
@end

#endif	// #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)


text:
license_callback({
  "domain_content": false,
  "domain_data": false,
  "domain_software": true,
  "family": "",
  "id": "apache2.0",
  "is_okd_compliant": false,
  "is_osi_compliant": true,
  "maintainer": "",
  "status": "active",
  "title": "Apache License, 2.0",
  "url": "http://www.opensource.org/licenses/apache2.0.php"
});


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Hoffmannseggia brachycarpa A.Gray

### Remarks
null


text:
from puzzle.puzzlepedia import _common
from spec.mamba import *

with description('_common_spec.format_label'):
  with it('is a no op for human readable inputs'):
    expect(_common.format_label('this is fine')).to(equal('this is fine'))

  with it('converts CamelCase'):
    expect(_common.format_label('CamelCaseWord')).to(equal('camel case word'))

  with it('converts snake_case'):
    expect(_common.format_label('snake_case_word')).to(equal('snake case word'))

with description('_common_spec.format_solution_html'):
  with it('wraps with pre tags'):
    expect(_common.preformat_html('foobar')).to(equal(
        '
foobar
'))

  with it('replaces newlines'):
    expect(_common.preformat_html('a\nb\nc')).to(equal(
        '
a
b
c
'))


text:
"""Creates a new Cloud SQL instance."""
import argparse
import logging

from googlecloudapis.apitools.base import py as apitools_base
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.core import log
from googlecloudsdk.core.util import console_io
from googlecloudsdk.core.util import list_printer
from googlecloudsdk.sql import util

class Create(base.Command):
  """Creates a new Cloud SQL instance."""

  @staticmethod
  def Args(parser):
    """Args is called by calliope to gather arguments for this command.

    Please add arguments in alphabetical order except for no- or a clear-
    pair for that argument which can follow the argument itself.
    Args:
      parser: An argparse parser that you can use to add arguments that go
          on the command line after this command. Positional arguments are
          allowed.
    """
    parser.add_argument(
        '--activation-policy',
        required=False,
        choices=['ALWAYS', 'NEVER', 'ON_DEMAND'],
        default=None,
        help='The activation policy for this instance. This specifies when the '
        'instance should be activated and is applicable only when the '
        'instance state is RUNNABLE.')
    parser.add_argument(
        '--assign-ip',
        required=False,
        action='store_true',
        help='Specified if the instance must be assigned an IP address.')
    parser.add_argument(
        '--authorized-gae-apps',
        required=False,
        nargs='+',
        type=str,
        default=[],
        help='List of App Engine app IDs that can access this instance.')
    parser.add_argument(
        '--authorized-networks',
        required=False,
        nargs='+',
        type=str,
        default=[],
        help='The list of external networks that are allowed to connect to the'
        ' instance. Specified in CIDR notation, also known as \'slash\' '
        'notation (e.g. 192.168.100.0/24).')
    parser.add_argument(
        '--backup-start-time',
        required=False,
        help='The start time of daily backups, specified in the 24 hour format '
        '- HH:MM, in the UTC timezone.')
    parser.add_argument(
        '--no-backup',
        required=False,
        action='store_true',
        help='Specified if daily backup should be disabled.')
    parser.add_argument(
        '--database-version',
        required=False,
        choices=['MYSQL_5_5', 'MYSQL_5_6'],
        default='MYSQL_5_5',
        help='The database engine type and version. Can be MYSQL_5_5 or '
        'MYSQL_5_6.')
    parser.add_argument(
        '--enable-bin-log',
        required=False,
        action='store_true',
        help='Specified if binary log should be enabled. If backup '
        'configuration is disabled, binary log must be disabled as well.')
    parser.add_argument(
        '--follow-gae-app',
        required=False,
        help='The App Engine app this instance should follow. It must be in '
        'the same region as the instance.')
    parser.add_argument(
        '--gce-zone',
        required=False,
        help='The preferred Compute Engine zone (e.g. us-central1-a, '
        'us-central1-b, etc.).')
    parser.add_argument(
        'instance',
        help='Cloud SQL instance ID.')
    parser.add_argument(
        '--master-instance-name',
        required=False,
        help='Name of the instance which will act as master in the replication '
        'setup. The newly created instance will be a read replica of the '
        'specified master instance.')
    parser.add_argument(
        '--pricing-plan',
        '-p',
        required=False,
        choices=['PER_USE', 'PACKAGE'],
        default='PER_USE',
        help='The pricing plan for this instance.')
    parser.add_argument(
        '--region',
        required=False,
        choices=['asia-east1', 'europe-west1', 'us-central', 'us-east1'],
        default='us-central',
        help='The geographical region. Can be asia-east1, europe-west1, '
        'or us-central.')
    parser.add_argument(
        '--replication',
        required=False,
        choices=['SYNCHRONOUS', 'ASYNCHRONOUS'],
        default=None,
        help='The type of replication this instance uses.')
    parser.add_argument(
        '--require-ssl',
        required=False,
        action='store_true',
        help='Specified if users connecting over IP must use SSL.')
    parser.add_argument(
        '--tier',
        '-t',
        required=False,
        default='D1',
        help='The tier of service for this instance, for example D0, D1.')
    parser.add_argument(
        '--database-flags',
        required=False,
        nargs='+',
        action=arg_parsers.AssociativeList(),
        help='A space-separated list of database flags to set on the instance. '
        'Use an equals sign to separate flag name and value. Flags without '
        'values, like skip_grant_tables, can be written out without a value '
        'after, e.g., `skip_grant_tables=`. Use on/off for '
        'booleans. View the Instance Resource API for allowed flags. '
        '(e.g., `--database-flags max_allowed_packet=55555 skip_grant_tables= '
        'log_output=1`)')
    parser.add_argument(
        '--async',
        action='store_true',
        help='Do not wait for the operation to complete.')

  @util.ReraiseHttpException
  def Run(self, args):
    """Creates a new Cloud SQL instance.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object representing the operations resource describing the create
      operation if the create was successful.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """

    # Added this temporarily for debugging SQL instance creation failures
    log.SetVerbosity(logging.DEBUG)
    sql_client = self.context['sql_client']
    sql_messages = self.context['sql_messages']
    resources = self.context['registry']

    util.ValidateInstanceName(args.instance)
    instance_ref = resources.Parse(args.instance, collection='sql.instances')

    instance_resource = util.ConstructInstanceFromArgs(sql_messages, args)

    if args.master_instance_name:
      replication = 'ASYNCHRONOUS'
      activation_policy = 'ALWAYS'
    else:
      replication = 'SYNCHRONOUS'
      activation_policy = 'ON_DEMAND'
    if not args.replication:
      instance_resource.settings.replicationType = replication
    if not args.activation_policy:
      instance_resource.settings.activationPolicy = activation_policy

    instance_resource.project = instance_ref.project
    instance_resource.instance = instance_ref.instance
    operation_ref = None

    if args.pricing_plan == 'PACKAGE':
      if not console_io.PromptContinue(
          'Charges will begin accruing immediately. Really create Cloud '
          'SQL instance?'):
        raise exceptions.ToolException('canceled by the user.')

    try:
      result = sql_client.instances.Insert(instance_resource)

      operation_ref = resources.Create(
          'sql.operations',
          operation=result.operation,
          project=instance_ref.project,
          instance=instance_ref.instance,
      )

      if args.async:
        return sql_client.operations.Get(operation_ref.Request())

      util.WaitForOperation(
          sql_client, operation_ref, 'Creating Cloud SQL instance')

      log.CreatedResource(instance_ref)

      return sql_client.instances.Get(instance_ref.Request())
    except apitools_base.HttpError:
      log.debug('operation : %s', str(operation_ref))
      raise

  def Display(self, unused_args, result):
    """Display prints information about what just happened to stdout.

    Args:
      unused_args: The same as the args in Run.
      result: The database created, or the operation if async.
    """
    if result.kind == 'sql#instance':
      list_printer.PrintResourceList('sql.instances', [result])
    else:
      self.format(result)


text:
This section describes details of how MDM functionality is implemented in HAPI FHIR.

# Automatic Linking

With MDM enabled, the default behavior of the MDM is to create a new Golden Record for every source record that is created such that there is a 1:1 relationship between them. Any relinking is then expected to be done manually via the [MDM Operations](/hapi-fhir/docs/server_jpa_mdm/mdm_operations.html).

In a typical configuration it is often desirable to have links created automatically using matching rules. For example, you might decide that if a Patient shares the same name, gender, and date of birth as another Patient, you have at least a little confidence that they are the same Patient.

This automatic linking is done via configurable matching rules that create links between source record and Golden Record. Based on the strength of the match configured in these rules, the link will be set to either POSSIBLE_MATCH or MATCH.

It is important to note that before a resource is processed by MDM, it is first checked to ensure that it has at least one attribute that the MDM system cares about, as defined in the `mdm-rules.json` file. If the incoming resource has no such attributes, then MDM processing does not occur on it. In this case, no Golden Resource is created for this source resource. If in the future the source resource is updated to contain attributes the MDM system does concern itself with, it will be processed at that time.

## Design

Below are some simplifying principles HAPI MDM follows to reduce complexity and ensure data integrity.

1. When MDM is enabled on a HAPI FHIR server, any Golden Resource in the repository that has the "hapi-mdm" tag is considered read-only by the FHIR endpoint. These Golden Resources are managed exclusively by HAPI MDM. Users can only change them via [MDM Operations](/hapi-fhir/docs/server_jpa_mdm/mdm_operations.html).  In most cases, users will indirectly change them by creating and updating the corresponding source resources.

1. Every source resource in the system has a MATCH link to at most one Golden Resource.

1. The only source resources in the system that do not have a MATCH link are those that have the 'NO-MDM' tag or those that have POSSIBLE_MATCH links pending review.

1. The HAPI MDM rules define a single identifier system that holds the external enterprise id ("EID"). If a source resource has an external EID, then the Golden Resource it links to always has the same EID. If a source resource has no EID when it arrives, a unique UUID will be assigned as that source resource's EID.

1. A Golden Resource can have both an internal EID (auto-created by HAPI), and an external EID (provided by an
external system).

1. Two different Golden Resources cannot have the same EID.

1. Source resources are only ever compared to Golden Resources via this EID.

## Links

1. HAPI MDM manages mdm-link records ("links") that link a source resource to a Golden Resource. When these are created/updated by matching rules, the links are marked as AUTO.  When these links are changed manually, they are marked as MANUAL.

1. Once a link has been manually assigned as NO_MATCH or MATCH, the system will not change it.

1. When a new source resource is created/updated it is then compared to all other source resources of the same type in the repository. The outcome of each of these comparisons is either NO_MATCH, POSSIBLE_MATCH or MATCH.

1. HAPI MDM stores these extra link details in a table called `MPI_LINK`.

### Possible rule match outcomes:

When a new source resource is compared with all other resources of the same type in the repository, there are four possible outcomes:

* CASE 1: No MATCH and no POSSIBLE_MATCH outcomes -> a new Golden Resource is created and linked to that source resource as MATCH. If the incoming resource has an EID, it is copied to the Golden Resource. Otherwise a new UUID is generated and used as the internal EID.

* CASE 2: All of the MATCH source resources are already linked to the same Golden Resource -> a new Link is created between the new source resource and that Golden Resource and is set to MATCH.

* CASE 3: The MATCH source resources link to more than one Golden Resource -> Mark all links as POSSIBLE_MATCH.  All other Golden Resources are marked as POSSIBLE_DUPLICATE of this first Golden Resource. These duplicates are manually reviewed later and either merged or marked as NO_MATCH and the system will no longer consider them as a POSSIBLE_DUPLICATE going forward. POSSIBLE_DUPLICATE is the only link type that can have a Golden Resource as both the source and target of the link.

* CASE 4: Only POSSIBLE_MATCH outcomes -> In this case, new POSSIBLE_MATCH links are created and await manual reassignment to either NO_MATCH or MATCH.

# HAPI MDM Technical Details

When MDM is enabled, the HAPI FHIR JPA Server does the following things on startup:

1. It enables the MESSAGE subscription type and starts up the internal subscription engine.
1. It creates MESSAGE subscriptions for each resource type prefixed with 'mdm-'. For example, if MDM supports Patient and Practitioner resource, two subscriptions, called 'mdm-patient' and 'mdm-practitioner' that match all incoming MDM managed resources and send them to an internal queue called "mdm". The JPA Server listens to this queue and links incoming resources to the appropriate Golden Resources.
1. The [MDM Operations](/hapi-fhir/docs/server_jpa_mdm/mdm_operations.html) are registered with the server.
1. It registers a new dao interceptor that restricts access to MDM managed Golden Resource records.


text:
#include "AnyInt.h"
#include "IntArgb.h"
#include "IntArgbBm.h"
#include "AlphaMacros.h"

#include "IntArgbPre.h"
#include "IntRgb.h"
#include "ByteIndexed.h"
#include "Index12Gray.h"

/*
 * This file declares, registers, and defines the various graphics
 * primitive loops to manipulate surfaces of type "IntArgb".
 *
 * See also LoopMacros.h
 */

RegisterFunc RegisterIntArgb;

DECLARE_CONVERT_BLIT(Index12Gray, IntArgb);
DECLARE_XOR_BLIT(IntArgb, IntArgb);
DECLARE_SRC_MASKFILL(IntArgb);
DECLARE_SRCOVER_MASKFILL(IntArgb);
DECLARE_ALPHA_MASKFILL(IntArgb);
DECLARE_SRCOVER_MASKBLIT(IntArgb, IntArgb);
DECLARE_ALPHA_MASKBLIT(IntArgb, IntArgb);
DECLARE_SRCOVER_MASKBLIT(IntArgbPre, IntArgb);
DECLARE_ALPHA_MASKBLIT(IntArgbPre, IntArgb);
DECLARE_ALPHA_MASKBLIT(IntRgb, IntArgb);
DECLARE_SOLID_DRAWGLYPHLISTAA(IntArgb);
DECLARE_SOLID_DRAWGLYPHLISTLCD(IntArgb);
DECLARE_XPAR_SCALE_BLIT(IntArgbBm, IntArgb);

DECLARE_TRANSFORMHELPER_FUNCS(IntArgb);

NativePrimitive IntArgbPrimitives[] = {
    REGISTER_ANYINT_ISOCOPY_BLIT(IntArgb),
    REGISTER_ANYINT_ISOSCALE_BLIT(IntArgb),
    REGISTER_CONVERT_BLIT(ByteIndexed, IntArgb),
    REGISTER_CONVERT_BLIT(Index12Gray, IntArgb),
    REGISTER_SCALE_BLIT(ByteIndexed, IntArgb),
    REGISTER_XPAR_CONVERT_BLIT(ByteIndexedBm, IntArgb),
    REGISTER_XPAR_SCALE_BLIT(ByteIndexedBm, IntArgb),
    REGISTER_XPAR_SCALE_BLIT(IntArgbBm, IntArgb),
    REGISTER_XPAR_BLITBG(ByteIndexedBm, IntArgb),

    REGISTER_XOR_BLIT(IntArgb, IntArgb),
    REGISTER_SRC_MASKFILL(IntArgb),
    REGISTER_SRCOVER_MASKFILL(IntArgb),
    REGISTER_ALPHA_MASKFILL(IntArgb),
    REGISTER_SRCOVER_MASKBLIT(IntArgb, IntArgb),
    REGISTER_ALPHA_MASKBLIT(IntArgb, IntArgb),
    REGISTER_SRCOVER_MASKBLIT(IntArgbPre, IntArgb),
    REGISTER_ALPHA_MASKBLIT(IntArgbPre, IntArgb),
    REGISTER_ALPHA_MASKBLIT(IntRgb, IntArgb),
    REGISTER_SOLID_DRAWGLYPHLISTAA(IntArgb),
    REGISTER_SOLID_DRAWGLYPHLISTLCD(IntArgb),

    REGISTER_TRANSFORMHELPER_FUNCS(IntArgb),
};

jboolean RegisterIntArgb(JNIEnv *env)
{
    return RegisterPrimitives(env, IntArgbPrimitives,
                              ArraySize(IntArgbPrimitives));
}

DEFINE_CONVERT_BLIT_LUT8(ByteIndexed, IntArgb, ConvertOnTheFly)

DEFINE_CONVERT_BLIT_LUT8(Index12Gray, IntArgb, ConvertOnTheFly)

DEFINE_SCALE_BLIT_LUT8(ByteIndexed, IntArgb, ConvertOnTheFly)

DEFINE_XPAR_CONVERT_BLIT_LUT8(ByteIndexedBm, IntArgb, ConvertOnTheFly)

DEFINE_XPAR_SCALE_BLIT_LUT8(ByteIndexedBm, IntArgb, ConvertOnTheFly)

DEFINE_XPAR_SCALE_BLIT(IntArgbBm, IntArgb, 1IntRgb)

DEFINE_XPAR_BLITBG_LUT8(ByteIndexedBm, IntArgb, ConvertOnTheFly)

DEFINE_XOR_BLIT(IntArgb, IntArgb, AnyInt)

DEFINE_SRC_MASKFILL(IntArgb, 4ByteArgb)

DEFINE_SRCOVER_MASKFILL(IntArgb, 4ByteArgb)

DEFINE_ALPHA_MASKFILL(IntArgb, 4ByteArgb)

DEFINE_SRCOVER_MASKBLIT(IntArgb, IntArgb, 4ByteArgb)

DEFINE_ALPHA_MASKBLIT(IntArgb, IntArgb, 4ByteArgb)

DEFINE_SRCOVER_MASKBLIT(IntArgbPre, IntArgb, 4ByteArgb)

DEFINE_ALPHA_MASKBLIT(IntArgbPre, IntArgb, 4ByteArgb)

DEFINE_ALPHA_MASKBLIT(IntRgb, IntArgb, 4ByteArgb)

DEFINE_SOLID_DRAWGLYPHLISTAA(IntArgb, 4ByteArgb)

DEFINE_SOLID_DRAWGLYPHLISTLCD(IntArgb, 4ByteArgb)

DEFINE_TRANSFORMHELPERS(IntArgb)


text:
import sys
import random

# hmm, annoying that you have to keep names unique across files :|
# since I like to use foo and bar ALL the time :D

def rd_foo():
    print('rd_foo')

def rd_bar():
    print('rd_bar')

if len(sys.argv) >= 2 and not sys.argv[1] in ['0', 'False', 'false']:
    func = rd_foo
else:
    func = rd_bar

func() # $ pt=rd_foo pt=rd_bar

# Random doesn't work with points-to :O
if random.random() < 0.5:
    func2 = rd_foo
else:
    func2 = rd_bar

func2() # $ pt=rd_foo pt=rd_bar