text:
from __future__ import unicode_literals

import datetime
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('vtn', '0022_auto_20171114_1718'),
    ]

    operations = [
        migrations.CreateModel(
            name='Report',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('report_specifier_id', models.CharField(blank=True, max_length=100, null=True)),
                ('report_request_id', models.CharField(blank=True, max_length=100, null=True)),
                ('start', models.CharField(blank=True, max_length=100, null=True)),
                ('end', models.CharField(blank=True, max_length=100, null=True)),
                ('state', models.CharField(choices=[('scheduled', 'scheduled'), ('active', 'active'), ('completed', 'completed'), ('cancelled', 'cancelled')], default='scheduled', max_length=100)),
                ('site', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vtn.Site')),
            ],
        ),
        migrations.RemoveField(
            model_name='reports',
            name='site',
        ),
        migrations.AlterField(
            model_name='drevent',
            name='last_status_time',
            field=models.DateTimeField(blank=True, default=datetime.datetime(2017, 11, 14, 18, 1, 14, 433165), null=True, verbose_name='Last Status Time'),
        ),
        migrations.AlterField(
            model_name='siteevent',
            name='last_opt_in',
            field=models.DateTimeField(blank=True, default=datetime.datetime(2017, 11, 14, 18, 1, 14, 435059), null=True, verbose_name='Last opt-in'),
        ),
        migrations.AlterField(
            model_name='siteevent',
            name='last_status_time',
            field=models.DateTimeField(default=datetime.datetime(2017, 11, 14, 18, 1, 14, 434927), verbose_name='Last Status Time'),
        ),
        migrations.DeleteModel(
            name='Reports',
        ),
        migrations.AddField(
            model_name='report',
            name='site_event',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vtn.SiteEvent'),
        ),
    ]


text:
package com.adobe.acs.commons.wcm.vanity.impl;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.RequestPathInfo;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.wrappers.SlingHttpServletRequestWrapper;

public class ExtensionlessRequestWrapper extends SlingHttpServletRequestWrapper {

    private static final String SLING_STATUS = "sling:status";

    public ExtensionlessRequestWrapper(SlingHttpServletRequest wrappedRequest) {
        super(wrappedRequest);
    }

    public RequestPathInfo getRequestPathInfo() {
        return new RequestPathInfoWrapper(super.getRequestPathInfo(), super.getResource());
    }

    private class RequestPathInfoWrapper implements RequestPathInfo {
        private final RequestPathInfo requestPathInfo;
        private final Resource resource;

        public RequestPathInfoWrapper(RequestPathInfo requestPathInfo, Resource resource) {
            this.requestPathInfo = requestPathInfo;
            this.resource = resource;
        }

        public String getResourcePath() {
            return requestPathInfo.getResourcePath();
        }

        public String getExtension() {
            final ValueMap properties = resource.getValueMap();
            if (properties != null) {
                if (properties.get(SLING_STATUS, -1) < 0) {
                    // Internal redirect; so keep extension
                    return requestPathInfo.getExtension();
                } else {
                    // External redirect; like 301 or 302 then kill the extension else it gets double added. Note this will also kill any selector addition.
                    return null;
                }
            } else {
                return requestPathInfo.getExtension();
            }
        }

        public String getSelectorString() {
            return requestPathInfo.getSelectorString();
        }

        public String[] getSelectors() {
            return requestPathInfo.getSelectors();
        }

        public String getSuffix() {
            return requestPathInfo.getSuffix();
        }

        public Resource getSuffixResource() {
            return requestPathInfo.getSuffixResource();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package ua.edu.cdu.fotius.lisun.musicplayer.utils;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class DatabaseUtils {
    private static final String TAG = "DatabaseUtils";
    /**
     * @return newly created list id
     */
    public static long createPlaylist(Context context, String name) {
        ContentValues values = new ContentValues(1);
        values.put(AudioStorage.Playlist.PLAYLIST, name);
        ContentResolver resolver = context.getContentResolver();
        Uri uri = resolver.insert(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, values);
        //TODO: uri == null if this playlist already exists
        return ContentUris.parseId(uri);
    }

    /**
     * @return added tracks quantity
     */
    public static int addToPlaylist(Context context, long playlistId, long[] trackIds) {
        ContentResolver resolver = context.getContentResolver();
        Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId);

        Cursor cursor = resolver.query(uri, null, null, null, null);
        int lastInPlayOrder = cursor.getColumnCount();
        cursor.close();

        List valuesList = new ArrayList();
        for (int i = 0; i < trackIds.length; i++) {
            cursor = resolver.query(uri, new String[]{AudioStorage.PlaylistMember.TRACK_ID},
                    AudioStorage.PlaylistMember.TRACK_ID + "=?",
                    new String[]{Long.toString(trackIds[i])}, null);
            /*if this track already exists don't add it*/
            if (cursor.getCount() == 0) {
                ContentValues cv = new ContentValues();
                cv.put(AudioStorage.PlaylistMember.PLAY_ORDER, lastInPlayOrder + i);
                cv.put(AudioStorage.PlaylistMember.TRACK_ID, trackIds[i]);
                valuesList.add(cv);
            }
            cursor.close();
        }
        ContentValues[] contentValues = new ContentValues[valuesList.size()];
        valuesList.toArray(contentValues);
        return resolver.bulkInsert(uri, contentValues);
    }

    public static String queryAlbumArtPath(Context context, long albumID) {
        ContentResolver contentResolver = context.getContentResolver();

        Uri uri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
        String[] projection = new String[]{AudioStorage.Album.ALBUM_ART};
        String selection = AudioStorage.Album.ALBUM_ID + "=?";
        String[] selectionArgs = new String[]{Long.toString(albumID)};

        Cursor c = contentResolver.query(uri, projection, selection, selectionArgs, null);

        String path = null;
        if (c != null) {
            if (c.moveToFirst()) {
                path = c.getString(c.getColumnIndexOrThrow(AudioStorage.Album.ALBUM_ART));
            }
            c.close();
        }
        return path;
    }

    public static long[] queryAlbumsTracks(Context context, long artistID, long[] albumsID) {
        ArrayList<Long> tracksID = new ArrayList<>();
        StringBuffer selectionBuffer = new StringBuffer();
        selectionBuffer.append(AudioStorage.Track.ALBUM_ID + " = ?");
        if (artistID != AudioStorage.WRONG_ID) {
            selectionBuffer.append(" AND " + AudioStorage.Track.ARTIST_ID + " = ?");
        }

        for (int i = 0; i < albumsID.length; i++) {
            String[] selectionArgs = (artistID != AudioStorage.WRONG_ID)
                    ? new String[]{Long.toString(albumsID[i]), Long.toString(artistID)}
                    : new String[]{Long.toString(albumsID[i])};
            tracksID.addAll(queryTracks(context, selectionBuffer.toString(), selectionArgs));
        }
        return toPrimitiveArray(tracksID);
    }

    public static long[] queryArtistsTracks(Context context, long[] artistsID) {
        ArrayList<Long> tracksID = new ArrayList<>();
        String selection = AudioStorage.Track.ARTIST_ID + " = ?";
        for (int i = 0; i < artistsID.length; i++) {
            String[] selectionArgs = new String[]{Long.toString(artistsID[i])};
            tracksID.addAll(queryTracks(context, selection, selectionArgs));
        }
        return toPrimitiveArray(tracksID);
    }

    private static ArrayList<Long> queryTracks(Context context, String selection, String[] selectionArgs) {
        ContentResolver contentResolver = context.getContentResolver();

        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String[] projection = new String[]{
                AudioStorage.Track.TRACK_ID
        };

        Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, null);

        ArrayList<Long> trackIds = new ArrayList<>();
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int columnIdx = 0;
                while (!cursor.isAfterLast()) {
                    columnIdx = cursor.getColumnIndexOrThrow(AudioStorage.Track.TRACK_ID);
                    trackIds.add(cursor.getLong(columnIdx));
                    cursor.moveToNext();
                }
            }
            cursor.close();
        }
        return trackIds;
    }

    public static String makeInBody(long[] ids) {
        if ((ids != null) && (ids.length > 0)) {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(ids[0]);
            for (int i = 1; i < ids.length; i++) {
                stringBuffer.append(", " + ids[i]);
            }
            return stringBuffer.toString();
        }
        return ("");
    }

    private static long[] toPrimitiveArray(ArrayList<Long> list) {
        Long[] objectsArray = list.toArray(new Long[list.size()]);
        long[] array = new long[objectsArray.length];
        for (int i = 0; i < objectsArray.length; i++) {
            array[i] = objectsArray[i];
        }
        return array;
    }

    //TODO: only for debug
//    public static void queryParamsInLog(Uri uri, String[] projection, String selection, String[] selectionArgs) {
//        if (uri != null) {
//            Log.d(TAG, "Uri: " + uri.toString());
//        }
//
//        if (projection != null) {
//            Log.d(TAG, "Projection: ");
//            for (int i = 0; i < projection.length; i++) {
//                Log.d(TAG, projection[i]);
//            }
//        }
//
//        if (selection != null) {
//            Log.d(TAG, "Selection: " + selection);
//        }
//
//        if (selectionArgs != null) {
//            Log.d(TAG, "SelectionArgs: ");
//            for (int i = 0; i < selectionArgs.length; i++) {
//                Log.d(TAG, selectionArgs[i]);
//            }
//        }
//    }
}


text:
require_relative '../../spec_helper'
require_lib 'reek/smells/too_many_instance_variables'
require_relative 'smell_detector_shared'

RSpec.describe Reek::Smells::TooManyInstanceVariables do
  let(:detector) { build(:smell_detector, smell_type: :TooManyInstanceVariables) }

  it_should_behave_like 'SmellDetector'

  def default_max_ivars
    Reek::Smells::TooManyInstanceVariables::DEFAULT_MAX_IVARS
  end

  def too_many_ivars
    default_max_ivars + 1
  end

  def ivar_sequence(count: default_max_ivars, alphabet: ('a'..'z').to_a)
    alphabet.first(count).map do |name|
      "@#{name}=#{rand}"
    end.join(',')
  end

  context 'counting instance variables' do
    it 'should not report for non-excessive ivars' do
      src = <<-EOS
        class Empty
          def ivars
           #{ivar_sequence}
          end
        end
      EOS
      expect(src).not_to reek_of(:TooManyInstanceVariables)
    end

    it 'counts each ivar only once' do
      src = <<-EOS
        class Empty
          def ivars
           #{ivar_sequence}
           #{ivar_sequence}
          end
        end
      EOS
      expect(src).not_to reek_of(:TooManyInstanceVariables)
    end

    it 'should report excessive ivars' do
      src = <<-EOS
        class Empty
          def ivars
            #{ivar_sequence(count: too_many_ivars)}
          end
        end
      EOS
      expect(src).to reek_of(:TooManyInstanceVariables)
    end

    it 'should not report for ivars in 2 extensions' do
      src = <<-EOS
        class Full
          def ivars_a
            #{ivar_sequence}
          end
        end

        class Full
          def ivars_b
            #{ivar_sequence}
          end
        end
      EOS
      expect(src).not_to reek_of(:TooManyInstanceVariables)
    end
  end

  context 'when a smell is reported' do
    let(:warning) do
      src = <<-EOS
        # Comment
        class Empty
          def ivars
            #{ivar_sequence(count: too_many_ivars)}
          end
        end
      EOS
      ctx = Reek::Context::CodeContext.new(nil, Reek::Source::SourceCode.from(src).syntax_tree)
      detector.inspect(ctx).first
    end

    it_should_behave_like 'common fields set correctly'

    it 'reports the correct values' do
      expect(warning.parameters[:count]).to eq(too_many_ivars)
      expect(warning.lines).to eq([2])
    end
  end
end


text:
'use strict';

var grunt = require('grunt');

exports.cssmin = {
  main: function(test) {
    test.expect(1);

    var expect = grunt.file.read('test/expected/style.css');
    var result = grunt.file.read('tmp/style.css');
    test.equal(expect, result, 'should concat and minify an array of css files in order using clean-css');

    test.done();
  },
  with_banner: function(test) {
    test.expect(1);

    var expect = grunt.file.read('test/expected/with-banner.css');
    var result = grunt.file.read('tmp/with-banner.css');
    test.equal(expect, result, 'should concat, minify and prefix banner');

    test.done();
  },
  empty: function(test) {
    test.expect(1);

    test.ok(!grunt.file.exists('tmp/idontexist.css'), 'Empty minified file should not exist');

    test.done();
  },
  remove_first_comment: function(test) {
    test.expect(1);

    var expect = grunt.file.read('test/expected/input_bannered.css');
    var result = grunt.file.read('tmp/remove_first_comment.css');
    test.equal(expect, result, 'should minify and replace banner');

    test.done();
  },
  imports: function(test) {
    test.expect(1);

    var expect = grunt.file.read('test/expected/inline_import.css');
    var result = grunt.file.read('tmp/inline_import.css');
    test.equal(expect, result, 'should inline @import');

    test.done();
  }
};


text:
package db

//go:generate counterfeiter . PipelineDBFactory

type PipelineDBFactory interface {
	Build(pipeline SavedPipeline) PipelineDB
	BuildWithID(pipelineID int) (PipelineDB, error)
	BuildWithTeamNameAndName(teamName, pipelineName string) (PipelineDB, error)
	BuildDefault() (PipelineDB, bool, error)
}

type pipelineDBFactory struct {
	conn        Conn
	bus         *notificationsBus
	pipelinesDB PipelinesDB
}

func NewPipelineDBFactory(
	sqldbConnection Conn,
	bus *notificationsBus,
	pipelinesDB PipelinesDB,
) *pipelineDBFactory {
	return &pipelineDBFactory{
		conn:        sqldbConnection,
		bus:         bus,
		pipelinesDB: pipelinesDB,
	}
}

func (pdbf *pipelineDBFactory) BuildWithID(pipelineID int) (PipelineDB, error) {
	savedPipeline, err := pdbf.pipelinesDB.GetPipelineByID(pipelineID)
	if err != nil {
		return nil, err
	}

	return pdbf.Build(savedPipeline), nil
}

func (pdbf *pipelineDBFactory) BuildWithTeamNameAndName(teamName, pipelineName string) (PipelineDB, error) {
	savedPipeline, err := pdbf.pipelinesDB.GetPipelineByTeamNameAndName(teamName, pipelineName)
	if err != nil {
		return nil, err
	}

	return pdbf.Build(savedPipeline), nil
}

func (pdbf *pipelineDBFactory) Build(pipeline SavedPipeline) PipelineDB {
	return &pipelineDB{
		conn: pdbf.conn,
		bus:  pdbf.bus,

		SavedPipeline: pipeline,
	}
}

func (pdbf *pipelineDBFactory) BuildDefault() (PipelineDB, bool, error) {
	orderedPipelines, err := pdbf.pipelinesDB.GetAllPipelines()
	if err != nil {
		return nil, false, err
	}

	if len(orderedPipelines) < 1 {
		return nil, false, nil
	}

	return &pipelineDB{
		conn: pdbf.conn,
		bus:  pdbf.bus,

		SavedPipeline: orderedPipelines[0],
	}, true, nil
}


text:
<?php

/**
 * PHP version 7.3
 *
 * @category OrderStatusItem
 * @package  RetailCrm\Api\Model\Entity\Orders
 */

namespace RetailCrm\Api\Model\Entity\Orders;

use RetailCrm\Api\Component\Serializer\Annotation as JMS;

/**
 * Class OrderStatusItem
 *
 * @category OrderStatusItem
 * @package  RetailCrm\Api\Model\Entity\Orders
 */
class OrderStatusItem
{
    /**
     * @var int
     *
     * @JMS\Type("int")
     * @JMS\SerializedName("id")
     */
    public $id;

    /**
     * @var string
     *
     * @JMS\Type("string")
     * @JMS\SerializedName("externalId")
     */
    public $externalId;

    /**
     * @var string
     *
     * @JMS\Type("string")
     * @JMS\SerializedName("status")
     */
    public $status;

    /**
     * @var string
     *
     * @JMS\Type("string")
     * @JMS\SerializedName("group")
     */
    public $group;
}


text:
class RunningMeanEstimatorTest : public CppUnit::TestFixture {

    CPPUNIT_TEST_SUITE(RunningMeanEstimatorTest);
    CPPUNIT_TEST(testSimple);
    CPPUNIT_TEST_SUITE_END();

  public:
    void testSimple();
};

#endif


text:
2-sat
=====
[2SAT](http://en.wikipedia.org/wiki/2-satisfiability) is a restricted version of the boolean satisfiability problem where the number of variables per clause is at most 2.  Works both in node.js and in the browser using browserify.

## Example

```javascript
var twoSat = require("2-sat")

//Solve problem:
//
//    (x1 | !x2) & (x3 | x1) & (x3 | x2)
//
console.log(twoSat(3, [[1, -2], [3, 1], [3,2]]))
```

## API

### `require("2-sat")(numVariables, clauses)`
Finds a satisfying assignment for a 2SAT problem written in conjunctive normal form.  If no assignment is possible returns `false`.

* `numVariables` is the number of variables
* `clauses` is a list of binary clauses.  Variables are indexed in clauses starting at `1` and negative values indicate negation.

**Returns** A vector of assignments to the variables of the clause.  If problem is not satisfiable, returns `false`

## Credits
(c) 2013 Mikola Lysenko. MIT License


text:
package org.apache.accumulo.server.conf;

import static org.apache.accumulo.core.conf.Property.GC_PORT;
import static org.apache.accumulo.core.conf.Property.TSERV_NATIVEMAP_ENABLED;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

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

import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.conf.SiteConfiguration;
import org.junit.jupiter.api.Test;

public class RuntimeFixedPropertiesTest {

  @Test
  public void defaultTest() {
    var siteConfig = SiteConfiguration.fromEnv().build();
    Map<String,String> storedProps = new HashMap<>();

    RuntimeFixedProperties fixed = new RuntimeFixedProperties(storedProps, siteConfig);

    assertEquals("true", fixed.get(Property.TSERV_NATIVEMAP_ENABLED));
  }

  @Test
  public void storedOverrideTest() {
    var siteConfig = SiteConfiguration.fromEnv().build();
    Map<String,String> storedProps = Map.of("tserver.memory.maps.native.enabled", "false");

    RuntimeFixedProperties fixed = new RuntimeFixedProperties(storedProps, siteConfig);

    assertEquals("false", fixed.get(Property.TSERV_NATIVEMAP_ENABLED));
  }

  @Test
  public void allTest() {
    var siteConfig = SiteConfiguration.fromEnv().build();
    Map<String,String> storedProps = new HashMap<>();

    RuntimeFixedProperties fixed = new RuntimeFixedProperties(storedProps, siteConfig);

    assertEquals(Property.fixedProperties.size(), fixed.getAll().size());
  }

  @Test
  public void changedTest() {
    var siteConfig = SiteConfiguration.fromEnv().build();
    Map<String,String> storedProps = Map.of(TSERV_NATIVEMAP_ENABLED.getKey(), "false");

    RuntimeFixedProperties fixed = new RuntimeFixedProperties(storedProps, siteConfig);

    // prop removed - changed
    assertTrue(fixed.hasChanged(Map.of()));

    // prop modified - changed
    assertTrue(fixed.hasChanged(Map.of(TSERV_NATIVEMAP_ENABLED.getKey(), "true")));

    // prop added - changed
    assertTrue(fixed
        .hasChanged(Map.of(TSERV_NATIVEMAP_ENABLED.getKey(), "false", GC_PORT.getKey(), "1234")));

    // same - no change
    assertFalse(fixed.hasChanged(storedProps));

  }
}


text:
semantic.table = {};

// ready event
semantic.table.ready = function() {

  // selector cache
  var
    // alias
    handler
  ;

};

// attach ready event
$(document)
  .ready(semantic.table.ready)
;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>类 com.asteroid.model.TagAdd的使用</title>
<meta name="date" content="2014-06-21">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

概览

程序包

类

使用

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类

类 com.asteroid.model.TagAdd
的使用

使用TagAdd的程序包

程序包
说明

com.asteroid.controller.daoVO

com.asteroid.controller.tagAdd

com.asteroid.controller.daoVO中TagAdd的使用

返回变量类型为TagAdd的类型的com.asteroid.controller.daoVO中的方法

限定符和类型
方法和说明

java.util.List<TagAdd>
ReleaseVO.getTagList()

类型变量类型为TagAdd的com.asteroid.controller.daoVO中的方法参数

限定符和类型
方法和说明

void
ReleaseVO.setTagList(java.util.List<TagAdd> tagList)

com.asteroid.controller.tagAdd中TagAdd的使用

返回变量类型为TagAdd的类型的com.asteroid.controller.tagAdd中的方法

限定符和类型
方法和说明

java.util.List<TagAdd>
TagAddDao.findAll()

返回所有添加的标签数据

java.util.List<TagAdd>
TagAddDao.findAllById(int user_id)

按个人id查找添加的标签

参数类型为TagAdd的com.asteroid.controller.tagAdd中的方法

限定符和类型
方法和说明

boolean
TagAddDao.save(TagAdd tagAdd)

添加标签

概览

程序包

类

使用

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类


text:
namespace Nancy.ViewEngines.DotLiquid
{
    using Responses;
    using System;
    using System.Collections.Generic;
    using System.Dynamic;
    using System.IO;
    using global::DotLiquid;
    using global::DotLiquid.FileSystems;
    using global::DotLiquid.NamingConventions;
    using global::DotLiquid.Exceptions;

    /// <summary>
    /// View engine for rendering dotLiquid views.
    /// </summary>
    public class DotLiquidViewEngine : IViewEngine
    {
        private readonly IFileSystemFactory fileSystemFactory;
        private readonly INamingConvention namingConvention;

        /// <summary>
        /// Initializes a new instance of the <see cref="DotLiquidViewEngine"/> class.
        /// </summary>
        /// <param name="namingConvention">Determines the DotLiquid naming convention that will be used for filters and Drops. This will default to the <c>RubyNamingConvention</c>.</param>
        /// <remarks>The instance will use the <see cref="DefaultFileSystemFactory"/> internally.</remarks>
        public DotLiquidViewEngine(INamingConvention namingConvention)
            : this(new DefaultFileSystemFactory(), namingConvention)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DotLiquidViewEngine"/> class.
        /// </summary>
        /// <param name="fileSystemFactory">Factory used to retrieve the <see cref="IFileSystem"/> instance that should be used by the engine.</param>
        /// <param name="namingConvention">The naming convention used by filters and DotLiquid's <c>Drop</c>s</param>
        public DotLiquidViewEngine(IFileSystemFactory fileSystemFactory, INamingConvention namingConvention)
        {
            this.fileSystemFactory = fileSystemFactory;
            this.namingConvention = namingConvention;
        }

        /// <summary>
        /// Gets the extensions file extensions that are supported by the view engine.
        /// </summary>
        /// <value>An <see cref="IEnumerable{T}"/> instance containing the extensions.</value>
        /// <remarks>The extensions should not have a leading dot in the name.</remarks>
        public IEnumerable<string> Extensions
        {
            get { yield return "liquid"; }
        }

        /// <summary>
        /// Initialise the view engine (if necessary)
        /// </summary>
        /// <param name="viewEngineStartupContext">Startup context</param>
        public void Initialize(ViewEngineStartupContext viewEngineStartupContext)
        {
            Template.FileSystem = this.fileSystemFactory.GetFileSystem(viewEngineStartupContext, this.Extensions);
            Template.NamingConvention = this.namingConvention;
        }

        /// <summary>
        /// Renders the view.
        /// </summary>
        /// <param name="viewLocationResult">A <see cref="ViewLocationResult"/> instance, containing information on how to get the view template.</param>
        /// <param name="model">The model that should be passed into the view</param>
        /// <param name="renderContext"></param>
        /// <returns>A response</returns>
        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
        {
            Template parsed;
            Hash hashedModel;
            HttpStatusCode status;

            try
            {
                // Set the parsed template
                parsed = renderContext.ViewCache.GetOrAdd(
                    viewLocationResult,
                    x =>
                    {
                        using (var reader = viewLocationResult.Contents.Invoke())
                            return Template.Parse(reader.ReadToEnd());
                    });

                hashedModel = Hash.FromAnonymousObject(new
                {
                    Model = new DynamicDrop(model),
                    ViewBag = new DynamicDrop(renderContext.Context.ViewBag)
                });

                // If we got past that, we have a good response
                status = HttpStatusCode.OK;

            }
            catch (SyntaxException syntaxException)
            {
                // Syntax Exceptions cause a 500
                status = HttpStatusCode.InternalServerError;

                // Build the error message
                String errorMessage = String.Format("Syntax error in liquid view '{0}':\r\n\r\n{1}",
                    String.Format("{0}/{1}.{2}", viewLocationResult.Location, viewLocationResult.Name, viewLocationResult.Extension),
                    syntaxException.Message);

                // Create the error model with a Nancy DynamicDictionary because i can ;)
                DynamicDictionary errorModel = new DynamicDictionary();
                errorModel.Add(new KeyValuePair<string, dynamic>("ErrorMessage", errorMessage));

                // Hash up the Error model so DotLiquid will understand it
                hashedModel =
                    Hash.FromAnonymousObject(new
                    {
                        Model = new DynamicDrop(errorModel)
                    });

                // Grab the error HTML from the embedded resource and build up the DotLiquid template.
                String errorHtml = LoadResource(@"500.liquid");
                parsed = Template.Parse(errorHtml);
            }
            catch (Exception ex)
            {
                status = HttpStatusCode.InternalServerError;
                // Build the error message
                String errorMessage = String.Format("Error: {0}", ex.Message);

                // Create the error model with a Nancy DynamicDictionary because i can ;)
                DynamicDictionary errorModel = new DynamicDictionary();
                errorModel.Add(new KeyValuePair<string, dynamic>("ErrorMessage", errorMessage));

                // Hash up the Error model so DotLiquid will understand it
                hashedModel =
                    Hash.FromAnonymousObject(new
                    {
                        Model = new DynamicDrop(errorModel)
                    });

                // Grab the error HTML from the embedded resource
                String errorHtml = LoadResource(@"500.liquid");
                parsed = Template.Parse(errorHtml);
            }

            // Build the response
            return new HtmlResponse(statusCode: status, contents: stream =>
            {
                parsed.Render(stream, new RenderParameters
                {
                    LocalVariables = hashedModel,
                    Registers = Hash.FromAnonymousObject(new { nancy = renderContext })
                });
            });
        }

        private static string LoadResource(string filename)
        {
            var resourceStream = typeof(DotLiquidViewEngine).Assembly.GetManifestResourceStream(String.Format("Nancy.ViewEngines.DotLiquid.Resources.{0}", filename));

            if (resourceStream == null)
            {
                return string.Empty;
            }

            using (var reader = new StreamReader(resourceStream))
            {
                return reader.ReadToEnd();
            }
        }
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Gentiana krauseana Gilg

### Remarks
null


text:
package org.apache.shardingsphere.encrypt.yaml.config;

import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.underlying.common.yaml.config.YamlConfiguration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Encrypt table rule configuration.
 */
@Getter
@Setter
public final class YamlEncryptTableRuleConfiguration implements YamlConfiguration {

    private Map<String, YamlEncryptColumnRuleConfiguration> columns = new LinkedHashMap<>();
}


text:
ACCEPTED

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

#### Published in
null

#### Original name
Saccolabium odoratissimum Ridl.

### Remarks
null


text:
@extends('layouts.app')

@section('content')

            <tasks></tasks>
            <currency></currency>

            <sports></sports>

            <github></github>
            <news></news>

@endsection


text:
var Node = function(key) { // Trie Nodes
  this.key      = key;
  this.isWord   = false;
  this.children = {};
};

Node.prototype.addChild = function(str) {
  this.children[str] = new Node(str);
};

Node.prototype.hasChild = function(str) {
  var result = false;
  Object.keys(this.children).forEach(function(key) {
    if(key == str)
      result = true;
  });
  return result;
};

var Trie = function() {
  this.head = new Node();
};

Trie.prototype.addWord = function(word) {
  var len         = word.length;
  var substring   = "";
  var currentNode = this.head;

  for(var x = 1; x <= len; x++) { // Traverse the Trie
    substring = word.substring(0, x);
    if(!currentNode.hasChild(substring)) // Create node if it doesn't exist
      currentNode.addChild(substring);
    currentNode = currentNode.children[substring];
  }
  currentNode.isWord = true;
};

Trie.prototype.findNode = function(str) { // Returns the node or false if not found
  var len         = str.length;
  var substring   = "";
  var currentNode = this.head;

  for(var x = 1; x <= len; x++) {
    substring = str.substring(0, x);
    if(!currentNode.hasChild(substring))
      return false;
    currentNode = currentNode.children[substring];
  }
  return currentNode;
};

Trie.prototype.valid = function(str) { // Returns an array with two elements. If the node exists, and if str is a word
  var node = this.findNode(str);
  if(node)
    return [true, node.isWord];
  return [false, false];
};


text:
configureTwitter = function() {
  // remove any previous configuration
  ServiceConfiguration.configurations.remove({
    service: "twitter"
  });
  ServiceConfiguration.configurations.insert(Meteor.settings.app_keys.twitter);
};


text:
from __future__ import annotations

import glob
import os
import shutil
import signal
import sys
import threading
import time
import unittest
from pathlib import Path
from textwrap import dedent

import psutil
import pytest

from pants.testutil.pants_integration_test import read_pants_log, setup_tmpdir, temporary_workdir
from pants.util.contextutil import environment_as, temporary_dir, temporary_file
from pants.util.dirutil import rm_rf, safe_file_dump, safe_mkdir, safe_open, safe_rmtree, touch
from pants_test.pantsd.pantsd_integration_test_base import (
    PantsDaemonIntegrationTestBase,
    launch_waiter,
)

def launch_file_toucher(f):
    """Launch a loop to touch the given file, and return a function to call to stop and join it."""
    if not os.path.isfile(f):
        raise AssertionError("Refusing to touch a non-file.")

    halt = threading.Event()

    def file_toucher():
        while not halt.isSet():
            touch(f)
            time.sleep(1)

    thread = threading.Thread(target=file_toucher)
    thread.daemon = True
    thread.start()

    def join():
        halt.set()
        thread.join(timeout=10)

    return join

compilation_failure_dir_layout = {
    os.path.join("compilation_failure", "main.py"): "if __name__ == '__main__':\n    import sys¡",
    os.path.join(
        "compilation_failure", "BUILD"
    ): "python_sources()\npex_binary(name='bin', entry_point='main.py')",
}

class TestPantsDaemonIntegration(PantsDaemonIntegrationTestBase):
    hermetic = False

    def test_pantsd_run(self):
        with self.pantsd_successful_run_context(log_level="debug") as ctx:
            with setup_tmpdir({"foo/BUILD": "target()"}) as tmpdir:
                ctx.runner(["list", f"{tmpdir}/foo::"])
                ctx.checker.assert_started()

                ctx.runner(["list", f"{tmpdir}/foo::"])
                ctx.checker.assert_running()

    def test_pantsd_broken_pipe(self):
        with self.pantsd_test_context() as (workdir, pantsd_config, checker):
            run = self.run_pants_with_workdir(
                "help | head -1",
                workdir=workdir,
                config=pantsd_config,
                shell=True,
                # FIXME: Why is this necessary to set?
                set_pants_ignore=False,
            )
            self.assertNotIn("broken pipe", run.stderr.lower())
            checker.assert_started()

    def test_pantsd_pantsd_runner_doesnt_die_after_failed_run(self):
        with self.pantsd_test_context() as (workdir, pantsd_config, checker):
            # Run target that throws an exception in pants.
            with setup_tmpdir(compilation_failure_dir_layout) as tmpdir:
                self.run_pants_with_workdir(
                    ["lint", os.path.join(tmpdir, "compilation_failure", "main.py")],
                    workdir=workdir,
                    config=pantsd_config,
                ).assert_failure()
            checker.assert_started()

            # Assert pantsd is in a good functional state.
            self.run_pants_with_workdir(
                ["help"], workdir=workdir, config=pantsd_config
            ).assert_success()
            checker.assert_running()

    def test_pantsd_lifecycle_invalidation(self):
        """Run with different values of daemon=True options, which should trigger restarts."""
        with self.pantsd_successful_run_context() as ctx:
            last_pid = None
            for idx in range(3):
                # Run with a different value of a daemon=True option in each iteration.
                ctx.runner([f"--pantsd-invalidation-globs=ridiculous{idx}", "help"])
                next_pid = ctx.checker.assert_started()
                if last_pid is not None:
                    assert last_pid != next_pid
                last_pid = next_pid

    def test_pantsd_lifecycle_invalidation_from_auth_plugin(self) -> None:
        """If the dynamic remote options changed, we should reinitialize the scheduler but not
        restart the daemon."""
        plugin = dedent(
            """\
            from datetime import datetime
            from pants.option.global_options import AuthPluginState, AuthPluginResult

            def auth_func(
                initial_execution_headers, initial_store_headers, options, env, prior_result
            ):
                # If the first run, don't change the headers, but use the `expiration` as a
                # sentinel so that future runs know to change it.
                if prior_result is None:
                    return AuthPluginResult(
                        state=AuthPluginState.OK,
                        execution_headers=initial_execution_headers,
                        store_headers=initial_store_headers,
                        expiration=datetime.min,
                    )

                # If second run, still don't change the headers, but update the `expiration` as a
                # sentinel for the next run.
                if prior_result.expiration == datetime.min:
                    return AuthPluginResult(
                        state=AuthPluginState.OK,
                        execution_headers=initial_execution_headers,
                        store_headers=initial_store_headers,
                        expiration=datetime.max,
                    )

                # Finally, on the third run, change the headers.
                if prior_result.expiration == datetime.max:
                    return AuthPluginResult(
                        state=AuthPluginState.OK,
                        execution_headers={"custom": "foo"},
                        store_headers=initial_store_headers,
                    )

                # If there was a fourth run, or `prior_result` didn't preserve the `expiration`
                # field properly, error.
                raise AssertionError(f"Unexpected prior_result: {prior_result}")
            """
        )
        with self.pantsd_successful_run_context() as ctx:

            def run_auth_plugin() -> tuple[str, int]:
                # This very hackily traverses up to the process's parent directory, rather than the
                # workdir.
                plugin_dir = Path(ctx.workdir).parent.parent / "auth_plugin"
                plugin_dir.mkdir(parents=True, exist_ok=True)
                (plugin_dir / "__init__.py").touch()
                (plugin_dir / "auth.py").write_text(plugin)
                sys.path.append(str(plugin_dir))
                try:
                    result = ctx.runner(
                        [
                            "--pythonpath=auth_plugin",
                            "--remote-auth-plugin=auth_plugin.auth:auth_func",
                            "--remote-cache-read",
                            "--remote-store-address=grpc://fake",
                            "help",
                        ]
                    )
                finally:
                    sys.path.pop()
                    shutil.rmtree(plugin_dir)
                return result.stderr, ctx.checker.assert_started()

            first_stderr, first_pid = run_auth_plugin()
            assert (
                "Initializing scheduler" in first_stderr
                or "reinitializing scheduler" in first_stderr
            )

            second_stderr, second_pid = run_auth_plugin()
            assert "reinitializing scheduler" not in second_stderr
            assert first_pid == second_pid

            third_stderr, third_pid = run_auth_plugin()
            assert "reinitializing scheduler" in third_stderr
            assert second_pid == third_pid

    def test_pantsd_lifecycle_non_invalidation(self):
        with self.pantsd_successful_run_context() as ctx:
            cmds = (["help"], ["--no-colors", "help"], ["help"])
            last_pid = None
            for cmd in cmds:
                # Run with a CLI flag.
                ctx.runner(cmd)
                next_pid = ctx.checker.assert_started()
                if last_pid is not None:
                    self.assertEqual(last_pid, next_pid)
                last_pid = next_pid

    def test_pantsd_lifecycle_non_invalidation_on_config_string(self):
        with temporary_dir() as dist_dir_root, temporary_dir() as config_dir:
            # Create a variety of config files that change an option that does _not_ affect the
            # daemon's fingerprint (only the Scheduler's), and confirm that it stays up.
            config_files = [
                os.path.abspath(os.path.join(config_dir, f"pants.{i}.toml")) for i in range(3)
            ]
            for idx, config_file in enumerate(config_files):
                print(f"writing {config_file}")
                with open(config_file, "w") as fh:
                    fh.write(
                        f"""[GLOBAL]\npants_distdir = "{os.path.join(dist_dir_root, str(idx))}"\n"""
                    )

            with self.pantsd_successful_run_context() as ctx:
                cmds = [[f"--pants-config-files={f}", "help"] for f in config_files]
                last_pid = None
                for cmd in cmds:
                    ctx.runner(cmd)
                    next_pid = ctx.checker.assert_started()
                    if last_pid is not None:
                        self.assertEqual(last_pid, next_pid)
                    last_pid = next_pid

    def test_pantsd_lifecycle_shutdown_for_broken_scheduler(self):
        with self.pantsd_test_context() as (workdir, config, checker):
            # Run with valid options.
            self.run_pants_with_workdir(["help"], workdir=workdir, config=config).assert_success()
            checker.assert_started()

            # And again with invalid scheduler-fingerprinted options that trigger a re-init.
            self.run_pants_with_workdir(
                ["--backend-packages=nonsensical", "help"], workdir=workdir, config=config
            ).assert_failure()
            checker.assert_stopped()

    def test_pantsd_aligned_output(self) -> None:
        # Set for pytest output display.
        self.maxDiff = None

        cmds = [["help", "goals"], ["help", "targets"], ["roots"]]

        config = {
            "GLOBAL": {
                # These must match the ones we configure in pantsd_integration_test_base.py.
                "backend_packages": ["pants.backend.python", "pants.backend.python.lint.flake8"],
            }
        }
        non_daemon_runs = [self.run_pants(cmd, config=config) for cmd in cmds]

        with self.pantsd_successful_run_context() as ctx:
            daemon_runs = [ctx.runner(cmd) for cmd in cmds]
            ctx.checker.assert_started()

        for cmd, run in zip(cmds, daemon_runs):
            print(f"(cmd, run) = ({cmd}, {run.stdout}, {run.stderr})")
            self.assertNotEqual(run.stdout, "", f"Empty stdout for {cmd}")

        for run_pair in zip(non_daemon_runs, daemon_runs):
            non_daemon_stdout = run_pair[0].stdout
            daemon_stdout = run_pair[1].stdout

            for line_pair in zip(non_daemon_stdout.splitlines(), daemon_stdout.splitlines()):
                assert line_pair[0] == line_pair[1]

    @unittest.skip("flaky: https://github.com/pantsbuild/pants/issues/7622")
    @pytest.mark.no_error_if_skipped
    def test_pantsd_filesystem_invalidation(self):
        """Runs with pantsd enabled, in a loop, while another thread invalidates files."""
        with self.pantsd_successful_run_context() as ctx:
            cmd = ["list", "::"]
            ctx.runner(cmd)
            ctx.checker.assert_started()

            # Launch a separate thread to poke files in 3rdparty.
            join = launch_file_toucher("3rdparty/jvm/com/google/auto/value/BUILD")

            # Repeatedly re-list 3rdparty while the file is being invalidated.
            for _ in range(0, 16):
                ctx.runner(cmd)
                ctx.checker.assert_running()

            join()

    def test_pantsd_client_env_var_is_inherited_by_pantsd_runner_children(self):
        expected_key = "TEST_ENV_VAR_FOR_PANTSD_INTEGRATION_TEST"
        expected_value = "333"
        with self.pantsd_successful_run_context() as ctx:
            # First, launch the daemon without any local env vars set.
            ctx.runner(["help"])
            ctx.checker.assert_started()

            # Then, set an env var on the secondary call.
            # We additionally set the `HERMETIC_ENV` env var to allow the integration test harness
            # to pass this variable through.
            env = {
                expected_key: expected_value,
                "HERMETIC_ENV": expected_key,
            }
            with environment_as(**env):
                result = ctx.runner(
                    ["run", "testprojects/src/python/print_env:binary", "--", expected_key]
                )
                ctx.checker.assert_running()

            self.assertEqual(expected_value, "".join(result.stdout).strip())

    def test_pantsd_launch_env_var_is_not_inherited_by_pantsd_runner_children(self):
        with self.pantsd_test_context() as (workdir, pantsd_config, checker):
            with environment_as(NO_LEAKS="33"):
                self.run_pants_with_workdir(
                    ["help"], workdir=workdir, config=pantsd_config
                ).assert_success()
                checker.assert_started()

            self.run_pants_with_workdir(
                ["run", "testprojects/src/python/print_env:binary", "--", "NO_LEAKS"],
                workdir=workdir,
                config=pantsd_config,
            ).assert_failure()
            checker.assert_running()

    def test_pantsd_touching_a_file_does_not_restart_daemon(self):
        test_file = "testprojects/src/python/print_env/main.py"
        config = {
            "GLOBAL": {"pantsd_invalidation_globs": '["testprojects/src/python/print_env/*"]'}
        }
        with self.pantsd_successful_run_context(extra_config=config) as ctx:
            ctx.runner(["help"])
            ctx.checker.assert_started()

            # Let any fs events quiesce.
            time.sleep(5)

            ctx.checker.assert_running()

            touch(test_file)
            # Permit ample time for the async file event propagate in CI.
            time.sleep(10)
            ctx.checker.assert_running()

    def test_pantsd_invalidation_file_tracking(self):
        test_dir = "testprojects/src/python/print_env"
        config = {"GLOBAL": {"pantsd_invalidation_globs": f'["{test_dir}/*"]'}}
        with self.pantsd_successful_run_context(extra_config=config) as ctx:
            ctx.runner(["help"])
            ctx.checker.assert_started()

            # Let any fs events quiesce.
            time.sleep(5)
            ctx.checker.assert_running()

            def full_pants_log():
                return "\n".join(read_pants_log(ctx.workdir))

            # Create a new file in test_dir
            with temporary_file(suffix=".py", binary_mode=False, root_dir=test_dir) as temp_f:
                temp_f.write("import that\n")
                temp_f.close()

                ctx.checker.assert_stopped()

            self.assertIn("saw filesystem changes covered by invalidation globs", full_pants_log())

    def test_pantsd_invalidation_pants_toml_file(self):
        # Test tmp_pants_toml (--pants-config-files=$tmp_pants_toml)'s removal
        tmp_pants_toml = os.path.abspath("testprojects/test_pants.toml")

        # Create tmp_pants_toml file
        with safe_open(tmp_pants_toml, "w") as f:
            f.write("[DEFAULT]\n")

        with self.pantsd_successful_run_context() as ctx:
            ctx.runner([f"--pants-config-files={tmp_pants_toml}", "help"])
            ctx.checker.assert_started()
            time.sleep(10)

            # Delete tmp_pants_toml
            os.unlink(tmp_pants_toml)
            ctx.checker.assert_stopped()

    def test_pantsd_pid_deleted(self):
        with self.pantsd_successful_run_context() as ctx:
            ctx.runner(["help"])
            ctx.checker.assert_started()

            # Let any fs events quiesce.
            time.sleep(10)

            ctx.checker.assert_running()
            subprocess_dir = ctx.pantsd_config["GLOBAL"]["pants_subprocessdir"]
            safe_rmtree(subprocess_dir)

            ctx.checker.assert_stopped()

    def test_pantsd_pid_change(self):
        with self.pantsd_successful_run_context() as ctx:
            ctx.runner(["help"])
            ctx.checker.assert_started()

            # Let any fs events quiesce.
            time.sleep(10)

            ctx.checker.assert_running()
            subprocess_dir = ctx.pantsd_config["GLOBAL"]["pants_subprocessdir"]
            (pidpath,) = glob.glob(os.path.join(subprocess_dir, "*", "pantsd", "pid"))
            with open(pidpath, "w") as f:
                f.write("9")

            ctx.checker.assert_stopped()

            # Remove the pidfile so that the teardown script doesn't try to kill process 9.
            os.unlink(pidpath)

    @pytest.mark.skip(reason="flaky: https://github.com/pantsbuild/pants/issues/8193")
    @pytest.mark.no_error_if_skipped
    def test_pantsd_memory_usage(self):
        """Validates that after N runs, memory usage has increased by no more than X percent."""
        number_of_runs = 10
        max_memory_increase_fraction = 0.40  # TODO https://github.com/pantsbuild/pants/issues/7647
        with self.pantsd_successful_run_context() as ctx:
            # NB: This doesn't actually run against all testprojects, only those that are in the chroot,
            # i.e. explicitly declared in this test file's BUILD.
            cmd = ["list", "testprojects::"]
            ctx.runner(cmd).assert_success()
            initial_memory_usage = ctx.checker.current_memory_usage()
            for _ in range(number_of_runs):
                ctx.runner(cmd).assert_success()
                ctx.checker.assert_running()

            final_memory_usage = ctx.checker.current_memory_usage()
            self.assertTrue(
                initial_memory_usage <= final_memory_usage,
                "Memory usage inverted unexpectedly: {} > {}".format(
                    initial_memory_usage, final_memory_usage
                ),
            )

            increase_fraction = (float(final_memory_usage) / initial_memory_usage) - 1.0
            self.assertTrue(
                increase_fraction <= max_memory_increase_fraction,
                "Memory usage increased more than expected: {} -> {}: {} actual increase (expected < {})".format(
                    initial_memory_usage,
                    final_memory_usage,
                    increase_fraction,
                    max_memory_increase_fraction,
                ),
            )

    def test_pantsd_max_memory_usage(self):
        """Validates that the max_memory_usage setting is respected."""
        # We set a very, very low max memory usage, which forces pantsd to restart immediately.
        max_memory_usage_bytes = 130
        with self.pantsd_successful_run_context() as ctx:
            # TODO: We run the command, but we expect it to race pantsd shutting down, so we don't
            # assert success. https://github.com/pantsbuild/pants/issues/8200 will address waiting
            # until after the current command completes to invalidate the scheduler, at which point
            # we can assert success here.
            ctx.runner(
                [f"--pantsd-max-memory-usage={max_memory_usage_bytes}", "list", "testprojects::"]
            )

            # Assert that a pid file is written, but that the server stops afterward.
            ctx.checker.assert_started_and_stopped()

    def test_pantsd_invalidation_stale_sources(self):
        test_path = "daemon_correctness_test_0001"
        test_build_file = os.path.join(test_path, "BUILD")
        test_src_file = os.path.join(test_path, "some_file.py")
        filedeps_cmd = ["--unmatched-build-file-globs=warn", "filedeps", test_path]

        try:
            with self.pantsd_successful_run_context() as ctx:
                safe_mkdir(test_path, clean=True)

                ctx.runner(["help"])
                ctx.checker.assert_started()

                safe_file_dump(
                    test_build_file, "python_sources(sources=['some_non_existent_file.py'])"
                )
                non_existent_file = os.path.join(test_path, "some_non_existent_file.py")

                result = ctx.runner(filedeps_cmd)
                ctx.checker.assert_running()
                assert non_existent_file not in result.stdout

                safe_file_dump(test_build_file, "python_sources(sources=['*.py'])")
                result = ctx.runner(filedeps_cmd)
                ctx.checker.assert_running()
                assert non_existent_file not in result.stdout

                safe_file_dump(test_src_file, "print('hello')\n")
                result = ctx.runner(filedeps_cmd)
                ctx.checker.assert_running()
                assert test_src_file in result.stdout
        finally:
            rm_rf(test_path)

    def _assert_pantsd_keyboardinterrupt_signal(
        self,
        signum: int,
        regexps: list[str] | None = None,
        not_regexps: list[str] | None = None,
        cleanup_wait_time: int = 0,
    ):
        """Send a signal to the thin pailgun client and observe the error messaging.

        :param signum: The signal to send.
        :param regexps: Assert that all of these regexps match somewhere in stderr.
        :param not_regexps: Assert that all of these regexps do not match somewhere in stderr.
        :param cleanup_wait_time: passed throught to waiter, dictated how long simulated cleanup will take
        """
        with self.pantsd_test_context() as (workdir, config, checker):
            client_handle, waiter_pid, child_pid, _ = launch_waiter(
                workdir=workdir, config=config, cleanup_wait_time=cleanup_wait_time
            )
            client_pid = client_handle.process.pid
            waiter_process = psutil.Process(waiter_pid)
            child_process = psutil.Process(waiter_pid)

            assert waiter_process.is_running()
            assert child_process.is_running()
            checker.assert_started()

            # give time to enter the try/finally block in the child process
            time.sleep(5)

            # This should kill the client, which will cancel the run on the server, which will
            # kill the waiting process and its child.
            os.kill(client_pid, signum)
            client_run = client_handle.join()
            client_run.assert_failure()

            for regexp in regexps or []:
                self.assertRegex(client_run.stderr, regexp)

            for regexp in not_regexps or []:
                self.assertNotRegex(client_run.stderr, regexp)

            # pantsd should still be running, but the waiter process and child should have been
            # killed.
            time.sleep(5)
            assert not waiter_process.is_running()
            assert not child_process.is_running()
            checker.assert_running()

    def test_pantsd_graceful_shutdown(self):
        """Test that SIGINT is propgated to child processes and they are given time to shutdown."""
        self._assert_pantsd_keyboardinterrupt_signal(
            signal.SIGINT,
            regexps=[
                "Interrupted by user.",
                "keyboard int received",
                "waiter cleaning up",
                "waiter cleanup complete",
            ],
            cleanup_wait_time=0,
        )

    def test_pantsd_graceful_shutdown_deadline(self):
        """Test that a child process that does not respond to SIGINT within 5 seconds, is forcibly
        cleaned up with a SIGKILL."""
        self._assert_pantsd_keyboardinterrupt_signal(
            signal.SIGINT,
            regexps=[
                "Interrupted by user.",
                "keyboard int received",
                "waiter cleaning up",
            ],
            not_regexps=[
                "waiter cleanup complete",
            ],
            cleanup_wait_time=6,
        )

    def test_sigint_kills_request_waiting_for_lock(self):
        """Test that, when a pailgun request is blocked waiting for another one to end, sending
        SIGINT to the blocked run will kill it."""
        config = {"GLOBAL": {"pantsd_timeout_when_multiple_invocations": -1, "level": "debug"}}
        with self.pantsd_test_context(extra_config=config) as (workdir, config, checker):
            # Run a process that will wait forever.
            first_run_handle, _, _, file_to_create = launch_waiter(workdir=workdir, config=config)

            checker.assert_started()
            checker.assert_running()

            # And another that will block on the first.
            blocking_run_handle = self.run_pants_with_workdir_without_waiting(
                command=["goals"], workdir=workdir, config=config
            )

            # Block until the second request is waiting for the lock.
            time.sleep(10)

            # Sends SIGINT to the run that is waiting.
            blocking_run_client_pid = blocking_run_handle.process.pid
            os.kill(blocking_run_client_pid, signal.SIGINT)
            blocking_run_handle.join()

            # Check that pantsd is still serving the other request.
            checker.assert_running()

            # Exit the second run by writing the file it is waiting for, and confirm that it
            # exited, and that pantsd is still running.
            safe_file_dump(file_to_create, "content!")
            result = first_run_handle.join()
            result.assert_success()
            checker.assert_running()

    def test_pantsd_unicode_environment(self):
        with self.pantsd_successful_run_context(extra_env={"XXX": "¡"}) as ctx:
            result = ctx.runner(["help"])
            ctx.checker.assert_started()
            result.assert_success()

    # This is a regression test for a bug where we would incorrectly detect a cycle if two targets swapped their
    # dependency relationship (#7404).
    def test_dependencies_swap(self):
        template = dedent(
            """
            python_source(
              name='A',
              source='A.py',
              {a_deps}
            )

            python_source(
              name='B',
              source='B.py',
              {b_deps}
            )
            """
        )
        with self.pantsd_successful_run_context() as ctx, temporary_dir(".") as directory:
            safe_file_dump(os.path.join(directory, "A.py"), mode="w")
            safe_file_dump(os.path.join(directory, "B.py"), mode="w")

            if directory.startswith("./"):
                directory = directory[2:]

            def list_and_verify(a_deps: str, b_deps: str) -> None:
                Path(directory, "BUILD").write_text(template.format(a_deps=a_deps, b_deps=b_deps))
                result = ctx.runner(["list", f"{directory}:"])
                ctx.checker.assert_started()
                result.assert_success()
                expected_targets = {f"{directory}:{target}" for target in ("A", "B")}
                assert expected_targets == set(result.stdout.strip().split("\n"))

            list_and_verify(a_deps='dependencies = [":B"],', b_deps="")
            list_and_verify(a_deps="", b_deps='dependencies = [":A"],')

    def test_concurrent_overrides_pantsd(self):
        """Tests that the --concurrent flag overrides the --pantsd flag, because we don't allow
        concurrent runs under pantsd."""
        config = {"GLOBAL": {"concurrent": True, "pantsd": True}}
        with temporary_workdir() as workdir:
            pants_run = self.run_pants_with_workdir(
                ["-ldebug", "help", "goals"], workdir=workdir, config=config
            )
            pants_run.assert_success()
            self.assertNotIn("Connecting to pantsd", pants_run.stderr)

    def test_unhandled_exceptions_only_log_exceptions_once(self):
        """Tests that the unhandled exceptions triggered by LocalPantsRunner instances don't
        manifest as a PantsRunFinishedWithFailureException.

        That is, that we unset the global Exiter override set by LocalPantsRunner before we try to log the exception.

        This is a regression test for the most glaring case of https://github.com/pantsbuild/pants/issues/7597.
        """
        with self.pantsd_run_context(success=False) as ctx, temporary_dir(".") as directory:
            Path(directory, "BUILD").write_text(
                dedent(
                    """\
                    python_requirement(name="badreq", requirements=["badreq==99.99.99"])
                    pex_binary(name="pex", dependencies=[":badreq"])
                    """
                )
            )
            result = ctx.runner(["package", f"{directory}:pex"])
            ctx.checker.assert_running()
            result.assert_failure()
            # Assert that the desired exception has been triggered once.
            self.assertRegex(result.stderr, r"ERROR:.*badreq==99.99.99")
            # Assert that it has only been triggered once.
            assert (
                "During handling of the above exception, another exception occurred:"
                not in result.stderr
            )
            assert (
                "pants.bin.daemon_pants_runner._PantsRunFinishedWithFailureException: Terminated with 1"
                not in result.stderr
            )


text:
namespace WheelMUD.Actions
{
    using System.Collections.Generic;
    using System.Text;
    using WheelMUD.Core;
    using WheelMUD.Core.Attributes;
    using WheelMUD.Utilities;

    /// A command to list the characters who are currently in-game.
    [ExportGameAction]
    [ActionPrimaryAlias("who", CommandCategory.Player)]
    [ActionDescription("See or query who is online.")]
    [ActionSecurity(SecurityRole.player)]
    public class Who : GameAction
    {
        /// List of reusable guards which must be passed before action requests may proceed to execution.
        private static readonly List<CommonGuards> ActionGuards = new List<CommonGuards>
        {
        };

        /// Executes the command.
        /// <param name="actionInput">The full input specified for executing the command.</param>
        public override void Execute(ActionInput actionInput)
        {
            string div = string.Empty;
            string mudName = MudEngineAttributes.Instance.MudName;
            string mudNameLine = "                                ";
            string plural = string.Empty;
            string plural1 = string.Empty;
            StringBuilder sb = new StringBuilder();

            plural1 = "is";

            if (PlayerManager.Instance.Players.Count > 1)
            {
                plural = "s";
                plural1 = "are";
            }

            // TODO: Version, Sort and add by guild/class
            // div = "<%b%><%green%>" + string.Empty.PadLeft(sender.Entity.Terminal.Width, '~') + "<%n%>";
            div = "<%b%><%green%>~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~<%n%>";
            mudNameLine += mudName;
            sb.AppendLine();
            sb.AppendLine(div);
            sb.AppendLine(mudNameLine);
            sb.AppendLine(div);
            sb.AppendLine();
            sb.AppendLine("The following player" + plural + " " + plural1 + " currently online:");
            foreach (PlayerBehavior player in PlayerManager.Instance.Players)
            {
                // TODO: I used string literal to handle "" issue is there a neater approach?
                sb.AppendFormat(@"<%mxpsecureline%><send ""finger {0}|tell {0}"" ""|finger|tell"">{0}</send>", player.Parent.Name);
                sb.AppendFormat(" - {0}", player.Parent.Name);

                // Add in AFK message
                if (player.IsAFK)
                {
                    sb.Append(" (afk");

                    if (!string.IsNullOrEmpty(player.AFKReason))
                    {
                        sb.AppendFormat(": {0}", player.AFKReason);
                    }

                    sb.Append(")");
                }

                // End with a newline char
                sb.Append("<%nl%>");
            }

            sb.AppendLine();
            sb.AppendLine(div);
            sb.AppendFormat("Counted {0} player{1} online.", PlayerManager.Instance.Players.Count, plural);
            sb.AppendLine();
            sb.AppendLine(div);
            actionInput.Controller.Write(sb.ToString().TrimEnd(null));
        }

        /// Checks against the guards for the command.
        /// <param name="actionInput">The full input specified for executing the command.</param>
        /// <returns>A string with the error message for the user upon guard failure, else null.</returns>
        public override string Guards(ActionInput actionInput)
        {
            string commonFailure = VerifyCommonGuards(actionInput, ActionGuards);
            if (commonFailure != null)
            {
                return commonFailure;
            }

            return null;
        }
    }
}


text:
/* Author: Peter Mitrano */

#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include <moveit/python/pybind_rosmsg_typecasters.h>

#include <moveit/robot_state/robot_state.h>
#include <moveit/robot_state/conversions.h>

namespace py = pybind11;
using namespace robot_state;

void def_robot_state_bindings(py::module& m)
{
  m.doc() = "Representation of a robot's state. This includes position, velocity, acceleration and effort.";
  py::class_<RobotState, RobotStatePtr>(m, "RobotState")
      .def(py::init<const robot_model::RobotModelConstPtr&>(), py::arg("robot_model"))
      .def("setToRandomPositions", py::overload_cast<>(&RobotState::setToRandomPositions))
      .def("setToRandomPositions", py::overload_cast<const JointModelGroup*>(&RobotState::setToRandomPositions))
      .def("getJointModelGroup", &RobotState::getJointModelGroup, py::return_value_policy::reference)
      .def("getJointModel", &RobotState::getJointModel, py::return_value_policy::reference)
      .def("getLinkModel", &RobotState::getLinkModel, py::return_value_policy::reference)
      .def("getVariableNames", &RobotState::getVariableNames)
      .def("getVariablePositions", py::overload_cast<>(&RobotState::getVariablePositions, py::const_),
           py::return_value_policy::reference)
      .def("getVariableCount", &RobotState::getVariableCount)
      .def("hasVelocities", &RobotState::hasVelocities)
      .def("setJointGroupPositions",
           py::overload_cast<const std::string&, const std::vector<double>&>(&RobotState::setJointGroupPositions))
      .def("setJointGroupPositions",
           py::overload_cast<const JointModelGroup*, const std::vector<double>&>(&RobotState::setJointGroupPositions))
      .def("satisfiesBounds",
           py::overload_cast<const JointModelGroup*, double>(&RobotState::satisfiesBounds, py::const_),
           py::arg("joint_model_group"), py::arg("margin") = 0.0)
      .def("update", &RobotState::update, py::arg("force") = false)
      .def("printStateInfo",
           [](const RobotState& s) {
             std::stringstream ss;
             s.printStateInfo(ss);
             return ss.str();
           })
      .def("printStatePositions",
           [](const RobotState& s) {
             std::stringstream ss;
             s.printStatePositions(ss);
             return ss.str();
           })
      .def("__repr__",
           [](const RobotState& s) {
             std::stringstream ss;
             s.printStatePositions(ss);
             return ss.str();
           })
      //
      ;

  m.def("jointStateToRobotState", &jointStateToRobotState);
  m.def(
      "robotStateToRobotStateMsg",
      [](const RobotState& state, bool copy_attached_bodies) {
        moveit_msgs::RobotState state_msg;
        robotStateToRobotStateMsg(state, state_msg, copy_attached_bodies);
        return state_msg;
      },
      py::arg("state"), py::arg("copy_attached_bodies") = true);
}


text:
package mountainrangepvp.server

import com.badlogic.gdx.math.Vector2
import mountainrangepvp.core.InputCommand

/**
 * Computes input state for each frame from an accumulated series of commands.
 */
object InputState {
  def apply(): InputState = new InputState(0,
                                           false,
                                           false, 0,
                                           new Vector2(0, 0),
                                           0)

  val FireRateDelay = 0.1f
}

case class InputState(private val runRaw: Float,
                      jump: Boolean,
                      private val fire: Boolean,
                      private val fireTimer: Float,
                      aimPoint: Vector2,
                      private val acc: Int) {
  def accumulate(command: InputCommand): InputState =
    InputState(runRaw + command.run,
               jump = command.jump,
               fire = command.fire,
               fireTimer,
               if (acc == 0) command.aimDirection else aimPoint,
               acc + 1)

  def run = runRaw.max(-1f).min(1f)

  def firing: Boolean = fire && fireTimer > InputState.FireRateDelay

  def nextFrame(dt: Float) =
    InputState(0,
               jump = false,
               fire = false,
               if (firing) 0 else fireTimer + dt,
               aimPoint,
               0)
}


text:
static void read_nonzero_string(boost::property_tree::ptree& ptree,
                               const std::string& key,
                               std::string& dst)
{
    auto it = ptree.find(key);
    if (it == ptree.not_found())
    {
        throw std::runtime_error{std::string("Key not found: ") + key};
    }

    dst = it->second.get_value<std::string>();
    if (dst.size() < 1)
    {
        throw std::runtime_error{std::string("Must not be empty: ") + key};
    }
}

static void read_optional_string(boost::property_tree::ptree& ptree, const std::string& key, std::string& dst)
{
    auto it = ptree.find(key);
    if (it == ptree.not_found())
        return;
    dst = it->second.get_value<std::string>();
}

static void read_boolean_value(boost::property_tree::ptree& ptree,
                               const std::string& key,
                               bool& dst)
{
    // First try to read it as a string
    std::string str;
    read_nonzero_string(ptree, key, str);

    dst = (boost::algorithm::iequals(str, "yes") ||
            boost::algorithm::iequals(str, "true")) ? true : false;

}

template <class T>
static void read_numeric_value(boost::property_tree::ptree& ptree,
                               const std::string& key,
                               T& dst)
{
    auto it = ptree.find(key);
    if (it == ptree.not_found())
    {
        throw std::runtime_error{std::string("Key not found: ") + key};
    }

    dst = it->second.get_value<T>();
}

static void read_server_configuration(boost::property_tree::ptree& tree_node,
                                      prog_config& cfg)
{
    p2u::nntp::connection_info conn;
    read_nonzero_string(tree_node, "Address", conn.serveraddr);
    read_numeric_value(tree_node, "Port", conn.port);

    // TODO: Support usenet connections without username and password
    read_nonzero_string(tree_node, "Username", conn.username);
    read_nonzero_string(tree_node, "Password", conn.password);
    read_boolean_value(tree_node, "TLS", conn.tls);

    // Num Connections
    int num_connections;
    read_numeric_value(tree_node, "Connections", num_connections);

    cfg.servers.push_back(std::make_pair(std::move(conn), num_connections));
}

static void read_configuration_file(const boost::filesystem::path& path,
                                    prog_config& cfg)
{
    using boost::property_tree::ptree;

    ptree pt;
    boost::property_tree::read_ini(path.string(), pt);

    // Global settings
    auto it = pt.find("global");
    if (it == pt.not_found())
    {
        throw std::runtime_error{"Missing global section in configuration file"};
    }

    auto& global_section = it->second;

    read_nonzero_string(global_section, "From", cfg.from);
    read_numeric_value(global_section, "ArticleSize", cfg.article_size);
    read_numeric_value(global_section, "ArticleQueueSize", cfg.queue_size);
    read_numeric_value(global_section, "OperationTimeout", cfg.operation_timeout);
    read_optional_string(global_section, "MsgIdDomain", cfg.msgiddomain);

    if (cfg.msgiddomain.empty()) {
        cfg.msgiddomain = "post2usenet";
    }

    // Read server configurations
    for (auto& section : pt)
    {
        if (boost::algorithm::starts_with(section.first, "Server"))
        {
            read_server_configuration(section.second, cfg);
        }
    }
}

namespace po = boost::program_options;

static void read_cmdline_args(const po::variables_map& vm, prog_config& cfg)
{
    cfg.io_threads = vm["iothreads"].as<int>();

    if (vm.count("articlesize"))
    {
        cfg.article_size = vm["articlesize"].as<int>();
    }

    if (vm.count("subject"))
    {
        cfg.subject = vm["subject"].as<std::string>();
    }

    cfg.validate_posts = vm.count("validate");
    cfg.raw = vm["raw"].as<bool>();

    auto& files = vm["file"].as<std::vector<std::string>>();

    std::transform(files.begin(), files.end(), std::back_inserter(cfg.files),
            [](const std::string& p)
            {
                return boost::filesystem::path(p);
            });

    if (vm.count("group"))
    {
        cfg.groups = vm["group"].as<std::vector<std::string>>();
    }

    if (vm.count("output"))
    {
        cfg.nzboutput = vm["output"].as<std::string>();
    }
}

bool load_program_config(int argc, const char* argv[], prog_config& cfg)
{
    po::options_description hidden{"So secret!"};
    hidden.add_options()
        ("iothreads", po::value<int>()->default_value(1), "Number of IO threads to use. 1 IO thread is usually fine.");

    po::options_description cli{"Command line arguments"};

    cli.add_options()
        ("help,h", "Show this message")
        ("articlesize,a", po::value<int>(), "Size in bytes of each article")
        ("raw,r", po::value<bool>()->default_value(true), "Raw post mode. Emulates GoPostStuff, newsmangler, etc.")
        ("validate,v", "Validate articles after post. Issues STAT command to ensure article was properly posted. Repost articles if bad.")
        ("subject,s", po::value<std::string>(), "Subject of the post. By default, will be set to the folder name if input is a folder, otherwise will be set to the filename")
        ("config,c", po::value<std::string>(), "Specifies configuration file path")
        ("output,o", po::value<std::string>(), "Specifies output NZB file/directory")
        ("group,g", po::value<std::vector<std::string>>(), "Groups to post to")
        ("file", po::value<std::vector<std::string>>()->required(), "File or directory to post");

    po::positional_options_description positionalopts;
    positionalopts.add("file", -1);

    po::options_description all_cli;
    all_cli.add(hidden).add(cli);

    po::variables_map vm;
    try
    {
        po::store(po::command_line_parser(argc, argv).options(all_cli).positional(positionalopts).run(), vm);

        if (vm.count("help"))
        {
            std::cout << "post2usenet " << std::endl << cli << std::endl;
            return false;
        }

        po::notify(vm);
    }
    catch (po::error& e)
    {
        std::cout << cli << std::endl;
        return false;
    }

    if (vm.count("file") < 1)
    {
        std::cout << "Missing files" << std::endl;
        return false;
    }

    boost::filesystem::path pathToConfig;
    if (vm.count("config") < 1)
    {
        pathToConfig = getenv("HOME");
        pathToConfig /= ".post2usenet.conf";
    }
    else
    {
        pathToConfig = vm["config"].as<std::string>();
    }

    if (!boost::filesystem::exists(pathToConfig))
    {
        std::cout << "Invalid path to configuration file " << pathToConfig << std::endl;
        return false;
    }

    try
    {
        read_configuration_file(pathToConfig, cfg);

        if (cfg.servers.size() < 1)
        {
            std::cout << "Need at least one server block! (Where else am I supposed to post?)" << std::endl;
            return false;
        }

        read_cmdline_args(vm, cfg);

        if (cfg.groups.size() < 1)
        {
            std::cout << "Need at least one group to post to!" << std::endl;
            return false;
        }

        bool good = true;
        for (const auto& path : cfg.files)
        {
            if (!boost::filesystem::exists(path))
            {
                std::cout << "ERROR: Path " << path << " does not exist!" << std::endl;
                good = false;
            }
        }

        return good;
    }
    catch (std::exception& e)
    {
        std::cout << e.what() << std::endl;
        return false;
    }
}


text:
module Elasticsearch
  module Resources
    class Index
      include Resource
      include Queryable
      include Configurable
      include Clusterable
      include Nameable

      define_configuration class_name: 'Elasticsearch::Resources::Configuration::Index'

      def initialize(cluster:, &block)
        self.cluster = cluster
        configure(&block)
      end

      def setup!
        unless exists?
          create
          super
        end
      end

      def teardown!
        if exists?
          delete
          super
        end
      end

      def client
        cluster.client
      end

      def name
        settings.name
      end

      def types
        @types ||= self.class.types.collect do |key, type_class|
          [
            key,
            build_type(key: key)
          ]
        end.to_h
      end

      def build_type(key:, type_class: nil)
        type_class = self.class.types[key] if type_class.nil?
        type_class&.new(index: self).tap do |type|
          settings.type(key).tap do |settings|
            type.settings = settings.dup unless settings.nil?
          end
        end
      end

      def query_index(action, options = {})
        params = {
          index: name
        }.merge(options)

        client.indices.send(action, **params)
      end

      def query(action, options = {})
        params = {
          index: name
        }.merge(options)

        super(action, **params)
      end

      def exists?
        query_index(:exists?)
      end

      def create
        query_index(:create)
      end

      def put_mapping(options = {})
        query_index(:put_mapping, options)
      end

      def delete
        query_index(:delete)
      end

      def search(body, options = {})
        params = {
          body: body
        }.merge(options)

        query(:search, params)
      end

      def count(body, options = {})
        params = {
          body: body
        }.merge(options)

        query(:count, params)
      end

      def find_cluster
        self.cluster
      end

      def find_index(index: nil)
        matches_name?(index) ? self : nil
      end

      def find_type(index: nil, type:)
        types.find do |t|
          t.find_type(type: type)
        end
      end

      def self.types
        (@type_names ||= {}).collect do |key, type_name|
          [key, Object.const_get(type_name)]
        end.to_h
      end

      protected

      def self.define_types(types = {})
        @type_names = types.collect do |key, type|
          [key.to_sym, type.class == Class ? type.name : type]
        end.to_h
      end
    end
  end
end


text:
app.factory('activityService', ['$http', '$q', '$log', '$filter', 'modalServiceNew', '$state', function ($http, $q, $log, $filter, modalServiceNew, $state) {

    var createParentActivity = function () {
        return {
            id: null,
            dateCreated: null,
            createdBy: null,
            updatedBy: null,
            dateStarted: null,
            dateFinished: null,
            reductionValue: null,
            reasonOfReduction: null,
            dateDeactivated: null,
            deactivatedBy: null,
            description: null,
            pointOfInjectionType: null,
            processStatus: null,
            pointOfInjectionList: null,
            childActivityList: [{
                id: null,
                dateStarted: null,
                dateFinished: null,
                reductionSetting: 60,
                discriminationCoefficientEnabled: false,
                reasonOfReduction: null,
                requiredReductionPower: null,
                description: null,
                practise: false,
                seqNum: null,
                processStatus: null,
                characteristicForMissingMeasurementFwt: 'NotIncluded',
                substituteValuePhotovoltaicFwt: null,
                substituteValueWindFwt: null,
                substituteValueBiogasFwt: null,
                characteristicForMissingMeasurementEfr: 'NotIncluded',
                substituteValuePhotovoltaicEfr: null,
                substituteValueWindEfr: null,
                substituteValueBiogasEfr: null,
                useWholeArea: true,
                subGeographicalRegions: null,
                transformerStations: null,
                substationProposalList: null
            }],
        };
    };

    var createChildActivity = function() {
        return {
            id: null,
            dateStarted: null,
            dateFinished: null,
            reductionSetting: 60,
            reductionValue: null,
            discriminationCoefficientEnabled: false,
            reasonOfReduction: null,
            requiredReductionPower: null,
            description: null,
            practise: false,
            processStatus: null,
            characteristicForMissingMeasurementFwt: 'NotIncluded',
            substituteValuePhotovoltaicFwt: null,
            substituteValueWindFwt: null,
            substituteValueBiogasFwt: null,
            characteristicForMissingMeasurementEfr: 'NotIncluded',
            substituteValuePhotovoltaicEfr: null,
            substituteValueWindEfr: null,
            substituteValueBiogasEfr: null,
            useWholeArea: true,
            pointOfInjectionType: null,
            pointOfInjectionList: null,
            subGeographicalRegions: null,
            transformerStations: null,
            substationProposalList: null
        };
    };

    var resetActivity = function () {
        childActivity = createChildActivity();
    }

    var currentParentActivityId;
    var currentParentActivity = createParentActivity();
    var childActivity = createChildActivity();
    var configData = {};

    function loadActivity() {
        return $http.get(Liferay.ThemeDisplay.getCDNBaseURL() + '/openk-eisman-portlet/rest/activity/latestusersettings/' + currentParentActivityId).then(function (result) {
            childActivity = result.data;
            angular.extend(childActivity, childActivity.preselectionConfigurationDto);
            delete childActivity.preselectionConfigurationDto;
        }, function (error) {
            modalServiceNew.showErrorDialog(error).then(function () {
                $state.go('state1', { show: 'Aktiv' });
            });
        });
    }

    function loadConfiguration() {
        configData.activity = {};
        configData.task = {};
        return $q.all([
            $http.get(Liferay.ThemeDisplay.getCDNBaseURL() + "/openk-eisman-portlet/rest/reasonofreductions/").then(function (result) {
                configData.regulationReasons = result.data;
            }),
            $http.get(Liferay.ThemeDisplay.getCDNBaseURL() + "/openk-eisman-portlet/rest/substation/lov/").then(function (result) {
                result.data = result.data.sort(function(a,b){if (a.name < b.name) return -1; else return 1;});
                configData.transformerStations = result.data;
            }),
            $http.get(Liferay.ThemeDisplay.getCDNBaseURL() + "/openk-eisman-portlet/rest/subgeographicalregion/lov/").then(function (result) {
                configData.subGeographicalRegions = result.data;
            }),
            $http.get(Liferay.ThemeDisplay.getCDNBaseURL() + "/openk-eisman-portlet/rest/hysteresis").then(function (result) {
                configData.hysteresis = result.data;
            }),
            $http.get(Liferay.ThemeDisplay.getCDNBaseURL() + "/openk-eisman-portlet/rest/preselection/").then(function (result) {
                configData.templates = result.data;
            }),
            $http.get(Liferay.ThemeDisplay.getCDNBaseURL() + "/openk-eisman-portlet/rest/reductionsettinglist/").then(function (result) {
                configData.regulationSteps = result.data;
            }),
            $http.get(Liferay.ThemeDisplay.getCDNBaseURL() + "/openk-eisman-portlet/rest/timeintervaldataexpired").then(function (result) {
                configData.timerTick = result.data;
            })
        ]);
    }
    var parentActivities;
    var pageSize = 5;
    var defaultSortExpression = 'id,desc';
    var loadParentActivities = function (page, size, time, sortExpression, filterExpression, show) {
        var params = {
            page: page || 0,
            size: size || pageSize,
            t: time || new Date().getTime()
        };

        params.sort = sortExpression || defaultSortExpression;

        params.filter = filterExpression || {};

        if (show === 'Deleted') {
            params.filter.isDeleted = "true";
        } else {
            params.filter.isDeleted = "false";
        }
        if (show === 'Terminated') {
            params.filter.isTerminated = "true";
        } else {
            params.filter.isTerminated = "false";
        }

        console.log('filter:' + params.filter);

        show = show || 'Aktiv';

        return $http.get(Liferay.ThemeDisplay.getCDNBaseURL() + "/openk-eisman-portlet/rest/findprocessoverviewlist", { "params": params }).then(function (result) {
            parentActivities = result.data;
            parentActivities.content.forEach(function (parent) {
                parent.childActivityList = [];
                parent.actionOverviewDtoList.forEach(function (child) {
                    parent.childActivityList.push(angular.extend({}, child));
                });
                delete parent.actionOverviewDtoList;
            });

            return parentActivities;
        }, function (error) {
            modalServiceNew.showErrorDialog(error).then(function () {
                $state.go('state1', { show: 'Aktiv' });
            });
            $log.error('Cannot load /openk-eisman-portlet/rest/findprocessoverviewlist/');
        });
    };

    return {
        pageSize: pageSize,
        createParentActivity: createParentActivity,
        createChildActivity: createChildActivity,
        resetActivity: resetActivity,
        childActivity: function (act) {
            if (act) {
                childActivity = act;
            }
            return childActivity;
        },

        activityConfigData: function () {
            return configData;
        },
        loadActivity: loadActivity,
        loadParentActivities: loadParentActivities,
        loadConfiguration: loadConfiguration,
        currentParentActivityId: function (id) {
            if (id) {
                currentParentActivityId = id;
                parentActivities.content.forEach(function (activity) {
                    if (activity.id === id) {
                        currentParentActivity = activity;
                    }
                });
            }

            return currentParentActivityId;
        },
        getParentActivities: function () {
            return parentActivities;
        },
        currentParentActivity: function () {
            return currentParentActivity;
        }
    };

}]);


text:
<?php

namespace FSi\Component\DataSource\Driver\Doctrine\ORM\Extension\Core\Field;

use FSi\Component\DataSource\Driver\Doctrine\ORM\DoctrineAbstractField;

/**
 * Datetime field.
 */
class DateTime extends DoctrineAbstractField
{
    /**
     * {@inheritdoc}
     */
    protected $comparisons = ['eq', 'neq', 'lt', 'lte', 'gt', 'gte', 'in', 'notIn', 'between', 'isNull'];

    /**
     * {@inheritdoc}
     */
    public function getType()
    {
        return 'datetime';
    }
}


text:
@interface WDAsyncImageThumbnailTest : XCTestCase <WDAsyncImageThumbnailDelegate>

- (void)WD_mockLongLoad:(NSTimeInterval)aLoadTime;

- (void)waitForGroup;
@end

@implementation WDAsyncImageThumbnailTest{
    NSURL *pic1URL;
    NSURL *pic2URL;
    NSURL *pic3URL;
    NSURL *pic4URL;
    NSURL *pic5URL;
    NSURL *pic6URL;
    NSArray *picURLs;
    NSCache *imageCache;
    BOOL continueLoad;
    BOOL delegateCalled;
    dispatch_group_t dispatchGroup;
    id dataUtilsMoc;
    NSTimeInterval loadSleepTime;
    int64_t imageLoadCallCount;
    int64_t videoLoadCallCount;
}

- (void)setUp{

    [super setUp];
    NSBundle *thisBundle = [NSBundle bundleForClass:[self class]];
    pic1URL = [thisBundle URLForResource:@"testPics/0.JPG" withExtension:nil];
    pic2URL = [thisBundle URLForResource:@"testPics/1.JPG" withExtension:nil];
    pic3URL = [thisBundle URLForResource:@"testPics/2.JPG" withExtension:nil];
    pic4URL = [thisBundle URLForResource:@"testPics/3.JPG" withExtension:nil];
    pic5URL = [thisBundle URLForResource:@"testPics/4.JPG" withExtension:nil];
    pic6URL = [thisBundle URLForResource:@"testPics/5.JPG" withExtension:nil];
    picURLs = @[pic1URL, pic2URL, pic3URL, pic4URL, pic5URL, pic6URL];
    imageCache = [[NSCache alloc] init];
    continueLoad = YES;
    delegateCalled = NO;
    dispatchGroup = dispatch_group_create();
    [WDAsyncImageThumbnail setDispatchGroup:dispatchGroup];
}

- (void)tearDown{

    [self waitForGroup];
    [imageCache removeAllObjects];
    [dataUtilsMoc stopMocking];
    imageLoadCallCount = 0;
    videoLoadCallCount = 0;
    [super tearDown];
}

- (void)WD_mockLongLoad:(NSTimeInterval)aLoadTime{

    loadSleepTime = aLoadTime;

    dataUtilsMoc = [OCMockObject mockForClass:[WDThumbnailDataUtils class]];
    [[[[dataUtilsMoc stub]
            classMethod]
            andCall:@selector(fake_newThumbnailForImage:heigth:error:) onObject:self]
            newThumbnailForImage:[OCMArg any] heigth:wdCollectionThumbnailMaxSize error:[OCMArg anyObjectRef]];
    [[[[dataUtilsMoc stub]
            classMethod]
            andCall:@selector(fake_newThumbnailForVideo:error:) onObject:self]
            newThumbnailForVideo:[OCMArg any] error:[OCMArg anyObjectRef]];
}

- (CGImageRef)fake_newThumbnailForImage:(NSURL *)imagePath heigth:(int)h error:(NSError *__autoreleasing *)aError{

    OSMemoryBarrier();
    OSAtomicIncrement64(&imageLoadCallCount);
    [NSThread sleepForTimeInterval:loadSleepTime];
    CGImageRef imRef = (__bridge_retained CGImageRef) [[NSObject alloc] init];
    return imRef;
}

- (CGImageRef)fake_newThumbnailForVideo:(NSURL *)videoPath error:(NSError *__autoreleasing *)aError{

    OSMemoryBarrier();
    OSAtomicIncrement64(&videoLoadCallCount);
    [NSThread sleepForTimeInterval:loadSleepTime];
    CGImageRef imRef = (__bridge_retained CGImageRef) [[NSObject alloc] init];
    return imRef;
}

#pragma mark - TEST

- (void)testItIgnoresSubsequentLoadOrders{
    //given
    [self WD_mockLongLoad:0.1];
    [WDAsyncImageThumbnail setDispatchGroup:dispatchGroup];
    WDAsyncImageThumbnail *image = [WDAsyncImageThumbnail imageWithImageCache:imageCache imageURL:pic1URL];

    //when
    [image loadImageWithCallbackBlock:^(CGImageRef aImageRef, NSError *aError){}];
    [image loadImageWithCallbackBlock:^(CGImageRef aImageRef, NSError *aError){}];
    [image loadImageWithCallbackBlock:^(CGImageRef aImageRef, NSError *aError){}];

    //test
    [self waitForGroup];
    OSMemoryBarrier();
    XCTAssertEqual(imageLoadCallCount, 1);
}

- (void)testItAsksIfIsVisibleJustBeforeLoad{

    [self WD_mockLongLoad:0.01];
    __block BOOL calledBack = NO;
    WDAsyncImageThumbnail *image = [WDAsyncImageThumbnail imageWithImageCache:imageCache imageURL:pic1URL];
    continueLoad = YES;
    image.delegate = self;
    [image loadImageWithCallbackBlock:^(CGImageRef aImageRef, NSError *aError){
        calledBack = YES;
    }];
    expect(delegateCalled && !calledBack).will.equal(YES);
}

- (void)testItsLoadCanBeCancelled{

    [self WD_mockLongLoad:0.1];
    WDAsyncImageThumbnail *im1 = [WDAsyncImageThumbnail imageWithImageCache:imageCache imageURL:pic1URL];
    WDAsyncImageThumbnail *im2 = [WDAsyncImageThumbnail imageWithImageCache:imageCache imageURL:pic2URL];
    WDAsyncImageThumbnail *im3 = [WDAsyncImageThumbnail imageWithImageCache:imageCache imageURL:pic3URL];
    WDAsyncImageThumbnail *im4 = [WDAsyncImageThumbnail imageWithImageCache:imageCache imageURL:pic4URL];

    __block NSUInteger callbackCount = 0;
    [im1 loadImageWithCallbackBlock:^(CGImageRef aImageRef, NSError *aError){
        callbackCount++;
    }];
    [im2 loadImageWithCallbackBlock:^(CGImageRef aImageRef, NSError *aError){
        callbackCount++;
    }];
    [im3 loadImageWithCallbackBlock:^(CGImageRef aImageRef, NSError *aError){
        callbackCount++;
    }];
    [im4 loadImageWithCallbackBlock:^(CGImageRef aImageRef, NSError *aError){
        callbackCount++;
    }];

    [im1 cancelLoad];
    [im2 cancelLoad];
    [im3 cancelLoad];
    [im4 cancelLoad];

    [self waitForGroup];
    XCTAssertLessThan(callbackCount, 4);
}

- (void)testItCallsBackOnMainThreadWhenImageIsLoaded{

    WDAsyncImageThumbnail *im1 = [WDAsyncImageThumbnail imageWithImageCache:imageCache imageURL:pic1URL];
    [im1 loadImageWithCallbackBlock:^(CGImageRef aImageRef, NSError *aError){
        WD_ASSERT_MT;
    }];
}

- (void)testItCachesImagesAndReadsFromCacheIfAvailable{

    //two pics referring to the same url
    [self WD_mockLongLoad:0.001];
    WDAsyncImageThumbnail *im1 = [WDAsyncImageThumbnail imageWithImageCache:imageCache imageURL:pic1URL];
    WDAsyncImageThumbnail *im2 = [WDAsyncImageThumbnail imageWithImageCache:imageCache imageURL:pic1URL];

    __block BOOL firstLoaded;
    [im1 loadImageWithCallbackBlock:^(CGImageRef aImageRef, NSError *aError){
        XCTAssertTrue(aImageRef != NULL);
        firstLoaded = YES;
    }];

    expect(firstLoaded).will.equal(YES);
    NSLog(@"first pic loaded");

    __block BOOL secondLoaded;
    [im2 loadImageWithCallbackBlock:^(CGImageRef aImageRef, NSError *aError){
        XCTAssertTrue(aImageRef != NULL);
        secondLoaded = YES;
    }];
    expect(secondLoaded).will.equal(YES);
    NSLog(@"second pic loaded.");

    //test
    XCTAssertEqual(imageLoadCallCount, 1);
}

- (void)testImageCanBeReleased{

    WDAsyncImageThumbnail *im1 = [WDAsyncImageThumbnail imageWithImageCache:imageCache imageURL:pic1URL];
    __block CGImageRef imRef;
    [im1 loadImageWithCallbackBlock:^(CGImageRef aImageRef, NSError *aError){
        imRef = aImageRef;
    }];
    [self waitForGroup];
    NSInteger retainBefore = CFGetRetainCount(imRef);
    XCTAssertEqual(retainBefore, 2);
    [im1 releaseImage];
    NSInteger retainAfter = CFGetRetainCount(imRef);
    XCTAssertEqual(retainAfter, 1);
}

- (void)testItLoadsAnImage{

    //given
    WDAsyncImageThumbnail *image = [WDAsyncImageThumbnail imageWithImageCache:imageCache imageURL:pic1URL];
    image.delegate = self;
    continueLoad = YES;
    XCTestExpectation *expectation;
    expectation = [self expectationWithDescription:@"image loaded callback"];

    //test
    [image loadImageWithCallbackBlock:^(CGImageRef aImageRef, NSError *aError){
        XCTAssertNil(aError);
        XCTAssertTrue(aImageRef);
        [expectation fulfill];
    }];

    [self waitForExpectationsWithTimeout:2.0 handler:nil];
    NSLog(@"image loaded");
}

- (void)testParallelLoadIsOk{

    [WDAsyncImageThumbnail setDispatchGroup:dispatchGroup];
    __block NSUInteger finishedBlocks = 0;
    for(NSUInteger i = 0; i < picURLs.count; ++i){

        WDAsyncImageThumbnail *image = [WDAsyncImageThumbnail imageWithImageCache:imageCache imageURL:picURLs[i]];
        image.delegate = self;
        [image loadImageWithCallbackBlock:^(CGImageRef aImageRef, NSError *aError){
            XCTAssertNil(aError);
            XCTAssertTrue(aImageRef);
            finishedBlocks++;
        }];
    }
    [self waitForGroup];
    NSLog(@"all loads finished");
    XCTAssertEqual(finishedBlocks, picURLs.count);
}

#pragma mark - Image delegate

- (BOOL)imageWillLoad:(WDAsyncImageThumbnail *)aImage{

    delegateCalled = YES;
    return continueLoad;
}

#pragma mark - Helpers

- (void)waitForGroup{

    __block BOOL didComplete = NO;
    dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^{
        didComplete = YES;
    });
    while( !didComplete ){
        NSTimeInterval const interval = 0.002;
        if( ![[NSRunLoop currentRunLoop]
                runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:interval]] ){
            [NSThread sleepForTimeInterval:interval];
        }
    }
}

@end

#pragma clang diagnostic pop