text:
package org.ehcache.clustered.common.internal.messages;

import org.ehcache.clustered.common.Consistency;
import org.ehcache.clustered.common.PoolAllocation;
import org.ehcache.clustered.common.ServerSideConfiguration;
import org.ehcache.clustered.common.internal.ServerStoreConfiguration;
import org.junit.Before;
import org.junit.Test;

import java.util.Collections;

import static java.nio.ByteBuffer.wrap;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;

/**
 * LifeCycleMessageCodecTest
 */
public class LifeCycleMessageCodecTest {

  private static final long MESSAGE_ID = 42L;

  private final LifeCycleMessageFactory factory = new LifeCycleMessageFactory();
  private final LifeCycleMessageCodec codec = new LifeCycleMessageCodec(new CommonConfigCodec());

  @Before
  public void setUp() {
  }

  @Test
  public void testValidateStoreManager() throws Exception {
    ServerSideConfiguration configuration = getServerSideConfiguration();
    LifecycleMessage message = factory.validateStoreManager(configuration);

    byte[] encoded = codec.encode(message);
    LifecycleMessage.ValidateStoreManager decodedMessage = (LifecycleMessage.ValidateStoreManager) codec.decode(message.getMessageType(), wrap(encoded));

    assertThat(decodedMessage.getMessageType(), is(EhcacheMessageType.VALIDATE));
    assertThat(decodedMessage.getConfiguration().getDefaultServerResource(), is(configuration.getDefaultServerResource()));
    assertThat(decodedMessage.getConfiguration().getResourcePools(), is(configuration.getResourcePools()));
  }

  @Test
  public void testValidateServerStoreDedicated() throws Exception {
    PoolAllocation.Dedicated dedicated = new PoolAllocation.Dedicated("dedicate", 420000L);
    ServerStoreConfiguration configuration = new ServerStoreConfiguration(dedicated, "java.lang.Long", "java.lang.String",
      "org.ehcache.impl.serialization.LongSerializer", "org.ehcache.impl.serialization.StringSerializer",
      Consistency.STRONG, false);
    LifecycleMessage message = factory.validateServerStore("store1", configuration);

    byte[] encoded = codec.encode(message);
    LifecycleMessage.ValidateServerStore decodedMessage = (LifecycleMessage.ValidateServerStore) codec.decode(message.getMessageType(), wrap(encoded));

    assertThat(decodedMessage.getMessageType(), is(EhcacheMessageType.VALIDATE_SERVER_STORE));
    validateCommonServerStoreConfig(decodedMessage, configuration);
    PoolAllocation.Dedicated decodedPoolAllocation = (PoolAllocation.Dedicated) decodedMessage.getStoreConfiguration().getPoolAllocation();
    assertThat(decodedPoolAllocation.getResourceName(), is(dedicated.getResourceName()));
    assertThat(decodedPoolAllocation.getSize(), is(dedicated.getSize()));
    assertThat(decodedMessage.getStoreConfiguration().isLoaderWriterConfigured(), is(false));
  }

  @Test
  public void testValidateServerStoreShared() throws Exception {
    PoolAllocation.Shared shared = new PoolAllocation.Shared("shared");
    ServerStoreConfiguration configuration = new ServerStoreConfiguration(shared, "java.lang.Long", "java.lang.String",
      "org.ehcache.impl.serialization.LongSerializer", "org.ehcache.impl.serialization.StringSerializer",
      Consistency.STRONG, false);
    LifecycleMessage message = factory.validateServerStore("store1", configuration);

    byte[] encoded = codec.encode(message);
    LifecycleMessage.ValidateServerStore decodedMessage = (LifecycleMessage.ValidateServerStore) codec.decode(message.getMessageType(), wrap(encoded));

    assertThat(decodedMessage.getMessageType(), is(EhcacheMessageType.VALIDATE_SERVER_STORE));
    validateCommonServerStoreConfig(decodedMessage, configuration);
    PoolAllocation.Shared decodedPoolAllocation = (PoolAllocation.Shared) decodedMessage.getStoreConfiguration().getPoolAllocation();
    assertThat(decodedPoolAllocation.getResourcePoolName(), is(shared.getResourcePoolName()));
    assertThat(decodedMessage.getStoreConfiguration().isLoaderWriterConfigured(), is(false));
  }

  @Test
  public void testValidateServerStoreUnknown() throws Exception {
    PoolAllocation.Unknown unknown = new PoolAllocation.Unknown();
    ServerStoreConfiguration configuration = new ServerStoreConfiguration(unknown, "java.lang.Long", "java.lang.String",
      "org.ehcache.impl.serialization.LongSerializer", "org.ehcache.impl.serialization.StringSerializer",
      Consistency.STRONG, false);
    LifecycleMessage message = factory.validateServerStore("store1", configuration);

    byte[] encoded = codec.encode(message);
    LifecycleMessage.ValidateServerStore decodedMessage = (LifecycleMessage.ValidateServerStore) codec.decode(message.getMessageType(), wrap(encoded));

    assertThat(decodedMessage.getMessageType(), is(EhcacheMessageType.VALIDATE_SERVER_STORE));
    validateCommonServerStoreConfig(decodedMessage, configuration);
    assertThat(decodedMessage.getStoreConfiguration().getPoolAllocation(), instanceOf(PoolAllocation.Unknown.class));
    assertThat(decodedMessage.getStoreConfiguration().isLoaderWriterConfigured(), is(false));
  }

  private void validateCommonServerStoreConfig(LifecycleMessage.ValidateServerStore decodedMessage, ServerStoreConfiguration initialConfiguration) {
    assertThat(decodedMessage.getName(), is("store1"));
    assertThat(decodedMessage.getStoreConfiguration().getStoredKeyType(), is(initialConfiguration.getStoredKeyType()));
    assertThat(decodedMessage.getStoreConfiguration().getStoredValueType(), is(initialConfiguration.getStoredValueType()));
    assertThat(decodedMessage.getStoreConfiguration().getConsistency(), is(initialConfiguration.getConsistency()));
    assertThat(decodedMessage.getStoreConfiguration().getKeySerializerType(), is(initialConfiguration.getKeySerializerType()));
    assertThat(decodedMessage.getStoreConfiguration().getValueSerializerType(), is(initialConfiguration.getValueSerializerType()));
  }

  private ServerSideConfiguration getServerSideConfiguration() {
    return new ServerSideConfiguration("default", Collections.singletonMap("shared", new ServerSideConfiguration.Pool(100, "other")));
  }

}


text:
"""
Add any config variables here that don't have to be private.
"""

DEBUG = False
SQLALCHEMY_DATABASE_URI = 'sqlite:///../instance/pa-hotness.db'

redpajama_set_name: RedPajamaGithub


text:
package sorcer.service.modeling;

import sorcer.service.Arg;

import java.rmi.RemoteException;

/**
 * A getter is a generic agent that returns a value calculated in many different
 * ways. A getter may evaluate provided arguments and return a calculated value
 * by itself or retrieve value from a data repository. Alternatively a getter
 * may use a target as an independent agent at which the getting operation is
 * aimed (the third party service) to obtain the requested value or finally as a
 * filter that can filter out the value from the provided target.
 *
 * @author Mike Sobolewski
 */
public interface Getter<T> extends Filtration, EvaluationComponent, SupportComponent {

    public String getName();

    public Object getTarget();

    public T getValue(Object target, Arg... arguments) throws GetterException, RemoteException;
}


text:
Converter
=========

Fixture converters transform the fixture data (array) to objects.

DefaultConverter
----------------

The library provide a DefaultConverter, that pass the data via setter and adder methods.
It can also works with classes that have a constructor and has some more features like create DateTime object by typehinting.

The default converter needs the `class` property so that it knows which class should be initialized.

``` yaml
user:
    properties:
        class: 'YourBundle\Entity\User'
    data:
        # ...
```

The converter handles all attributes and it trying to pass the values to the object.

``` yaml
user:
    properties:
        class: 'YourBundle\Entity\User'
    data:
        david:
            name: 'David Badura'
            email: 'd.badura@gmx.de'
```

In this example has the DefaultConverter following workflow:

``` php

$object = new YourBundle\Entity\User();
$object->setName('David Badura');
$object->setEmail('d.badura@gmx.de');
return $object;

```

With the following sequence the DefaultConterver tried to pass the data:

* `$object->set{PropertyName}({value})`
* `$object->add{PropertyName}({value.element})` wrapped in foreach if the value is an array
* `$object->get{PropertyName}()` and then add with `add({value})` method (instanceof ArrayCollection)
* `$object->{PropertyName} = {value}`
* `$object->__set({key}, {value})`

If you have a class with a constructor you can add the `constructor` property. You must define which property are passed in the constructor (the order is important!).

``` yaml
user:
    properties:
        class: 'YourBundle\Entity\User'
        constructor: [name, email]
    data:
        david:
            name: 'David Badura'
            email: 'd.badura@gmx.de'
```

DefaultConverter workflow:

``` php

$object = new YourBundle\Entity\User('David Badura', 'd.badura@gmx.de');
return $object;

```

Also you can mark optional constructor attributes with a `?` symbole.

``` yaml
user:
    properties:
        class: 'YourBundle\Entity\User'
        constructor: [name, ?email]
    data:
        david:
            name: 'David Badura'
```

The DefaultConverter support \DateTime parameters in setter and adder methods:
In this example provide the User Entity this method `YourBundle\Entity\User::setCreateDate(\DateTime $date)`

``` yaml
user:
    properties:
        class: 'YourBundle\Entity\User'
        constructor: [name, ?email]
    data:
        david:
            name: 'David Badura'
            createDate: 'now'
```

DefaultConverter workflow:

``` php

$object = new YourBundle\Entity\User('David Badura');
$object->setCreateDate(new \DateTime('now'));
return $object;

```

Create your own converter
-------------------------

You can also implement your own Converter.
The Converter must extends the `DavidBadura\Fixtures\Converter\AbstractConverter` class
or implement the `DavidBadura\Fixtures\Converter\ConverterInterface` interface.

``` php
// UserConverter.php

use DavidBadura\Fixtures\Converter\AbstractConverter;
use DavidBadura\Fixtures\Fixture\FixtureData;

class UserConverter extends AbstractConverter
{

    public function createObject(FixtureData $fixtureData)
    {
        $data = $fixtureData->getData();

        $user = new User($data['name'], $data['email']);
        foreach ($data['groups'] as $group) {
            $user->addGroup($group);
        }

        return $user;
    }

    public function getName()
    {
        return 'user';
    }
}
```

Now you must register the converter to use it:

``` php

use DavidBadura\Fixtures\FixtureManager\FixtureManager;

$userConverter = new \UserConverter();

$fixtureManager = FixtureManager::createDefaultFixtureManager($objectManager);
$fixtureManager->getExecutor()->addConverter($userConverter);

```

In the last step, your fixture files must add/change the converter property in `user`.

``` yaml
user:
    converter: user
    data: # ...
```

Your converter can also access the properties parameters.

``` yaml
user:
    converter: user
    properties:
        foo: bar
    data: # ...
```

``` php
// BazConverter.php

use DavidBadura\Fixtures\Converter\AbstractConverter;
use DavidBadura\Fixtures\Fixture\FixtureData;

class BazConverter extends AbstractConverter
{

    public function createObject(FixtureData $data)
    {
        $properties = $data->getProperties();
        $properties->get('foo'); # bar
        // ...
    }

    // ...

}
```

To resolve bidrectional references you can overwrite the `finalizeObject` method.

``` php
// GroupConverter.php

use DavidBadura\Fixtures\Converter\AbstractConverter;
use DavidBadura\Fixtures\Fixture\FixtureData;

class GroupConverter extends AbstractConverter
{

    public function createObject(FixtureData $data)
    {
        $data = $fixtureData->getData();

        $group = new Group($data['name']);

        return $group;
    }

    public function finalizeObject($object, FixtureData $data)
    {
        $data = $fixtureData->getData();
        $object->addLadder($data['ladder']);
    }

    public function getName()
    {
        return 'group';
    }
}
```


text:
year: 1987

images:

documents:
---

Retour en Afrique. Traversée du désert avec sa 504.
Achat d'un âne et périple dans la savane au nord Niger entre Sanam et Tahoua.
Rencontre avec les habitants de Dan Marké : 131 familles, 1187 habitants.
Patrick travaille son haoussa, la langue locale, pendant un mois.


text:
package emojih

//go:generate go run ./internal/generator/generator.go ./internal/emoji-data


text:
namespace {

class UVTestCallbackSapiSandbox : public uv::UVSandbox {
 private:
  std::unique_ptr<sandbox2::Policy> ModifyPolicy(
      sandbox2::PolicyBuilder*) override {
    return sandbox2::PolicyBuilder()
        .DangerDefaultAllowAll()
        .AllowDynamicStartup()
        .AllowExit()
        .AllowFutexOp(FUTEX_WAKE_PRIVATE)
        .AllowSyscalls({__NR_epoll_create1, __NR_eventfd2, __NR_pipe2})
        .AllowWrite()
        .BuildOrDie();
  }
};

class UVTestCallback : public ::testing::Test {
 protected:
  void SetUp() override {
    sandbox_ = std::make_unique<UVTestCallbackSapiSandbox>();
    ASSERT_THAT(sandbox_->Init(), sapi::IsOk());
    api_ = std::make_unique<uv::UVApi>(sandbox_.get());
  }

  // Check sapi_uv_timer_init
  void UVTimerInit(sapi::v::Ptr* loop, sapi::v::Ptr* timer) {
    SAPI_ASSERT_OK_AND_ASSIGN(int error_code,
                              api_->sapi_uv_timer_init(loop, timer));
    ASSERT_EQ(error_code, 0);
  }

  // Check sapi_uv_timer_start
  // (actual time is ignored because timeout and repeat are 0)
  void UVTimerStart(sapi::v::Ptr* timer) {
    // Get the TimerCallback callback from the sandbox
    void* timer_cb_voidptr;
    ASSERT_THAT(
        sandbox_->rpc_channel()->Symbol("TimerCallback", &timer_cb_voidptr),
        sapi::IsOk());
    sapi::v::RemotePtr timer_cb(timer_cb_voidptr);

    // Set the timer's callback, timeout and repeat
    SAPI_ASSERT_OK_AND_ASSIGN(
        int error_code, api_->sapi_uv_timer_start(timer, &timer_cb, 0, 0));
    ASSERT_EQ(error_code, 0);
  }

  // Check sapi_uv_run
  void UVRun(sapi::v::Ptr* loop) {
    SAPI_ASSERT_OK_AND_ASSIGN(int error_code,
                              api_->sapi_uv_run(loop, UV_RUN_DEFAULT));
    ASSERT_EQ(error_code, 0);
  }

  // Check sapi_uv_loop_close
  void UVLoopClose(sapi::v::Ptr* loop) {
    SAPI_ASSERT_OK_AND_ASSIGN(int error_code, api_->sapi_uv_loop_close(loop));
    ASSERT_EQ(error_code, 0);
  }

  // Check sapi_uv_default_loop, set loop to default loop
  void UVDefaultLoop(sapi::v::Ptr* loop) {
    SAPI_ASSERT_OK_AND_ASSIGN(void* loop_voidptr, api_->sapi_uv_default_loop());
    loop->SetRemote(loop_voidptr);
  }

  std::unique_ptr<UVTestCallbackSapiSandbox> sandbox_;
  std::unique_ptr<uv::UVApi> api_;

  static constexpr int kData = 1729;
};

TEST_F(UVTestCallback, TimerCallback) {
  // Initialize loop
  sapi::v::RemotePtr loop(nullptr);

  // Allocate memory for timer
  void* timer_voidptr;
  ASSERT_THAT(
      sandbox_->rpc_channel()->Allocate(sizeof(uv_timer_t), &timer_voidptr),
      sapi::IsOk());
  sapi::v::RemotePtr timer(timer_voidptr);

  // Initialize timer and add it to default loop
  UVDefaultLoop(&loop);
  UVTimerInit(loop.PtrNone(), timer.PtrBoth());

  // Set timer data to kData
  sapi::v::Int data(kData);
  void* data_voidptr;
  ASSERT_THAT(sandbox_->rpc_channel()->Allocate(sizeof(int), &data_voidptr),
              sapi::IsOk());
  data.SetRemote(data_voidptr);
  ASSERT_THAT(api_->sapi_uv_handle_set_data(timer.PtrBoth(), data.PtrBefore()),
              sapi::IsOk());

  // Start the timer
  UVTimerStart(timer.PtrBoth());

  // Check that data has not changed (because the loop is not running yet)
  // This is done by resetting the local value and then getting the remote one
  data.SetValue(0);
  ASSERT_THAT(sandbox_->TransferFromSandboxee(&data), sapi::IsOk());
  ASSERT_EQ(data.GetValue(), kData);

  // Run the loop
  UVDefaultLoop(&loop);
  UVRun(loop.PtrNone());

  // Check that data has changed (and therefore callback was called correctly)
  ASSERT_THAT(sandbox_->TransferFromSandboxee(&data), sapi::IsOk());
  ASSERT_EQ(data.GetValue(), kData + 1);

  // Close the loop
  UVDefaultLoop(&loop);
  UVLoopClose(loop.PtrNone());
}

}  // namespace


text:
using System.Collections.Generic;

namespace Avalonia.Threading
{
    public class ThreadSafeObjectPool<T> where T : class, new()
    {
        private Stack<T> _stack = new Stack<T>();
        public static ThreadSafeObjectPool<T> Default { get; } = new ThreadSafeObjectPool<T>();

        public T Get()
        {
            lock (_stack)
            {
                if(_stack.Count == 0)
                    return new T();
                return _stack.Pop();
            }
        }

        public void Return(T obj)
        {
            lock (_stack)
            {
                _stack.Push(obj);
            }
        }
    }
}


text:
import { computeFetch, computeOperation } from 'reducers/rest'
import { combineReducers } from 'redux'

import {
  FV_JOIN_REQUESTS_FETCH_START,
  FV_JOIN_REQUESTS_FETCH_SUCCESS,
  FV_JOIN_REQUESTS_FETCH_ERROR,
  FV_JOIN_REQUEST_UPDATE_START,
  FV_JOIN_REQUEST_UPDATE_SUCCESS,
  FV_JOIN_REQUEST_UPDATE_ERROR,
  FV_MEMBERSHIP_CREATE_START,
  FV_MEMBERSHIP_CREATE_SUCCESS,
  FV_MEMBERSHIP_CREATE_ERROR,
  FV_MEMBERSHIP_FETCH_START,
  FV_MEMBERSHIP_FETCH_SUCCESS,
  FV_MEMBERSHIP_FETCH_ERROR,
} from './actionTypes'

const computeJoinRequestFactory = computeFetch('join_request')
const computeUserFactory = computeFetch('user')
const computeUserDialectsOperation = computeOperation('user_dialects')
const computeUserSelfregisterOperation = computeOperation('user_selfregister')
const computeUserStartPageOperation = computeOperation('user_startpage')

export const fvUserReducer = combineReducers({
  computeMembershipCreate(state = { isFetching: false, message: null, success: false }, action) {
    switch (action.type) {
      case FV_MEMBERSHIP_CREATE_START:
        return { ...state, isFetching: true }

      // Send modified document to UI without access REST end-point
      case FV_MEMBERSHIP_CREATE_SUCCESS:
        return { ...state, message: action.message, isFetching: false, success: true }

      // Send modified document to UI without access REST end-point
      case FV_MEMBERSHIP_CREATE_ERROR:
        return {
          ...state,
          isFetching: false,
          isError: true,
          error: action.message,
        }

      default:
        return { ...state, isFetching: false }
    }
  },
  computeMembershipFetch(state = { isFetching: false, message: null, success: false }, action) {
    switch (action.type) {
      case FV_MEMBERSHIP_FETCH_START:
        return { ...state, isFetching: true }

      // Send modified document to UI without access REST end-point
      case FV_MEMBERSHIP_FETCH_SUCCESS:
        return { ...state, message: action.message, isFetching: false, success: true }

      // Send modified document to UI without access REST end-point
      case FV_MEMBERSHIP_FETCH_ERROR:
        return {
          ...state,
          isFetching: false,
          isError: true,
          error: action.message,
        }

      default:
        return { ...state, isFetching: false }
    }
  },
  computeUpdateJoinRequest(state = { isFetching: false, message: null, success: false }, action) {
    switch (action.type) {
      case FV_JOIN_REQUEST_UPDATE_START:
        return { ...state, isFetching: true }

      // Send modified document to UI without access REST end-point
      case FV_JOIN_REQUEST_UPDATE_SUCCESS:
        return { ...state, message: action.message, isFetching: false, success: true }

      // Send modified document to UI without access REST end-point
      case FV_JOIN_REQUEST_UPDATE_ERROR:
        return {
          ...state,
          isFetching: false,
          isError: true,
          error: action.message,
        }

      default:
        return { ...state, isFetching: false }
    }
  },
  computeJoinRequests(state = { isFetching: false, message: null, success: false }, action) {
    switch (action.type) {
      case FV_JOIN_REQUESTS_FETCH_START:
        return { ...state, isFetching: true }

      // Send modified document to UI without access REST end-point
      case FV_JOIN_REQUESTS_FETCH_SUCCESS:
        return { ...state, message: action.message, isFetching: false, success: true }

      // Send modified document to UI without access REST end-point
      case FV_JOIN_REQUESTS_FETCH_ERROR:
        return {
          ...state,
          isFetching: false,
          isError: true,
          error: action.message,
        }

      default:
        return { ...state, isFetching: false }
    }
  },
  computeJoinRequest: computeJoinRequestFactory.computeJoinRequest,
  computeUser: computeUserFactory.computeUser,
  computeUserDialects: computeUserDialectsOperation.computeUserDialects,
  computeUserSelfregister: computeUserSelfregisterOperation.computeUserSelfregister,
  computeUserStartpage: computeUserStartPageOperation.computeUserStartpage,
})


text:
/*jslint browser: true, devel: true, plusplus: true, nomen: true */
/*global require, define, module, console, jQuery */

/**
 * Hooks to apply on content
 *
 * @package dragonet
 * @subpackage dragonet.modules.hooks
 */
(function (dragonet, $) {
	'use strict';

	// Define the variables used
	var hooks,
		iterator,
		children;

	// The main hooks object
	hooks = {
		// List of hooks
		list: [],

		// Hooks initStatus: the hooks can be automatically executed on the global selector - $('html') - only once
		initStatus: 'waiting'
	};

	/**
	 * Add a hook
	 * @param   {string}   selector jQuery selector for the elements to apply to hook function on
	 * @param   {function} fn       Function to apply on the element. Receives only 1 parameter, the item itself
	 * @param   {string}   type     The type of the selector: load - run only when the page loads, always - run when the selector is encountered
	 * @returns {string}	Return the selector
	 */
	hooks.add = function (selector, fn, type) {
		if (typeof type === 'undefined') {
			type = 'always';
		}

		if (typeof fn === 'function') {
			hooks.list.push({
				selector: selector,
				fn: fn,
				type: type
			});
		}

		return selector;
	};

	/**
	 * Remove a hook
	 * @param {string} selector jQuery selector corresponding to the hook
	 * @returns {string}	Return the selector
	 */
	hooks.remove = function (selector) {
		if (typeof hooks.list[selector] !== 'undefined') {
			delete hooks.list[selector];
		}

		hooks.list.map(function (item, idx) {
			if (item.selector === selector) {
				hooks.list.splice(idx, 1);
			}
		});

		return selector;
	};

	/**
	 * Execute the existing hooks
	 * @param {object} realm jQuery selector for the html element to apply the hooks on
	 */
	hooks.exec = function (realm) {
		var obj;

		switch (typeof realm) {
		case 'string':
			obj = $(realm);
			break;
		case 'object':
			obj = realm;
			break;
		case 'undefined':
			if (hooks.initStatus === 'waiting') {
				obj = $('html');
				hooks.initStatus = 'executing';
			} else {
				return;
			}
			break;
		default:
			return;
		}

		// Loop through hooks
		// each hook
		hooks.list.map(function (value, key) {
			// Children of the selector in the target element
			obj.find(value.selector).each(function (idx, el) {
				if (value.type !== 'load' || hooks.initStatus === 'executing') {
					value.fn.call(this, $(el));
				}
			});
		});

		// Complete the init
		if (hooks.initStatus === 'executing') {
			hooks.initStatus = 'finished';
		}
	};

	/**
	 * Add dragonet to the window object
	 */
	dragonet.add = hooks.add;
	dragonet.remove = hooks.remove;
	dragonet.exec = hooks.exec;

	// Apply the initial hooks
	$(document).ready(function () {
		dragonet.exec();
	});

}(window.dragonet = window.dragonet || {}, jQuery));


text:
function dispProj_CALLBACK(src,evnt,parameters)
%dispProj_CALLBACK.m Callback function to display projection
%
%INPUTS
%parameters - parameters structure
%
%ASM 11/13

%get parameters
parameters = get(parameters.ROIFig,'UserData');

if parameters.dispProj
    parameters.dispProj = false;

    %save updated parameters
    set(parameters.ROIFig,'UserData',parameters);

    set(parameters.projection,'String','Show Projection');

    %update frame
    changeFrame_CALLBACK(src,evnt,parameters);

    return;
end

%create projection name string
if strcmpi(parameters.projType,'Average')
    projString = [fullfile(parameters.filePath,parameters.fileBase),'_avgProj.tif'];
elseif strcmpi(parameters.projType,'Max')
    projString = [fullfile(parameters.filePath,parameters.fileBase),'_maxProj.tif'];
elseif strcmpi(parameters.projType,'Gaussian')
    projString = [fullfile(parameters.filePath,parameters.fileBase),'_gaussProj.tif'];
end

%check if file exists
if exist(projString,'file')
    projExist = true;
else
    projExist = false;
end

%ask user to create projection if doesn't exist
if ~projExist
    questAns = questdlg('Projection does not exist. Create? This will take several minutes.',...
        'No projection exists','Yes','No','Yes');
    switch questAns
        case 'Yes'
            if parameters.folderMode
                tiffProj = createMultiTiffProjection(parameters.filePath,parameters.fileStr,false);
                saveastiff(tiffProj,projString);
            else
                %load in entire tiff
                tiff = loadtiffAM(parameters.ROIFile);

                %project tiff (avg)
                tiffProj = sum(tiff,3)/size(tiff,3);

                %save projected tiff
                saveastiff(tiffProj,projString);
            end
        case 'No'
            return;
    end
end

%if tiff projection does exist, load
if projExist
    tiffProj = loadtiffAM(projString);
end

%store projection
parameters.tiffProj = tiffProj;
parameters.dispProj = true;
set(parameters.projection,'String','Hide Projection');

%save updated parameters
set(parameters.ROIFig,'UserData',parameters);

%update frame
changeFrame_CALLBACK(src,evnt,parameters);


text:
module Merb
  module Rack
    class PathPrefix < Merb::Rack::Middleware

      def initialize(app, path_prefix = nil)
        super(app)
        @path_prefix = /^#{Regexp.escape(path_prefix)}/
      end

      def deferred?(env)
        strip_path_prefix(env)
        @app.deferred?(env)
      end

      def call(env)
        strip_path_prefix(env)
        @app.call(env)
      end

      def strip_path_prefix(env)
        ['PATH_INFO', 'REQUEST_URI'].each do |path_key|
          if env[path_key] =~ @path_prefix
            env[path_key].sub!(@path_prefix, '')
            env[path_key] = '/' if env[path_key].empty?
          end
        end
      end

    end
  end
end


text:
//Simulator for the simulation of the automata
autoSim.SimulatorTM = function($scope, $uibModal) {
    var self = this;
    autoSim.Simulator.apply(this, arguments);

    self.tape = new autoSim.TMTape($scope);
    self.virtualTape = new autoSim.TMTape($scope);

    self.tape.refillTape();
    self.tape.setPointer();
    self.virtualTape.refillTape();
    self.virtualTape.setPointer();

    //save the reference
    var parentReset = this.reset;

    /**
     * Should reset the simulation
     */
    self.reset = function() {
        self.tape.refillTape();
        self.tape.fillTape($scope.automatonData.inputWord);
        self.virtualTape.refillTape();
        self.virtualTape.fillTape($scope.automatonData.inputWord);
        self.currentSequencePosition = 0;
        self.animated = {
            currentState: null,
            transition: null,
            nextState: null,
            currentTapeItem: null
        };
        parentReset.apply(this);
    }

    /**
     * Prepare the simulation (set startSettings)
     */
    self.prepareSimulation = function() {
        self.reset();
        self.isInAnimation = true;
        self.sequences = self.getSequences(self.virtualTape.tapeArray);
    };

    /**
     * Make a step forward
     */
    self.stepForward = function() {
        var modalIsDisplayed = false;
        if (!self.isInAnimation) {
            self.prepareSimulation();
        }
        if (!_.includes(["accepted", "notAccepted"], self.status)) {
            // if (self.isEmptyWordAccepted && self.tape.isEmpty() === true) {
            //     self.animateEmptyWord();
            // } else {
                if (self.animated.currentState === null) {
                    self.animateCurrentState();
                    self.animateCurrentTapeItem();
                } else if (self.animated.transition === null) {
                    self.animateTransition();
                    self.animateCurrentTapeItem();
                    if (self.animated.transition !== null) {
                        self.tape.writeOnTape(self.animated.transition.outputSymbol);
                        if (self.animated.transition.movingDirection === "→") {
                            self.tape.pointerGoRight();
                        } else if (self.animated.transition.movingDirection === "←") {
                            self.tape.pointerGoLeft();
                        } else {
                            self.tape.pointerStay();
                        }
                        //wenn aktiviert, dann wandert currentTapeItem gleichzeitig mit Pointer
                        // self.animateCurrentTapeItem();
                    }
                    if (self.tape.pointer > 24 && !self.modalIsDisplayed) {
                        $uibModal.open({
                            ariaLabelledBy: 'modal-title',
                            templateUrl: '/app/components/automata/tm/views/tm.modal.html',
                            controller: 'ModalCtrl',
                            controllerAs: 'vm'
                        });
                        self.modalIsDisplayed = true;
                    }
                    if (self.tape.pointer < 0 && !self.modalIsDisplayed) {
                      $uibModal.open ({
                        ariaLabelledBy: 'modal-title',
                        templateUrl: '/app/components/automata/tm/views/tm.modal.html',
                        controller: 'ModalCtrl',
                        controllerAs: 'vm'
                      });
                      self.modalIsDisplayed = true;
                    }
                } else if (self.animated.nextState === null) {
                    self.animateNextState();
                    self.animateCurrentTapeItem();
                } else {
                    self.changeNextStateToCurrentState();
                }
            // }
        }
        $scope.saveApply();
    };

    self.sleep = function(milliseconds) {
        var start = new Date().getTime();
        for (var i = 0; i < 1e7; i++) {
            if ((new Date().getTime() - start) > milliseconds) {
                break;
            }
        }
    }
    /**
     *Animate the currentState
     */
    self.animateCurrentTapeItem = function() {
        self.animated.currentTapeItem = self.tape.pointer;
    };

    /**
     *Change the currentState to the nextState
     */
    self.changeNextStateToCurrentState = function() {
        self.currentPosition++;
        self.currentSequencePosition++;
        self.animated.currentState = self.animated.nextState;
        self.animated.nextState = null;
        self.animated.transition = null;
        if (self.isAnimationAccepted()) {
            self.status = "accepted";
            self.isInPlay = false;
        }
    };

    /**
     * Returns if the animation is accepted for overriding
     * @returns {boolean}
     */
    self.isAnimationAccepted = function() {
        return self.currentSequencePosition == self.sequences.sequences[0].length && self.sequences.possible;
    };

    /**
     * Goes the animation back. if we have only a currentState
     */
    self.goAnimationBack = function() {
        self.status = "unknown";
        if (self.currentPosition !== 0) {
            self.currentPosition--;
            self.animated.nextState = self.animated.currentState;
            self.animated.transition = self.getLongestSequence(self.sequences.sequences)[self.currentPosition];
            if (self.animated.transition.movingDirection === "→") {
                self.tape.pointerGoLeft();
            } else if (self.animated.transition.movingDirection === "←") {
                self.tape.pointerGoRight();
            } else {
                self.tape.pointerStay();
            }
            self.tape.writeOnTape(self.animated.transition.inputSymbol);
            self.animated.currentState = self.animated.transition.fromState;
        } else {
            self.reset();
        }
    };

    /**
     * checks if a word is accepted from the automata
     * @return {Boolean}
     */
    self.isInputWordAccepted = function(tapeWord) {
        self.virtualTape.tapeSetup($scope.automatonData.inputWord);
        return self.getSequences(self.virtualTape.tapeArray).possible;
    };

    /**
     * Return either the possibleSequences, if there is no possibleSequence, then return the farthestPossibleSequences
     * @param inputWord
     * @returns {{}}
     */
    self.getSequences = function(tapeWord) {
        self.virtualTape.fillTape(tapeWord);
        tapeWord = self.virtualTape.tapeArray;
        var tmpObj = {};
        if (self.tape.isEmpty() && $scope.states.final.isFinalState($scope.states.startState)) {
            tmpObj.possible = true;
            tmpObj.sequences = [];
            return tmpObj;
        }
        // if (self.tape.isEmpty()) {
        //     if ($scope.states.final.isFinalState($scope.states.startState)) {
        //         tmpObj.possible = true;
        //         tmpObj.sequences = [];
        //         return tmpObj;
        //     } else {
        //         tmpObj.possible = false;
        //         tmpObj.sequences = [];
        //         return tmpObj;
        //     }
        // }
        var possibleSequences = self.getAllPossibleSequences(tapeWord);
        if (possibleSequences.length !== 0) {
            tmpObj.possible = true;
            tmpObj.sequences = possibleSequences;
            return tmpObj;
        } else {
            tmpObj.possible = false;
            tmpObj.sequences = self.getFarthestPossibleSequences(tapeWord);
            return tmpObj;
        }
    };

    /**
     * returns all possible transition, which go from the fromState with the inputSymbol to a state
     * @param fromState
     * @param inputSymbol
     * @returns {Array}
     */
    self.getNextTransitions = function(fromState, tapeSymbol) {
        var transitions = [];
        _.forEach($scope.transitions, function(transitionGroup) {
            _.forEach(transitionGroup, function(transition) {
                if (transition.fromState == fromState && transition.inputSymbol == tapeSymbol) {
                    transitions.push([transition]);
                }
            })
        });
        return transitions;
    };

    /**
     * Returns all possible sequences, if an empty array is returned, there is no possibleSequence
     * @param inputWord
     * @returns {Array}
     */
    self.getAllPossibleSequences = function(tapeWord) {
        var possibleSequences = [];
        var state = $scope.states.startState;
        var possibleSequence = [];

        while (self.getNextTransitions(state, self.virtualTape.tapeArray[self.virtualTape.pointer]).length !== 0) {
            var possibleTransition = self.getNextTransitions(state, self.virtualTape.tapeArray[self.virtualTape.pointer]);
            if (possibleTransition[0][0].inputSymbol === tapeWord[self.virtualTape.pointer]) {
                self.virtualTape.writeOnTape(possibleTransition[0][0].outputSymbol);
                if (possibleTransition[0][0].movingDirection === "→") {
                    self.virtualTape.pointerGoRight();
                } else if (possibleTransition[0][0].movingDirection === "←") {
                    self.virtualTape.pointerGoLeft();
                } else {
                    self.virtualTape.pointerStay();
                }
                possibleSequence.push(possibleTransition[0][0]);
            }
            // } else if ($scope.states.final.isFinalState(possibleTransition[0][0].fromState)) {
            //     possibleSequences.push(possibleSequence);
            //     return possibleSequences;
            // } else {
            //     self.virtualTape.refillTape();
            //     self.virtualTape.fillTape($scope.automatonData.inputWord);
            //     possibleSequences = [];
            //     console.log("start");
            //     return possibleSequences;
            // }
            state = possibleTransition[0][0].toState;
        }
        if ($scope.states.final.isFinalState(state)) {
            possibleSequences.push(possibleSequence);
            return possibleSequences;
        }
        self.virtualTape.tapeSetup($scope.automatonData.inputWord);
        return possibleSequences;

        // //as long as there are possibleSequences do
        // while (tapeSequences.length !== 0) {
        //     var tmpSequence = tapeSequences.pop();
        //     if (tmpSequence.length === self.tape.numOfChar && $scope.states.final.isFinalState(_.last(tmpSequence).toState)) {
        //         possibleSequences.push(tmpSequence);
        //     } else if (self.tape.numOfChar > tmpSequence.length) {
        //         // console.log(tmpSequence);
        //         var tmpSequences = [];
        //         var newTmpSequence = [];
        //         var i = self.getPointerPosition(tmpSequence);
        //         console.log(tapeWord[i]);
        //         _.forEach(self.getNextTransitions(_.last(tmpSequence).toState, tapeWord[self.tape.pointer + tmpSequence.length]), function(value) {
        //             newTmpSequence = _.concat(tmpSequence, value);
        //             tmpSequences.push(newTmpSequence);
        //         });
        //         tapeSequences = _.concat(tapeSequences, tmpSequences);
        //     }
        // }
        // return possibleSequences;
    };

    /**
     * Returns the farthest possible sequences
     * @param inputWord
     * @returns {Array}
     */
    self.getFarthestPossibleSequences = function(tapeWord) {
        var farthestSequences = [];
        //     //     //1.Get the all possible transitions
        //     //     var tapeSequences = self.getNextTransitions($scope.states.startState, tapeWord[self.tape.pointer]);
        //     //     //as long as there are possibleSequences do
        //     //     while (tapeSequences.length !== 0) {
        //     //         var tmpSequence = tapeSequences.pop();
        //     //         if (tmpSequence.length === self.tape.numOfChar && $scope.states.final.isFinalState(_.last(tmpSequence).toState)) {}
        //     // else if (self.tape.numOfChar > tmpSequence.length) {
        //     //             var tmpSequences = [];
        //     //             var newTmpSequence = [];
        //     //             var i = self.tape.pointer + tmpSequence.length;
        //     //             _.forEach(self.getNextTransitions(_.last(tmpSequence).toState, tapeWord[i]), function(value) {
        //     //                 newTmpSequence = _.concat(tmpSequence, value);
        //     //                 tmpSequences.push(newTmpSequence);
        //     //             });
        //     //             tapeSequences = _.concat(tapeSequences, tmpSequences);
        //     //             if (tmpSequences.length === 0) {
        //     //                 farthestSequences.push(tmpSequence);
        //     //             }
        //     //         } else {
        //     //             farthestSequences.push(tmpSequence);
        //     //         }
        //     //     }
        //     //     return farthestSequences;
        //
        var state = $scope.states.startState;
        var farthestSequence = [];

        while (self.getNextTransitions(state, self.virtualTape.tapeArray[self.virtualTape.pointer]).length !== 0) {
            var possibleTransition = self.getNextTransitions(state, self.virtualTape.tapeArray[self.virtualTape.pointer]);
            if (possibleTransition[0][0].inputSymbol === tapeWord[self.virtualTape.pointer]) {
                self.virtualTape.writeOnTape(possibleTransition[0][0].outputSymbol);
                if (possibleTransition[0][0].movingDirection === "→") {
                    self.virtualTape.pointerGoRight();
                } else if (possibleTransition[0][0].movingDirection === "←") {
                    self.virtualTape.pointerGoLeft();
                } else {
                    self.virtualTape.pointerStay();
                }
                farthestSequence.push(possibleTransition[0][0]);
            }
            // } else if ($scope.states.final.isFinalState(possibleTransition[0][0].fromState)) {
            //     farthestSequences.push(farthestSequence);
            //     return farthestSequences;
            // } else {
            //     farthestSequences = [];
            //     return farthestSequences;
            // }
            state = possibleTransition[0][0].toState;
        }
        if ($scope.states.final.isFinalState(state)) {
            farthestSequences.push(farthestSequence);
            return farthestSequences;
        }
        farthestSequences.push(farthestSequence);
        return farthestSequences;
    };

    /**
     *update the currentSequences if it didn't break the simulation
     */
    self.updateCurrentSequences = function() {};

    // //save the reference
    // var parentReset = this.reset;
    //
    // /**
    //  * Should reset the simulation
    //  */
    // self.reset = function () {
    //     self.stack = new autoSim.PDAStack();
    //     parentReset.apply(this);
    //
    //     //TODO:
    //     //$scope.statediagram.addToStack(self.stack.stackContainer);
    // };
    //
    // /**
    //  * for stack pop used
    //  */
    // self.animateTransitionOverride = function () {
    //     self.stack.pop();
    // };
    //
    // //saving reference
    // var parentChangeNextStateToCurrentState = self.changeNextStateToCurrentState;
    //
    // /**
    //  * stack push integrated
    //  */
    // self.changeNextStateToCurrentState = function () {
    //     self.stack.push(self.animated.transition.writeToStack);
    //     parentChangeNextStateToCurrentState();
    // };

    // /**
    //  * Returns all possible sequences, if an empty array is returned, there is no possibleSequence
    //  * @param inputWord
    //  * @returns {Array}
    //  */
    // self.getAllPossibleSequences = function(inputWord) {
    //     var possibleSequences = [];
    //     //Get the all possible transitions
    //     var stackSequences = self.getNextTransitions($scope.states.startState, inputWord[0]);
    //     //as long as there are possibleSequences do
    //     while (stackSequences.length !== 0) {
    //         var tmpSequence = stackSequences.pop();
    //         if (tmpSequence.length === inputWord.length && $scope.states.final.isFinalState(_.last(tmpSequence).toState)) {
    //             possibleSequences.push(tmpSequence);
    //         } else if (inputWord.length > tmpSequence.length) {
    //             var tmpSequences = [];
    //             var newTmpSequence = [];
    //             _.forEach(self.getNextTransitions(_.last(tmpSequence).toState, inputWord[tmpSequence.length]), function(value) {
    //                 newTmpSequence = _.concat(tmpSequence, value);
    //                 tmpSequences.push(newTmpSequence);
    //             });
    //             stackSequences = _.concat(stackSequences, tmpSequences);
    //         }
    //     }
    //     return possibleSequences;
    // //init needed variables
    // var possibleSequences = [];
    // var stackSequences = [];
    // var tmpSequences = [];
    //
    // if (inputWord.length !== 0) {
    //     tmpSequences = self.getNextTransitions($scope.states.startState, inputWord[0], new autoSim.PDAStack().stackFirstSymbol);
    //     for (var i = 0; i < tmpSequences.length; i++) {
    //         var tmpSequence = {};
    //         tmpSequence.stack = new autoSim.PDAStack();
    //         tmpSequence.stack.pop();
    //         tmpSequence.stack.push(tmpSequences[i].writeToStack);
    //         tmpSequence.value = [tmpSequences[i]];
    //         stackSequences.push(tmpSequence);
    //     }
    // }
    //
    // while (stackSequences.length !== 0) {
    //     tmpSequence = stackSequences.pop();
    //     if (tmpSequence.value.length === inputWord.length && tmpSequence.stack.stackContainer.length === 0) {
    //         possibleSequences.push(tmpSequence.value);
    //     } else if (inputWord.length > tmpSequence.value.length && tmpSequence.stack.stackContainer.length !== 0) {
    //         tmpSequences = [];
    //         _.forEach(self.getNextTransitions(_.last(tmpSequence.value).toState, inputWord[tmpSequence.value.length], tmpSequence.stack.pop()), function (sequence) {
    //             var newTmpSequence = {};
    //             newTmpSequence.stack = new autoSim.PDAStack(tmpSequence.stack.stackContainer);
    //             newTmpSequence.stack.push(sequence.writeToStack);
    //             newTmpSequence.value = _.concat(tmpSequence.value, sequence);
    //             tmpSequences.push(newTmpSequence);
    //         });
    //         stackSequences = _.concat(stackSequences, tmpSequences);
    //     }
    // }
    // return possibleSequences;
    // };

    // /**
    //  * Returns the farthest possible sequences
    //  * @param inputWord
    //  * @returns {Array}
    //  */
    // self.getFarthestPossibleSequences = function(inputWord) {
    //     var farthestSequences = [];
    //     //1.Get the all possible transitions
    //     var stackSequences = self.getNextTransitions($scope.states.startState, inputWord[0]);
    //     //as long as there are possibleSequences do
    //     while (stackSequences.length !== 0) {
    //         var tmpSequence = stackSequences.pop();
    //         if (tmpSequence.length === inputWord.length && $scope.states.final.isFinalState(_.last(tmpSequence).toState)) {} else if (inputWord.length > tmpSequence.length) {
    //             var tmpSequences = [];
    //             var newTmpSequence = [];
    //             _.forEach(self.getNextTransitions(_.last(tmpSequence).toState, inputWord[tmpSequence.length]), function(value) {
    //                 newTmpSequence = _.concat(tmpSequence, value);
    //                 tmpSequences.push(newTmpSequence);
    //             });
    //             stackSequences = _.concat(stackSequences, tmpSequences);
    //             if (tmpSequences.length === 0) {
    //                 farthestSequences.push(tmpSequence);
    //             }
    //         } else {
    //             farthestSequences.push(tmpSequence);
    //         }
    //     }
    //     return farthestSequences;
    // //init needed variables
    // var farthestSequences = [];
    // var stackSequences = [];
    // var tmpSequences = [];
    //
    //
    // if (inputWord.length !== 0) {
    //     tmpSequences = self.getNextTransitions($scope.states.startState, inputWord[0], new autoSim.PDAStack().stackFirstSymbol);
    //     for (var i = 0; i < tmpSequences.length; i++) {
    //         var tmpSequence = {};
    //         tmpSequence.stack = new autoSim.PDAStack();
    //         tmpSequence.stack.pop();
    //         tmpSequence.stack.push(tmpSequences[i].writeToStack);
    //         tmpSequence.value = [tmpSequences[i]];
    //         stackSequences.push(tmpSequence);
    //     }
    // }
    //
    // while (stackSequences.length !== 0) {
    //     tmpSequence = stackSequences.pop();
    //     if (tmpSequence.value.length === inputWord.length && tmpSequence.stack.stackContainer.length === 0) {
    //     } else if (inputWord.length > tmpSequence.value.length && tmpSequence.stack.stackContainer.length !== 0) {
    //         tmpSequences = [];
    //         _.forEach(self.getNextTransitions(_.last(tmpSequence.value).toState, inputWord[tmpSequence.value.length], tmpSequence.stack.pop()), function (sequence) {
    //             var newTmpSequence = {};
    //             newTmpSequence.stack = new autoSim.PDAStack(tmpSequence.stack.stackContainer);
    //             newTmpSequence.stack.push(sequence.writeToStack);
    //             newTmpSequence.value = _.concat(tmpSequence.value, sequence);
    //             tmpSequences.push(newTmpSequence);
    //         });
    //         stackSequences = _.concat(stackSequences, tmpSequences);
    //         if (tmpSequences.length === 0) {
    //             farthestSequences.push(tmpSequence.value);
    //         }
    //     } else {
    //         farthestSequences.push(tmpSequence.value);
    //     }
    // }
    // return farthestSequences;
    // };

};


text:
var gulp    = require('gulp')
// var package = require('../../package.json')
var path    = require('path')

// var settings = {
//   url: package.homepage,
//   src: path.join(Config.root.dest, '/**/*'),
// }

module.exports = function(){
  gulp.task('deploy', ['build:production'], function() {
    // deploy stuff
  })
};


text:
package uk.joshiejack.penguinlib.world.storage.loot;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import uk.joshiejack.penguinlib.util.interfaces.IPenguinMulti;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.storage.loot.LootContext;
import net.minecraft.world.storage.loot.conditions.LootCondition;
import net.minecraft.world.storage.loot.functions.LootFunction;

import javax.annotation.Nonnull;
import java.util.Random;

import static uk.joshiejack.penguinlib.PenguinLib.MOD_ID;

public class SetEnum extends LootFunction {
    private final String name;

    public SetEnum(LootCondition[] conditionsIn, String name) {
        super(conditionsIn);
        this.name = name;
    }

    @Nonnull
    public ItemStack apply(@Nonnull ItemStack stack, @Nonnull Random rand, @Nonnull LootContext context) {
        if (stack.getItem() instanceof IPenguinMulti) {
            return ((IPenguinMulti)stack.getItem()).getStackFromEnumString(name, stack.getCount());
        } else return stack;
    }

    public static class Serializer extends LootFunction.Serializer<SetEnum> {
        public Serializer() {
            super(new ResourceLocation(MOD_ID, "set_enum"), SetEnum.class);
        }

        public void serialize(@Nonnull JsonObject object, @Nonnull SetEnum functionClazz, @Nonnull JsonSerializationContext serializationContext) {
            object.addProperty("enum", functionClazz.name);
        }

        @Nonnull
        public SetEnum deserialize(@Nonnull JsonObject object, @Nonnull JsonDeserializationContext deserializationContext, @Nonnull LootCondition[] conditionsIn) {
            return new SetEnum(conditionsIn, object.get("enum").getAsString());
        }
    }
}


text:
.. include:: meta-toggle.rst

Toggle the visibility of an element.

Example::

   {% button action={toggle target="myid"} %}

Shows the element with id `myid` if it was hidden, otherwise hide it.

.. seealso:: actions :ref:`action-show`, :ref:`action-hide`, :ref:`action-fade_in`, :ref:`action-fade_out`, :ref:`action-slide_down`, :ref:`action-slide_up`, :ref:`action-slide_fade_in` and :ref:`action-slide_fade_out`.


text:
package pvi

import (
	"github.com/stretchr/testify/assert"
	"os"
	"testing"
)

func TestPrintToFile(t *testing.T) {
	var filename = "fileToPrint.txt"
	defer os.Remove(filename)

	PrintToFile("This is written!", filename)
	_, err := os.Stat(filename)
	assert.False(t, os.IsNotExist(err))
}


text:
from __future__ import unicode_literals
import abc
import itertools

class SentenceLanguage(object):
    _USER_TEXT_FIELD_NAME = 'user'
    _TOTAL_FIELD_NAME = 'total'
    _COUNTING_FIELD_NAME = 'counting'
    _CHARACTER_FIELD_NAME = 'char'
    _COUNT_FIELD_NAME = 'cnt'

    @abc.abstractmethod
    def is_countable_character(self, character):
        """
        :type character: unicode
        :rtype: bool
        """
        pass

    def tokenize(self, text):
        """
        :type text: unicode
        :rtype: collections.Iterable[unicode]
        """
        return itertools.ifilter(self.is_countable_character, text or '')

    @property
    @abc.abstractproperty
    def special_characters(self):
        """
        :rtype: collections.Iterable[unicode]
        """
        raise NotImplementedError

    @abc.abstractmethod
    def translate_number(self, number):
        """
        :type number: int | long
        :rtype: unicode
        """
        pass

    def compose_sentence(self, total_count, character_counts, user_text=None):
        """
        :type total_count: int
        :type character_counts: dict[unicode, int]
        :rtype: unicode
        """
        counting_text = ''.join([
            self._compose_character_count(character, count)
            for character, count in character_counts.iteritems()
            if count > 0
        ])

        params = {
            self._USER_TEXT_FIELD_NAME: user_text or '',
            self._TOTAL_FIELD_NAME: self.translate_number(total_count),
            self._COUNTING_FIELD_NAME: counting_text,
        }
        return self._sentence_template.format(**params)

    def get_single_use_template_text(self, user_text=''):
        """
        :rtype: unicode
        """
        params = {
            self._USER_TEXT_FIELD_NAME: user_text or '',
            self._TOTAL_FIELD_NAME: '',
            self._COUNTING_FIELD_NAME: '',
        }
        return self._sentence_template.format(**params)

    def get_repeated_template_text(self):
        """
        :rtype: unicode
        """
        params = {
            self._CHARACTER_FIELD_NAME: '',
            self._COUNT_FIELD_NAME: '',
        }
        return self._character_count_template.format(**params)

    @property
    @abc.abstractproperty
    def _sentence_template(self):
        """
        :rtype: unicode
        """
        raise NotImplementedError

    @property
    @abc.abstractproperty
    def _character_count_template(self):
        """
        :rtype: unicode
        """
        raise NotImplementedError

    def _compose_character_count(self, character, count):
        """
        :type character: unicode
        :type count: int
        :rtype: unicode
        """
        params = {
            self._CHARACTER_FIELD_NAME: character,
            self._COUNT_FIELD_NAME: self.translate_number(count),
        }
        return self._character_count_template.format(**params)


text:
// Copyright (c) Zolution Software Ltd. All rights reserved.
// Licensed under the MIT License, see LICENSE.txt in the solution root for license information

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Rezolver.Tests.Examples.Types
{
    //<example>
    public class HasAttributeInjectedMembers
    {
        [Inject]
        public IMyService InjectedServiceField;

        [Inject(typeof(MyService6))]
        public IMyService InjectedServiceProp { get; set; }

        //these two will not be injeccted

        public IMyService ServiceField;
        public IMyService ServiceProp { get; set; }
    }
    //</example>
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('healthsites', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='HealthsiteAssessmentEntryDropDown',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('selected_option', models.CharField(max_length=32)),
                ('assessment_criteria', models.ForeignKey(to='healthsites.AssessmentCriteria')),
                ('healthsite_assessment', models.ForeignKey(to='healthsites.HealthsiteAssessment')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='HealthsiteAssessmentEntryInteger',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('selected_option', models.IntegerField()),
                ('assessment_criteria', models.ForeignKey(to='healthsites.AssessmentCriteria')),
                ('healthsite_assessment', models.ForeignKey(to='healthsites.HealthsiteAssessment')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='HealthsiteAssessmentEntryReal',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('selected_option', models.DecimalField(max_digits=9, decimal_places=2)),
                ('assessment_criteria', models.ForeignKey(to='healthsites.AssessmentCriteria')),
                ('healthsite_assessment', models.ForeignKey(to='healthsites.HealthsiteAssessment')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.RemoveField(
            model_name='healthsiteassessmententry',
            name='assessment_criteria',
        ),
        migrations.RemoveField(
            model_name='healthsiteassessment',
            name='assessment_groups',
        ),
        migrations.DeleteModel(
            name='HealthsiteAssessmentEntry',
        ),
        migrations.AddField(
            model_name='assessmentcriteria',
            name='result_type',
            field=models.CharField(default=b'Integer', max_length=32, choices=[(b'DropDown', b'DropDown'), (b'Integer', b'Integer'), (b'Decimal', b'Decimal'), (b'MultipleChoice', b'MultipleChoice')]),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='resultoption',
            name='value',
            field=models.IntegerField(default=1),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='healthsite',
            name='date',
            field=models.DateTimeField(auto_now_add=True),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='healthsite',
            name='uuid',
            field=models.CharField(help_text=b'Unique identifier', unique=True, max_length=32, verbose_name=b'UUID'),
            preserve_default=True,
        ),
    ]


text:
package projectgoldstarsx;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class StartSearch
{
    public StartSearch()
    {
        getSearchCaseSensitivitySetting();
    }

    /*
     * Attempt to import the saved choice of whether Search is case-sensitive from the Search folder.
     * If nothing has been saved, Project GoldStars X will turn off case sensitivity for Search and save this to the Search folder.
     */
    private static void getSearchCaseSensitivitySetting()
    {
        File scsTemp = new File(ProjectGoldStarsX.SEARCH_FOLDER, "searchCaseSensitive.txt");
        try
        {
            Scanner s9 = new Scanner(scsTemp).useDelimiter("\\Z");
            String temp = s9.next();
            s9.close();
            if("1".equals(temp))
            {
                ProjectGoldStarsX.searchCaseSensitive = true;
            }
            else
            {
                ProjectGoldStarsX.searchCaseSensitive = false;
            }
        }
        catch(FileNotFoundException e)
        {
            File file = new File(ProjectGoldStarsX.SEARCH_FOLDER, "searchCaseSensitive.txt");
            ProjectGoldStarsX.searchCaseSensitive = false;
            PrintWriter out;
            try
            {
                out = new PrintWriter(file);
                out.println("0");
                out.close();
            }
            catch(FileNotFoundException e2)
            {

            }
        }
    }
}


text:
<?xml version="1.0"?>
<mapping>
	<dbms product="MicrosoftCrm" id="mscrm_id" label="Mapping MicrosoftCrm"
		default="true">
		<dbTypes>
			<dbType type="BOOLEAN" ignorePre="true" />
			<dbType type="CUSTOMER" ignorePre="true" defaultLength="36" />
			<dbType type="DATETIME" ignorePre="true" ignoreLen="true"/>
			<dbType type="DECIMAL" defaultLength="20" defaultPrecision="10" preBeforelen="false" />
			<dbType type="DOUBLE" defaultLength="20" defaultPrecision="10" />
			<dbType type="INTEGER" ignorePre="true" />
			<dbType type="LOOKUP" ignorePre="true" defaultLength="36" />
			<dbType type="MEMO" ignorePre="true" default="true" defaultLength="100" />
			<dbType type="MONEY" defaultLength="20" defaultPrecision="10" preBeforelen="false" />
			<dbType type="OWNER" ignorePre="true" defaultLength="36" />
			<dbType type="PARTYLIST" ignorePre="true" />
			<dbType type="PICKLIST" ignorePre="true" />
			<dbType type="STATE" ignorePre="true" />
			<dbType type="STATUS" ignorePre="true" />
			<dbType type="STRING" ignorePre="true" default="true" defaultLength="100" />
			<dbType type="UNIQUEIDENTIFIER" ignorePre="true" defaultLength="36" />
			<dbType type="CALENDARRULES" ignorePre="true" />
			<!--dbType type="VIRTUAL" ignorePre="true" /-->
			<dbType type="BIGINT" ignorePre="true" />
			<dbType type="MANAGEDPROPERTY" ignorePre="true" />
			<dbType type="ENTITYNAME" ignorePre="true" default="true" defaultLength="100" />
		</dbTypes>

		<language name="java">
			<talendToDbTypes>
				<talendType type="id_List">
				    <dbType type="PARTYLIST" default="true" />
				    <dbType type="CALENDARRULES" />
                </talendType>
				<talendType type="id_Boolean">
					<dbType type="BOOLEAN" default="true" />
					<dbType type="MANAGEDPROPERTY" />
				</talendType>
				<talendType type="id_Byte" />
				<talendType type="id_byte[]" />
				<talendType type="id_Character" />
				<talendType type="id_Date">
				    <dbType type="DATETIME" default="true" />
				</talendType>
				<talendType type="id_BigDecimal">
				    <dbType type="DECIMAL" default="true" />
				    <dbType type="MONEY" />
				</talendType>
				<talendType type="id_Double">
				    <dbType type="DOUBLE" default="true" />
				</talendType>
				<talendType type="id_Float" />
				<talendType type="id_Integer">
				    <dbType type="INTEGER" default="true" />
				    <dbType type="PICKLIST" />
				    <dbType type="STATE" />
				    <dbType type="STATUS" />
				</talendType>
				<talendType type="id_Long">
				    <dbType type="BIGINT" default="true" />
				</talendType>
				<talendType type="id_Object" />
				<talendType type="id_Short" />
				<talendType type="id_String">
				    <dbType type="STRING" default="true" />
				    <dbType type="CUSTOMER" />
				    <dbType type="LOOKUP" />
				    <dbType type="MEMO" />
				    <dbType type="OWNER" />
				    <dbType type="UNIQUEIDENTIFIER" />
				    <dbType type="ENTITYNAME" />
				</talendType>
			</talendToDbTypes>
			<dbToTalendTypes>
				<dbType type="BOOLEAN">
					<talendType type="id_Boolean" default="true" />
				</dbType>
				<dbType type="CUSTOMER">
					<talendType type="id_String" default="true" />
				</dbType>
				<dbType type="DATETIME">
					<talendType type="id_Date" default="true" />
				</dbType>
				<dbType type="DECIMAL">
					<talendType type="id_BigDecimal" default="true" />
				</dbType>
				<dbType type="DOUBLE">
					<talendType type="id_Double" default="true" />
				</dbType>
				<dbType type="INTEGER">
					<talendType type="id_Integer" default="true" />
				</dbType>
				<dbType type="LOOKUP">
					<talendType type="id_String" default="true" />
				</dbType>
				<dbType type="MEMO">
					<talendType type="id_String" default="true" />
				</dbType>
				<dbType type="MONEY">
					<talendType type="id_BigDecimal" default="true" />
				</dbType>
				<dbType type="OWNER">
					<talendType type="id_String" default="true" />
				</dbType>
				<dbType type="PARTYLIST">
					<talendType type="id_List" default="true" />
				</dbType>
				<dbType type="PICKLIST">
					<talendType type="id_Integer" default="true" />
				</dbType>
				<dbType type="STATE">
					<talendType type="id_Integer" default="true" />
				</dbType>
				<dbType type="STATUS">
					<talendType type="id_Integer" default="true" />
				</dbType>
				<dbType type="STRING">
					<talendType type="id_String" default="true" />
				</dbType>
				<dbType type="UNIQUEIDENTIFIER">
					<talendType type="id_String" default="true" />
				</dbType>
				<dbType type="CALENDARRULES">
					<talendType type="id_List" default="true" />
				</dbType>
				<!--dbType type="VIRTUAL">
					<talendType type="" default="true" />
				</dbType-->
				<dbType type="BIGINT">
					<talendType type="id_Long" default="true" />
				</dbType>
				<dbType type="MANAGEDPROPERTY">
					<talendType type="id_Boolean" default="true" />
				</dbType>
				<dbType type="ENTITYNAME">
                    <talendType type="id_String" default="true" />
                </dbType>
			</dbToTalendTypes>
		</language>
	</dbms>

</mapping>


text:
layout: post
title: "Road to Ember 3.0 Reaction"
date: 2017-10-03
categories: ember
description: This is my instant reaction to some of the highlights and changes proposed for Ember 3.0
---

Well, nearly 3 years later and here we are again with another reaction for the latest Ember major version release and this one's going to be short and sweet.

I honestly do not have enough positive things to say about this release plan. It is yet another validating reason that firmly solidifies Ember's status as the best frontend framework.

Basically, if your app is running without deprecations right now on an Ember version 2.14 and above then you are 100% set and ready to go for 3.0.

...Yes, it is actually that easy :heart_eyes:

**Highlights:**

- No new public APIs or breaking changes
- No 3.0 targeted deprecations
- New addon will help provide support for Ember 2.x APIs into the 3.x series
- Dropping IE9, IE10, and Phantom JS support
- Improvements and features have been effectively decoupled from the 3.x release — meaning you will see new features landing throughout the transition period

With the JS hype machine cranked up to 11 in recent months and years, seeing this level of planning, preparation, and communication is really just breath of fresh air for the ecosystem as a whole.

Also, be sure to check out the [Ember Status Board](https://emberjs.com/statusboard) for news around upcoming functionality and RFCs landing in the framework.


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

#include "mhook/mhook.h"
#include "timer/timer.h"

#include "search/config.h"
#include "search/search.h"

#include "config.h"
#include "httpd.h"
#include "utils.h"

const char *httpd_on_recv(const char* req, void* arg_)
{
	P_CAST(args, struct searcher_args, arg_);
	const char      *ret = NULL;
	struct query     qry;
	uint32_t         page;
	ranked_results_t srch_res; /* search results */
	struct timer     timer;

#ifdef SEARCHD_LOG_ENABLE
	FILE *log_fh = fopen(SEARCHD_LOG_FILE, "a");

	if (log_fh == NULL) {
		fprintf(stderr, "cannot open %s.\n", SEARCHD_LOG_FILE);
		log_fh = fopen("/dev/null", "a");
	}

	fprintf(log_fh, "JSON query: ");
	fprintf(log_fh, "%s\n", req);
	fflush(log_fh);

	fprintf(log_fh, "relay from: ");
	log_json_qry_ip(log_fh, req);
	fprintf(log_fh, "\n");
#endif

	/* start timer */
	timer_reset(&timer);

	/* parse JSON query into local query structure */
	qry = query_new();
	page = parse_json_qry(req, args->lex, &qry);

	if (page == 0) {
#ifdef SEARCHD_LOG_ENABLE
		fprintf(log_fh, "requested JSON parse error.\n");
#endif
		ret = search_errcode_json(SEARCHD_RET_BAD_QRY_JSON);
		goto reply;

	} else if (qry.len == 0) {
#ifdef SEARCHD_LOG_ENABLE
		fprintf(log_fh, "resulted qry of length zero.\n");
#endif
		ret = search_errcode_json(SEARCHD_RET_EMPTY_QRY);
		goto reply;

	} else if (qry.n_math > MAX_ACCEPTABLE_MATH_KEYWORDS) {
#ifdef SEARCHD_LOG_ENABLE
		fprintf(log_fh, "qry contains too many math keywords.\n");
#endif
		ret = search_errcode_json(SEARCHD_RET_TOO_MANY_MATH_KW);
		goto reply;

	} else if (qry.n_term > MAX_ACCEPTABLE_TERM_KEYWORDS) {
#ifdef SEARCHD_LOG_ENABLE
		fprintf(log_fh, "qry contains too many term keywords.\n");
#endif
		ret = search_errcode_json(SEARCHD_RET_TOO_MANY_TERM_KW);
		goto reply;
	}

#ifdef SEARCHD_LOG_ENABLE
	fprintf(log_fh, "requested page: %u\n", page);
	fprintf(log_fh, "parsed query: \n");
	query_print_to(qry, log_fh);
	fprintf(log_fh, "\n");
	fflush(log_fh);
#endif

	/* search query */
#ifdef SEARCHD_LOG_ENABLE
	fprintf(log_fh, "run query...\n");
	fflush(log_fh);
#endif

	srch_res = indices_run_query(args->indices, &qry);

	/* generate response JSON */
#ifdef SEARCHD_LOG_ENABLE
	fprintf(log_fh, "return results...\n");
	fflush(log_fh);
#endif
	ret = search_results_json(&srch_res, page - 1, args);

	/* free ranked results */
#ifdef SEARCHD_LOG_ENABLE
	fprintf(log_fh, "free results...\n");
	fflush(log_fh);
#endif
	free_ranked_results(&srch_res);

reply:
#ifdef SEARCHD_LOG_ENABLE
	fprintf(log_fh, "delete query...\n");
	fflush(log_fh);
#endif
	query_delete(qry);

#ifdef SEARCHD_LOG_ENABLE
	fprintf(log_fh, "query handled, "
	        "unfree allocs: %ld.\n", mhook_unfree());
	fflush(log_fh);

	fprintf(log_fh, "query handle time cost: %ld msec.\n",
	        timer_tot_msec(&timer));

	fprintf(log_fh, "\n");
	fclose(log_fh);
#endif
	return ret;
}

int main(int argc, char *argv[])
{
	int                   opt;
	char                 *index_path = NULL;
	struct indices        indices;
	unsigned short        cache_sz = SEARCHD_DEFAULT_CACHE_MB;
	unsigned short        port = SEARCHD_DEFAULT_PORT;
	text_lexer            lex = lex_eng_file;
	char                 *dict_path = NULL;
	struct searcher_args  searcher_args;

	/* parse program arguments */
	while ((opt = getopt(argc, argv, "hi:t:p:c:d:")) != -1) {
		switch (opt) {
		case 'h':
			printf("DESCRIPTION:\n");
			printf("search daemon.\n");
			printf("\n");
			printf("USAGE:\n");
			printf("%s -h |"
			       " -i <index path> |"
			       " -p <port> | "
			       " -c <cache size (MB)> | "
			       " -d <dict> "
			       "\n", argv[0]);
			printf("\n");
			goto exit;

		case 'i':
			index_path = strdup(optarg);
			break;

		case 'p':
			sscanf(optarg, "%hu", &port);
			break;

		case 'c':
			sscanf(optarg, "%hu", &cache_sz);
			break;

		case 'd':
			dict_path = strdup(optarg);
			lex = lex_mix_file;
			break;

		default:
			printf("bad argument(s). \n");
			goto exit;
		}
	}

	/* check program arguments */
	if (index_path == NULL) {
		fprintf(stderr, "indices path not specified.\n");
		goto exit;
	}

	/* open text-segment dictionary if needed */
	if (lex == lex_mix_file) {
		printf("opening dictionary...\n");
		if (text_segment_init(dict_path)) {
			fprintf(stderr, "cannot open dict.\n");
			goto exit;
		}
	}

	/* open indices */
	printf("opening index at: `%s' ...\n", index_path);
	if (indices_open(&indices, index_path, INDICES_OPEN_RD)) {
		printf("index open failed.\n");
		goto close;
	}

	/* setup cache */
	printf("setup cache size: %hu MB\n", cache_sz);
	indices_cache(&indices, cache_sz MB);

	/* run httpd */
	printf("listen on port %hu\n", port);

	searcher_args.indices = &indices;
	searcher_args.lex     = lex;
	httpd_run(port, &httpd_on_recv, &searcher_args);

close:
	/* close indices */
	printf("closing index...\n");
	indices_close(&indices);

	/* close text-segment dictionary if opened */
	if (lex == lex_mix_file) {
		printf("closing dictionary...\n");
		text_segment_free();
	}

exit:
	/*
	 * free program arguments
	 */
	free(index_path);
	free(dict_path);

	mhook_print_unfree();
	return 0;
}


text:
echo "this is a network hack for generic/debianXX boxes.."
sudo sed -i "/dns-nameserver/d" /etc/network/interfaces
sudo sed -i "s/#DNSSEC=.*/DNSSEC=no/g" /etc/systemd/resolved.conf
# The IP below is that of libvirt network gateway
sudo bash -c 'echo "nameserver 10.248.2.1" > /etc/resolvconf/resolv.conf.d/original'
sudo bash -c 'echo "nameserver 10.248.2.1" > /run/resolvconf/resolv.conf'
sudo bash -c 'echo "nameserver 10.248.2.1" > /etc/resolv.conf'


text:
import React from 'react'
import { mount } from 'enzyme'
import { EditSourceControls } from '../EditSourceControls'

describe('EditSourceControls', () => {
  let props

  beforeEach(() => {
    props = {
      onApply: jest.fn()
    }
  })

  it('renders', () => {
    const component = mount(<EditSourceControls {...props}/>)
    expect(component.exists()).toBe(true)
  })

  it('updates the state as input value changes', () => {
    const component = mount(<EditSourceControls {...props}/>)
    const titleInput = component.find('input[name="title"]')
    titleInput.simulate('change', { target: { value: 'Jacobin' }})

    const urlInput = component.find('input[name="url"]')
    urlInput.simulate('change', { target: { value: 'jacobinmag.com' }})

    expect(component.state('title')).toBe('Jacobin')
    expect(component.state('url')).toBe('jacobinmag.com')
  })

  it('calls onApply when apply is clicked', () => {
    const component = mount(<EditSourceControls {...props}/>)
    const button = component.find('Button')
    button.simulate('click')

    expect(props.onApply.mock.calls[0]).toBeTruthy()
  })
})


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>TreeDataView.js Example</title>
  <link rel="stylesheet" href="src/fonts/awesome.css">
  <link href='https://fonts.googleapis.com/css?family=Signika:400,600,700' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="src/css/TreeDataView.css">

TreeDataView.js1.0

Default

Show code

var tree = new TreeDataView({
  append: $('#tree-example-1')
}, data);
tree.render();

Disabled Node

Show code

// Node have field ['_node-disabled']
var tree = new TreeDataView({
  append: $('#tree-example-4'),
  openLevel: 2
}, data);
tree.render();

Sliding Duration

Show code

var tree = new TreeDataView({
  append: $('#tree-example-7'),
  slidingDuration: 400
}, data);
tree.render();

Custom Template

Show code

var tree10 = new TreeDataView({
  append: $('#tree-example-10'),
  template: '<span><i style="margin-right: 10px;" class="fa fa-child"></i>' +
  ' {{ country }}' +
  ' {{ city.title }}' +
  ' {{ city.population }}</span>'
}, dataCountry);
tree10.render();

Default theme

Show code

var tree = new TreeDataView({
  append: $('#tree-example-13'),
}, data);
tree.render();

Open two level

Show code

var tree = new TreeDataView({
  append: $('#tree-example-2'),
  openLevel: 2
}, data);
tree.render();

Selected Node

Show code

// Node have field ['_node-selected']
var tree = new TreeDataView({
  append: $('#tree-example-5'),
}, data);
tree.render();

Count nodes

Show code

var tree8 = new TreeDataView({
  append: $('#tree-example-8'),
  count: true
}, data);
tree8.render();

Events (print console)

Show code

var tree11 = new TreeDataView({
  append: $('#tree-example-11'),
}, data);
tree11.render();

Dark theme

Show code

var tree14 = new TreeDataView({
  append: $('#tree-example-14'),
  count: true
  theme: 'dark'
}, data);
tree14.render();

Open all

Show code

var tree = new TreeDataView({
  append: $('#tree-example-3'),
  openLevel: 'all'
}, data);
tree.render();

Custom icons

Show code

var tree = new TreeDataView({
  append: $('#tree-example-6'),
  iconClasses: {
    open: 'fa-plus-circle',
    close: 'fa-minus-circle'
  }
}, data);
tree.render();

Count nodes callback

Show code

var tree9 = new TreeDataView({
  append: $('#tree-example-9'),
  count: true,
  countCallback: function(count) {
  if(count > 10) {
   return '10+';
  }
  else if(count > 5) {
   return '5+';
  }
  return count;
  },
}, data);
tree9.render();

Get data (print console)

Show code

var tree12 = new TreeDataView({
 append: $('#tree-example-12'),
}, data);
tree12.render();
console.info(tree12.getNodes(3, 'object'));
console.info(tree12.getNodes(3, 'html'));
console.info(tree12.getNodes(3, 'json'));

Color theme

Show code

var tree15 = new TreeDataView({
  append: $('#tree-example-15'),
  count: true,
  theme: 'color'
}, data);
tree15.render();

Support format - Object, Array, JSON

Show code

  // Object
  var data = {
    title: 'Parent',
    nodes: [
     {title: 'Children'},
     {title: 'Children'}
    ]
  };

  // Array
  var data = [
    {title: 'Parent'},
    {title: 'Parent}
  ];

  // JSON
  var data = '{"title":"Parent","nodes":[{"title":"Children"},{"title":"Children"}]}';

  new TreeDataView({}, data);


text:
module Microscope
  VERSION = "0.0.1"
end


text:
"use strict";
/*
 Copyright 2013 jQuery Foundation and other contributors
 Released under the MIT license.
 http://jquery.org/license
*/
define(["ojs/ojcore", "jquery", "ojs/ojeditablevalue"], function($oj$$70$$) {
  (function() {
    $oj$$70$$.$__registerWidget$("oj.ojSwitch", $.oj.editableValue, {version:"1.1.0", defaultElement:"\x3cinput\x3e", widgetEventPrefix:"oj", options:{disabled:!1, readOnly:!1, required:!1, title:"", value:!1}, refresh:function() {
      this._super();
      this.$_setup$();
    }, widget:function() {
      return this.$_element2$;
    }, getNodeBySubId:function($locator$$56_subId$$60$$) {
      var $node$$125$$, $rootElement$$19$$ = this.widget();
      $node$$125$$ = null == $locator$$56_subId$$60$$ || null == $locator$$56_subId$$60$$.subId ? $rootElement$$19$$ : null;
      return $node$$125$$ || ($locator$$56_subId$$60$$ = $locator$$56_subId$$60$$.subId, "oj-switch-thumb" !== $locator$$56_subId$$60$$ && "oj-switch-track" !== $locator$$56_subId$$60$$) ? $node$$125$$ || null : $rootElement$$19$$.find("." + $locator$$56_subId$$60$$)[0];
    }, getSubIdByNode:function($node$$126$$) {
      var $originalId$$ = $(this.element).attr("id"), $nodeId$$1$$, $result$$80$$ = null;
      null != $node$$126$$ && ($($node$$126$$).hasClass("oj-switch-track") || $($node$$126$$).hasClass("oj-switch-thumb")) && ($nodeId$$1$$ = $($node$$126$$).parents("div.oj-switch").find("input.oj-component-initnode").attr("id"), $originalId$$ === $nodeId$$1$$ && $($node$$126$$).hasClass("oj-switch-track") ? $result$$80$$ = {subId:"oj-switch-track"} : $originalId$$ === $nodeId$$1$$ && $($node$$126$$).hasClass("oj-switch-thumb") && ($result$$80$$ = {subId:"oj-switch-thumb"}));
      return $result$$80$$;
    }, $_BUNDLE_KEY$:{$_SWITCH_OFF$:"SwitchOFF", $_SWITCH_ON$:"SwitchON"}, $_InitOptions$:function($originalDefaults$$18$$, $constructorOptions$$20$$) {
      var $val$$69$$;
      this._super($originalDefaults$$18$$, $constructorOptions$$20$$);
      $oj$$70$$.$EditableValueUtils$.$initializeOptionsFromDom$([{$attribute$:"disabled", $validateOption$:!0}, {$attribute$:"readonly", option:"readOnly", $validateOption$:!0}, {$attribute$:"required", $validateOption$:!1, $coerceDomValue$:function() {
        return!1;
      }}, {$attribute$:"checked", option:"value", $validateOption$:!1, $coerceDomValue$:function($domValue$$3$$) {
        return $domValue$$3$$ ? !0 : !1;
      }}, {$attribute$:"title"}], $constructorOptions$$20$$, this);
      $val$$69$$ = this.option("value");
      this.option({required:!1, value:!!$val$$69$$}, {_context:{$writeback$:!0, $internalSet$:!0}});
    }, _ComponentCreate:function() {
      this._super();
      if (!this.element.is("input")) {
        throw Error("ojSwitch can be bound to INPUT only.");
      }
      this.$_inputElementOriginalDisplay$ = this.element.css("display");
      this.element.css("display", "none").attr("type", "checkbox").attr("checked", this.option("value")).attr("tabindex", "-1").attr("disabled", this.option("disabled")).attr("readonly", this.option("readOnly"));
      this.$_element2$ = this.element.wrap("\x3cdiv\x3e\x3c/div\x3e").parent().addClass("oj-switch oj-component oj-form-control");
      this.$_element2$.append("\x3cdiv class\x3d'oj-switch-container'\x3e\x3cdiv class\x3d'oj-switch-track'\x3e\x3cdiv class\x3d'oj-switch-thumb' tabIndex\x3d'0'\x3e\x3c/div\x3e\x3c/div\x3e\x3c/div\x3e");
      this.$switchThumb$ = this.$_element2$.find(".oj-switch-thumb");
      this.$switchThumb$.attr("role", "switch checkbox");
      this.$_setAriaLabel$(this.element, this.$switchThumb$);
      this.$_setup$();
    }, $_setAriaLabel$:function($elem$$161$$, $target$$104$$) {
      var $id$$56_switchLabel$$ = $elem$$161$$.prop("id"), $ariaLabelledBy$$ = $elem$$161$$.attr("aria-labelledby"), $ariaLabel$$ = $elem$$161$$.attr("aria-label");
      $ariaLabel$$ ? $target$$104$$.attr("aria-label", $ariaLabel$$) : $ariaLabelledBy$$ ? $target$$104$$.attr("aria-labelledby", $ariaLabelledBy$$) : $id$$56_switchLabel$$ && ($id$$56_switchLabel$$ = $("label[for\x3d'" + $id$$56_switchLabel$$ + "']")) && ($id$$56_switchLabel$$.attr("id") ? $target$$104$$.attr("aria-labelledby", $id$$56_switchLabel$$.attr("id")) : $target$$104$$.attr("aria-label", $($id$$56_switchLabel$$).text()));
    }, $_setup$:function() {
      var $rootElement$$20$$ = $(this.widget()), $thumbTitle$$ = this.option("title");
      this.$_setupEvents$();
      if (void 0 !== $rootElement$$20$$) {
        this.element.attr("checked", this.option("value"));
        $rootElement$$20$$.removeClass("oj-disabled oj-read-only oj-selected oj-hover oj-active");
        $(this.$switchThumb$).attr("tabindex", "0");
        $(this.$switchThumb$).html("");
        if (this.option("disabled") || this.option("readOnly")) {
          this.option("disabled") ? $rootElement$$20$$.addClass("oj-disabled") : ($rootElement$$20$$.addClass("oj-read-only"), $(this.$switchThumb$).html(this.$_setReadOnlyValue$())), $(this.$switchThumb$).removeAttr("tabindex");
        }
        this.option("value") && $rootElement$$20$$.addClass("oj-selected");
        void 0 !== $thumbTitle$$ && $(this.$switchThumb$).attr("title", $thumbTitle$$);
        $(this.$switchThumb$).attr("aria-checked", this.option("value"));
        $(this.$switchThumb$).removeAttr("aria-disabled");
        $rootElement$$20$$.removeAttr("aria-disabled");
        this.$_CanSetValue$() || $(this.$switchThumb$).attr("aria-disabled", "true");
      }
    }, $_setReadOnlyValue$:function() {
      var $strReturn$$ = this.$_BUNDLE_KEY$.$_SWITCH_OFF$;
      this.option("value") && ($strReturn$$ = this.$_BUNDLE_KEY$.$_SWITCH_ON$);
      return this.$getTranslatedString$($strReturn$$);
    }, $_setupEvents$:function() {
      this._off(this.$_element2$, "keydown keyup mousedown mouseup mouseleave mouseenter touchstart");
      this.$_CanSetValue$() && (this._on(this.$_element2$, this.$_switchEvents$), this._hoverable(this.$_element2$));
      this._focusable(this.$_element2$);
    }, $_switchEvents$:{keydown:function($event$$627$$) {
      if ($event$$627$$.which === $.ui.keyCode.ENTER || $event$$627$$.which === $.ui.keyCode.SPACE) {
        $($event$$627$$.currentTarget).addClass("oj-active"), $event$$627$$.preventDefault();
      }
    }, keyup:function($event$$628$$) {
      $event$$628$$.which !== $.ui.keyCode.ENTER && $event$$628$$.which !== $.ui.keyCode.SPACE || this.$_SetValue$(!this.option("value"), $event$$628$$);
    }, mousedown:function($event$$629$$) {
      1 === $event$$629$$.which && $($event$$629$$.currentTarget).addClass("oj-active");
    }, mouseup:function($event$$630$$) {
      1 === $event$$630$$.which && this.$_SetValue$(!this.option("value"), $event$$630$$);
    }, mouseleave:function($event$$631$$) {
      1 === $event$$631$$.which && $($event$$631$$.currentTarget).removeClass("oj-active");
    }, mouseenter:function($event$$632$$) {
      1 === $event$$632$$.which && $($event$$632$$.currentTarget).addClass("oj-active");
    }, $touchstart$:function($event$$633$$) {
      this.$_SetValue$(!this.option("value"), $event$$633$$);
      $event$$633$$.preventDefault();
    }}, _GetDefaultStyleClass:function() {
      return "oj-switch";
    }, $_setSwitchRole$:function() {
      return "switch checkbox";
    }, _destroy:function() {
      this.$_element2$.find(".oj-switch-track").remove();
      $oj$$70$$.$DomUtils$.unwrap(this.element);
      this.$_RestoreAttributes$(this.element);
      return this._super();
    }, $_GetContentElement$:function() {
      return this.$_element2$;
    }, _setOption:function($key$$182$$, $coercedValue$$2_value$$313$$, $flags$$47$$) {
      switch($key$$182$$) {
        case "disabled":
        ;
        case "readOnly":
        ;
        case "value":
          $coercedValue$$2_value$$313$$ = !!$coercedValue$$2_value$$313$$;
          break;
        case "required":
          $coercedValue$$2_value$$313$$ = !1;
          break;
      }
      this._super($key$$182$$, $coercedValue$$2_value$$313$$, $flags$$47$$);
      this.$_setup$();
    }});
  })();
});


text:
package fnf

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// FlowsItem is a nested struct in fnf response
type FlowsItem struct {
	Name                    string `json:"Name" xml:"Name"`
	Description             string `json:"Description" xml:"Description"`
	Definition              string `json:"Definition" xml:"Definition"`
	Id                      string `json:"Id" xml:"Id"`
	Type                    string `json:"Type" xml:"Type"`
	RoleArn                 string `json:"RoleArn" xml:"RoleArn"`
	CreatedTime             string `json:"CreatedTime" xml:"CreatedTime"`
	LastModifiedTime        string `json:"LastModifiedTime" xml:"LastModifiedTime"`
	ExternalStorageLocation string `json:"ExternalStorageLocation" xml:"ExternalStorageLocation"`
}


text:
define([
	'backbone',
	'hbs!tmpl/item/jui-floating-scroll-indicators-view',
    'TweenMax',
    'gsap-scrollto-plugin'

],
function( Backbone, JuiFloatingScrollIndicatorsView  ) {
    'use strict';

	/* Return a ItemView class definition */
	return Backbone.Marionette.ItemView.extend({

		initialize: function() {
		},

    	template: JuiFloatingScrollIndicatorsView,

    	/* ui selector cache */
    	ui: {},

		/* Ui events hash */
		events: {},

		/* on show callback */
		onShow: function() {
            var indTestElm = $('.floating-scroll-indicators-test')
                .juiFloatingScrollIndicators({ui: {scrollableElm: $(window)}});
        }
	});

});


text:
require 'omniauth-oauth2'

module OmniAuth
    module Strategies
        class WanliuId < OmniAuth::Strategies::OAuth2

            # option :iframe, true

            server_addr = OmniAuth::Wanliu.config["provider_url"]

            # This is where you pass the options you would pass when
            # initializing your consumer from the OAuth gem.
            option :client_options, {
                :site => server_addr,
                :authorize_url => "#{server_addr}/auth/wanliu_id/authorize",
                :access_token_url => "#{server_addr}/auth/wanliu_id/access_token"
            }

            # These are called after authentication has succeeded. If
            # possible, you should try to set the UID without making
            # additional calls (if the user id is returned with the token
            # or as a URI parameter). This may not be possible with all
            # providers.
            uid{ raw_info['id'] }

            info do
            {
              :name => raw_info["info"]['name'],
              :email => raw_info["info"]['email']
            }
            end

            extra do
            {
              'raw_info' => raw_info
            }
            end

            def raw_info
                @raw_info ||= access_token.get("/auth/wanliu_id/user.json?oauth_token=#{access_token.token}").parsed
            end
        end
    end
end


text:
package clang;
import com.sun.jna.Structure;
/**
 * native declaration : src/main/c/clang-c/Index.h

 * This file was autogenerated by JNAerator,

 * a tool written by Olivier Chafik that uses a few opensource projects..

 * For help, please visit NativeLibs4Java , Rococoa, or JNA.
 */
public class CXIdxIBOutletCollectionAttrInfo extends Structure {
	/// C type : const CXIdxAttrInfo*
	public clang.CXIdxAttrInfo.ByReference attrInfo;
	/// C type : const CXIdxEntityInfo*
	public clang.CXIdxEntityInfo.ByReference objcClass;
	/// C type : CXCursor
	public CXCursor classCursor;
	/// C type : CXIdxLoc
	public CXIdxLoc classLoc;
	public CXIdxIBOutletCollectionAttrInfo() {
		super();
		initFieldOrder();
	}
	protected void initFieldOrder() {
		setFieldOrder(new String[]{"attrInfo", "objcClass", "classCursor", "classLoc"});
	}
	/**
	 * @param attrInfo C type : const CXIdxAttrInfo*

	 * @param objcClass C type : const CXIdxEntityInfo*

	 * @param classCursor C type : CXCursor

	 * @param classLoc C type : CXIdxLoc
	 */
	public CXIdxIBOutletCollectionAttrInfo(clang.CXIdxAttrInfo.ByReference attrInfo, clang.CXIdxEntityInfo.ByReference objcClass, CXCursor classCursor, CXIdxLoc classLoc) {
		super();
		this.attrInfo = attrInfo;
		this.objcClass = objcClass;
		this.classCursor = classCursor;
		this.classLoc = classLoc;
		initFieldOrder();
	}
	public static class ByReference extends CXIdxIBOutletCollectionAttrInfo implements Structure.ByReference {

	};
	public static class ByValue extends CXIdxIBOutletCollectionAttrInfo implements Structure.ByValue {

	};
}


text:
<?php

namespace Drupal\Core\Form;

/**
 * Provides an interface for a Form that has a base form ID.
 *
 * This will become the $form_state->getBaseInfo()['base_form_id'] used to
 * generate the name of hook_form_BASE_FORM_ID_alter().
 */
interface BaseFormIdInterface extends FormInterface {

  /**
   * Returns a string identifying the base form.
   *
   * @return string|null
   *   The string identifying the base form or NULL if this is not a base form.
   */
  public function getBaseFormId();

}


text:
(function () {
  'use strict';

  // Authentication service for user variables

  angular
    .module('users.services')
    .factory('Authentication', Authentication);

  Authentication.$inject = ['$window'];

  function Authentication($window) {
    var auth = {
      user: $window.user
    };

    return auth;
  }
}());


text:
import 'mocha'
import { expect } from 'chai'
import {spy} from 'sinon'
import { LocalCache } from './local-cache'

describe('it saves values in memory', () => {
  let localCache

  before(() => {
    localCache = new LocalCache()
  })

  it('has created the Local Cache', async () => {
    await localCache.whenReady()
  })

  it('sets a value in the cache', (done) => {
    const successCallback = spy()
    localCache.set('firstname', 1, 'Wolfram', successCallback)
    setTimeout(() => {
      expect(successCallback).to.have.callCount(1)
      expect(successCallback).to.have.been.calledWith(null)
      done()
    }, 1)
  })

  it('retrieves an existing value from the cache', (done) => {
    const successCallback = spy()
    localCache.get('firstname', successCallback)
    setTimeout(() => {
      expect(successCallback).to.have.callCount(1)
      expect(successCallback).to.have.been.calledWith(null, 1, 'Wolfram')
      done()
    }, 1)
  })

  it('deletes a value from the cache', (done) => {
    const successCallback = spy()
    localCache.delete('firstname', successCallback)
    setTimeout(() => {
      expect(successCallback).to.have.callCount(1)
      expect(successCallback).to.have.been.calledWith(null)
      done()
    }, 1)
  })

  it('tries to retrieve a non-existing value from the cache', (done) => {
    const successCallback = spy()
    localCache.get('firstname', successCallback)
    setTimeout(() => {
      expect(successCallback).to.have.callCount(1)
      expect(successCallback).to.have.been.calledWith(null, -1, null)
      done()
    }, 1)
  })
})


text:
using System;
using System.Collections.Generic;
using System.Linq;
using d60.Cirqus.Aggregates;
using d60.Cirqus.Commands;
using d60.Cirqus.Config;
using d60.Cirqus.Events;
using d60.Cirqus.Extensions;
using d60.Cirqus.MongoDb.Events;
using d60.Cirqus.Serialization;
using d60.Cirqus.Snapshotting;
using d60.Cirqus.Tests.MongoDb;
using NUnit.Framework;

namespace d60.Cirqus.Tests.Snapshotting
{
    [TestFixture]
    public class TestCachingAggregateRootRepositoryDecorator : FixtureBase
    {
        CachingAggregateRootRepositoryDecorator _cachingAggregateRootRepository;
        MongoDbEventStore _eventStore;
        JsonDomainEventSerializer _domainEventSerializer;
        DefaultAggregateRootRepository _realAggregateRootRepository;
        DefaultDomainTypeNameMapper _domainTypeNameMapper;

        protected override void DoSetUp()
        {
            _eventStore = new MongoDbEventStore(MongoHelper.InitializeTestDatabase(), "Events");
            _domainEventSerializer = new JsonDomainEventSerializer();

            _domainTypeNameMapper = new DefaultDomainTypeNameMapper();

            var snapshotCache = new InMemorySnapshotCache();

            _realAggregateRootRepository = new DefaultAggregateRootRepository(_eventStore, _domainEventSerializer, _domainTypeNameMapper);
            _cachingAggregateRootRepository = new CachingAggregateRootRepositoryDecorator(_realAggregateRootRepository, snapshotCache, _eventStore, _domainEventSerializer);
        }

        [TestCase(1000, true)]
        [TestCase(1000, false)]
        public void CheckHydrationPerformance(int historyLength, bool useCaching)
        {
            var aggregateRootId = Guid.NewGuid();

            GeneratePrettyLongHistory(aggregateRootId, historyLength);

            TakeTime("Load instance", () =>
            {
                100.Times(() =>
                {
                    var realUnitOfWork = new RealUnitOfWork(_cachingAggregateRootRepository, _domainTypeNameMapper);

                    if (useCaching)
                    {
                        _cachingAggregateRootRepository.Get<Root>(aggregateRootId.ToString(), realUnitOfWork);
                    }
                    else
                    {
                        _realAggregateRootRepository.Get<Root>(aggregateRootId.ToString(), realUnitOfWork);
                    }
                });
            });
        }

        void GeneratePrettyLongHistory(Guid aggregateRootId, int howLong)
        {
            var eventsToSave = Enumerable.Range(0, howLong)
                .Select(i => CreateEvent(aggregateRootId, i))
                .Select(e => _domainEventSerializer.Serialize(e))
                .ToList();

            var random = new Random();

            foreach (var partition in eventsToSave.Batch(100))
            {
                var batchSize = random.Next(10)+1;

                foreach (var batch in partition.Batch(batchSize))
                {
                    _eventStore.Save(Guid.NewGuid(), batch);
                }
            }
        }

        DomainEvent CreateEvent(Guid aggregateRootId, int sequenceNumber)
        {
            return new Event
            {
                Meta =
                {
                    {DomainEvent.MetadataKeys.AggregateRootId, aggregateRootId.ToString()},
                    {DomainEvent.MetadataKeys.SequenceNumber, sequenceNumber.ToString()},
                    {DomainEvent.MetadataKeys.GlobalSequenceNumber, sequenceNumber.ToString()},
                    {DomainEvent.MetadataKeys.Owner, _domainTypeNameMapper.GetName(typeof(Root))},
                    {DomainEvent.MetadataKeys.Type, _domainTypeNameMapper.GetName(typeof(Event))},
                }
            };
        }

        class Root : AggregateRoot, IEmit<Event>
        {
            public int NumberOfProcessedEvents { get; private set; }

            public void Apply(Event e)
            {
                NumberOfProcessedEvents++;
            }
        }

        class Event : DomainEvent<Root> { }
    }
}


text:
This is a simple visualization of the world map using HighCharts. It is a static page with no backend and the dark color represents the countries that I have visited. It allows one to zoom within US and India and highlights the visited states. As I have never lived longterm in any other country I didn't add the ability to zoom into them.

This was purely a fun project for me in trying to read more about data visualization and also thinking more about my future vacations.

# Future Ideas

- Convert into a webapp or embeddable widget
- Add more information using timelines and markers for cities that have been visited

# License
MIT


text:
/**
 * @name as
 * @description Checks if given object can be consumed as an instance of given type
 * @example
 *  as(obj, type)
 * @params
 *  obj: object - object that needs to be checked
 *  type: string OR type - type to be checked for, it can be following:
 *                         > expected native javascript data types like 'string', 'number', 'function', 'array', 'date', etc.
 *                         > 'function' - any function, cfunction' - constructor function and 'afunction - arrow function
 *                         > any 'flair' object or type
 *                         > inbuilt flair object types like 'class', 'struct', 'enum', etc.
 *                         > custom flair object instance types which are checked in following order:
 *                           >> for class instances:
 *                              isInstanceOf given as type
 *                              isImplements given as interface
 *                              isMixed given as mixin
 *                           >> for struct instances:
 *                              isInstance of given as struct type
 * @returns {object} - if can be used as specified type, return same object, else null
 */
const _as = (obj, type) => {
    // NOTE: in all 'check' type functions, Args() is not to be used, as Args use them itself

    // obj may be undefined or null or false, so don't check for validation of that here
    if (type[meta]) { type = type[meta].name || type[meta].Type.getName(); } // since it can be a type as well
    if (_typeOf(type) !== 'string') { throw _Exception.InvalidArgument('type', _as); }

    if (_is(obj, type)) { return obj; }
    return null;
};

// attach to flair
a2f('as', _as);