text:
import {ActivityIframeView} from '../ui/activity-iframe-view';
import {SubscriptionFlows} from '../api/subscriptions';
import {feArgs, feUrl} from './services';
import {isCancelError} from '../utils/errors';

export class LoginPromptApi {
  /**
   * @param {!./deps.DepsDef} deps
   */
  constructor(deps) {
    /** @private @const {!./deps.DepsDef} */
    this.deps_ = deps;

    /** @private @const {!Window} */
    this.win_ = deps.win();

    /** @private @const {!../components/activities.ActivityPorts} */
    this.activityPorts_ = deps.activities();

    /** @private @const {!../components/dialog-manager.DialogManager} */
    this.dialogManager_ = deps.dialogManager();

    /** @private {?Promise} */
    this.openViewPromise_ = null;

    /** @private @const {!ActivityIframeView} */
    this.activityIframeView_ = new ActivityIframeView(
      this.win_,
      this.activityPorts_,
      feUrl('/loginiframe'),
      feArgs({
        publicationId: deps.pageConfig().getPublicationId(),
        productId: deps.pageConfig().getProductId(),
        // First ask the user if they want us to log them in.
        userConsent: true,
      }),
      /* shouldFadeBody */ true
    );
  }

  /**
   * Prompts the user to login.
   * @return {!Promise}
   */
  start() {
    this.deps_
      .callbacks()
      .triggerFlowStarted(SubscriptionFlows.SHOW_LOGIN_PROMPT);

    this.openViewPromise_ = this.dialogManager_.openView(
      this.activityIframeView_
    );

    return this.activityIframeView_.acceptResult().then(
      () => {
        // The consent part is complete.
        this.dialogManager_.completeView(this.activityIframeView_);
      },
      (reason) => {
        if (isCancelError(reason)) {
          this.deps_
            .callbacks()
            .triggerFlowCanceled(SubscriptionFlows.SHOW_LOGIN_PROMPT);
        } else {
          this.dialogManager_.completeView(this.activityIframeView_);
        }
        throw reason;
      }
    );
  }
}


text:
from PIL import Image
from PIL import ImageOps
import re
import os

class EPDError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)

class EPD(object):

    """EPD E-Ink interface

to use:
  from EPD import EPD

  epd = EPD([path='/path/to/epd'], [auto=boolean])

  image = Image.new('1', epd.size, 0)
  # draw on image
  epd.clear()         # clear the panel
  epd.display(image)  # tranfer image data
  epd.update()        # refresh the panel image - not deeed if auto=true
"""

    PANEL_RE = re.compile('^([A-Za-z]+)\s+(\d+\.\d+)\s+(\d+)x(\d+)\s+COG\s+(\d+)\s+FILM\s+(\d+)\s*$', flags=0)

    def __init__(self, *args, **kwargs):
        self._epd_path = '/dev/epd'
        self._width = 200
        self._height = 96
        self._panel = 'EPD 2.0'
        self._cog = 0
        self._film = 0
        self._auto = False

        if len(args) > 0:
            self._epd_path = args[0]
        elif 'epd' in kwargs:
            self._epd_path = kwargs['epd']

        if ('auto' in kwargs) and kwargs['auto']:
            self._auto = True

        with open(os.path.join(self._epd_path, 'version')) as f:
            self._version = f.readline().rstrip('\n')

        with open(os.path.join(self._epd_path, 'panel')) as f:
            line = f.readline().rstrip('\n')
            m = self.PANEL_RE.match(line)
            if None == m:
                raise EPDError('invalid panel string')
            self._panel = m.group(1) + ' ' + m.group(2)
            self._width = int(m.group(3))
            self._height = int(m.group(4))
            self._cog = int(m.group(5))
            self._film = int(m.group(6))

        if self._width < 1 or self._height < 1:
            raise EPDError('invalid panel geometry')

    @property
    def size(self):
        return (self._width, self._height)

    @property
    def width(self):
        return self._width

    @property
    def height(self):
        return self._height

    @property
    def panel(self):
        return self._panel

    @property
    def version(self):
        return self._version

    @property
    def cog(self):
        return self._cog

    @property
    def film(self):
        return self._film

    @property
    def auto(self):
        return self._auto

    @auto.setter
    def auto(self, flag):
        if flag:
            self._auto = True
        else:
            self._auto = False

    def display(self, image):

        # attempt grayscale conversion, ath then to single bit
        # better to do this before callin this if the image is to
        # be dispayed several times
        if image.mode != "1":
            image = ImageOps.grayscale(image).convert("1", dither=Image.FLOYDSTEINBERG)

        if image.mode != "1":
            raise EPDError('only single bit images are supported')

        if image.size != self.size:
            raise EPDError('image size mismatch')

        with open(os.path.join(self._epd_path, 'LE', 'display_inverse'), 'r+b') as f:
            f.write(image.tobytes())

        if self.auto:
            self.update()

    def update(self):
        self._command('U')

    def partial_update(self):
        self._command('P')

    def clear(self):
        self._command('C')

    def _command(self, c):
        with open(os.path.join(self._epd_path, 'command'), 'wb') as f:
            f.write(bytes(c, 'UTF-8'))

redpajama_set_name: RedPajamaGithub


text:
/*
new_handler.cpp

*/
/*
Copyright © 2017 Far Group
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// BUGBUG
#include "platform.headers.hpp"

// Self:
#include "new_handler.hpp"

// Internal:
#include "farversion.hpp"

// Platform:

// Common:
#include "common/scope_exit.hpp"

// External:

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

static new_handler* NewHandler;

namespace
{
	enum size
	{
		X = 80,
		Y = 25
	};
}

new_handler::new_handler():
	m_BufferSize{ X, Y },
	m_Screen(CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, CONSOLE_TEXTMODE_BUFFER, nullptr))
{
	if (!m_Screen)
		return;

	const COORD BufferSize{ X, Y };

	const SMALL_RECT WindowInfo{ 0, 0, X - 1, Y - 1 };
	if (!SetConsoleWindowInfo(m_Screen.native_handle(), true, &WindowInfo))
		return;

	if (!SetConsoleScreenBufferSize(m_Screen.native_handle(), BufferSize))
		return;

	const auto WhiteOnBlue = 0x9F;
	if (!SetConsoleTextAttribute(m_Screen.native_handle(), WhiteOnBlue))
		return;

	DWORD AttrWritten;
	if (!FillConsoleOutputAttribute(m_Screen.native_handle(), WhiteOnBlue, BufferSize.X * BufferSize.Y, { 0, 0 }, &AttrWritten))
		return;

	const CONSOLE_CURSOR_INFO cci{ 1 };
	if (!SetConsoleCursorInfo(m_Screen.native_handle(), &cci))
		return;

	const string_view Strings[]
	{
		build::version_string(),
		{},
		L"Not enough memory is available to complete this operation."sv,
		L"Press Enter to retry or Esc to continue..."sv
	};

	const auto Write = [this](const string_view Str, size_t Y)
	{
		SetConsoleCursorPosition(m_Screen.native_handle(), { static_cast<short>((m_BufferSize.X - Str.size()) / 2), static_cast<short>(Y) });
		DWORD CharWritten;
		return WriteConsole(m_Screen.native_handle(), Str.data(), static_cast<DWORD>(Str.size()), &CharWritten, nullptr) && CharWritten == Str.size();
	};

	auto InitialY = (m_BufferSize.Y - std::size(Strings)) / 2;
	for (const auto& Str : Strings)
	{
		if (!Write(Str, InitialY++))
			return;
	}

	NewHandler = this;
	m_OldHandler = std::set_new_handler(invoke_new_handler);
}

new_handler::~new_handler()
{
	if (!NewHandler)
		return;

	std::set_new_handler(m_OldHandler);
	NewHandler = nullptr;
}

bool new_handler::retry() const
{
	const auto CurrentBuffer = GetStdHandle(STD_OUTPUT_HANDLE);
	if (!SetConsoleActiveScreenBuffer(m_Screen.native_handle()))
		return false;

	SCOPE_EXIT { SetConsoleActiveScreenBuffer(CurrentBuffer); };

	INPUT_RECORD ir{};
	const auto& KeyEvent = ir.Event.KeyEvent;

	do
	{
		DWORD Read;
		if (!ReadConsoleInput(GetStdHandle(STD_INPUT_HANDLE), &ir, 1, &Read) || Read != 1)
			return false;
	}
	while (!(ir.EventType == KEY_EVENT && !KeyEvent.bKeyDown && (KeyEvent.wVirtualKeyCode == VK_RETURN || KeyEvent.wVirtualKeyCode == VK_ESCAPE)));

	return KeyEvent.wVirtualKeyCode != VK_ESCAPE;
}

void invoke_new_handler()
{
	if (!NewHandler || !NewHandler->retry())
		throw std::bad_alloc{};
}


text:
package org.deidentifier.arx.gui.view.impl.common.table;

import org.eclipse.nebula.widgets.nattable.config.AbstractRegistryConfiguration;

/**
 * Table style wrapper
 * @author Fabian Prasser
 *
 */
public abstract class CTStyleConfiguration extends AbstractRegistryConfiguration implements CTComponent {

    /**  Configuration */
    private final CTConfiguration config;

    /**
     * Creates a new instance
     * @param config
     */
    public CTStyleConfiguration(CTConfiguration config){
        this.config = config;
    }

    @Override
    public CTConfiguration getConfig() {
        return config;
    }
}


text:
package edu.columbia.tjw.item.data;

import edu.columbia.tjw.item.ItemRegressor;
import edu.columbia.tjw.item.ItemStatus;
import edu.columbia.tjw.item.util.EnumFamily;

/**
 * @param <S> The Status type
 * @param <R> The regressor type
 * @author tyler
 */
public interface ItemStatusGrid<S extends ItemStatus<S>, R extends ItemRegressor<R>> extends ItemGrid<R>
{

    public EnumFamily<S> getStatusFamily();

    public int getStatus(final int index_);

    public int getNextStatus(final int index_);

    public boolean hasNextStatus(final int index_);

}


text:
package com.haulmont.timesheets.gui.timeentry;

import com.haulmont.cuba.core.entity.Entity;
import com.haulmont.cuba.gui.WindowManager;
import com.haulmont.cuba.gui.components.AbstractLookup;
import com.haulmont.cuba.gui.components.GroupTable;
import com.haulmont.cuba.gui.components.Table;
import com.haulmont.cuba.gui.components.Window;
import com.haulmont.cuba.gui.components.actions.CreateAction;
import com.haulmont.cuba.gui.components.actions.EditAction;
import com.haulmont.timesheets.entity.TimeEntry;
import com.haulmont.timesheets.gui.commandline.CommandLineFrameController;
import com.haulmont.timesheets.gui.util.ComponentsHelper;
import org.apache.commons.collections.CollectionUtils;

import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.Map;

/**
 * @author gorelov
 */
public class MyTimeEntries extends AbstractLookup {
    @Inject
    protected GroupTable<TimeEntry> timeEntriesTable;
    @Named("timeEntriesTable.edit")
    protected EditAction timeEntriesTableEdit;
    @Named("timeEntriesTable.create")
    protected CreateAction timeEntriesTableCreate;
    @Inject
    private CommandLineFrameController commandLine;

    @Override
    public void init(Map<String, Object> params) {
        timeEntriesTableCreate.setOpenType(WindowManager.OpenType.DIALOG);
        timeEntriesTableEdit.setOpenType(WindowManager.OpenType.DIALOG);

        timeEntriesTable.setStyleProvider(new Table.StyleProvider() {
            @Nullable
            @Override
            public String getStyleName(Entity entity, String property) {
                if ("status".equals(property)) {
                    TimeEntry timeEntry = (TimeEntry) entity;
                    if (timeEntry == null) {
                        return null;
                    } else {
                        return ComponentsHelper.getTimeEntryStatusStyle(timeEntry);
                    }
                }
                return null;
            }
        });

        commandLine.setTimeEntriesHandler(resultTimeEntries -> {
            if (CollectionUtils.isNotEmpty(resultTimeEntries)) {
                final TimeEntryEdit window = (TimeEntryEdit) openEditor("ts$TimeEntry.edit", resultTimeEntries.get(0),
                        WindowManager.OpenType.DIALOG);
                window.addListener(actionId -> {
                    if (Window.COMMIT_ACTION_ID.equals(actionId)) {
                        timeEntriesTable.refresh();
                        timeEntriesTable.setSelected(window.getItem());
                    }
                });
            }
        });
    }
}


text:
extern void* memchr(const void*,int,int);
extern int memcmp(const void*,const void*,int);
extern void* memcpy(void*,const void*,int);
extern void* memmove(void*,const void*,int);
extern void* memset(void*,int,int);
extern char* strcat(char*,const char*);
extern char* strchr(const char*,int);
extern int strcmp(const char*,const char*);
extern int strcoll(const char*,const char*);
extern char* strcpy(char*,const char*);
extern int strcspn(const char*,const char*);
extern int strlen(const char*);
extern char* strncat(char*,const char*,int);
extern int strncmp(const char*,const char*,int);
extern char* strncpy(char*,const char*,int);
extern char* strpbrk(const char*,const char*);
extern char* strrchr(const char*,int);
extern int strspn(const char*,const char*);
extern char* strstr(const char*,const char*);
extern char* strtok(char*,const char*);
extern int strxfrm(char*,const char*,int);
extern char* strdup(const char*);
#endif


text:
<!doctype html>

        <title>Viewport: Scroll - no page scale</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, minimum-scale=1">

Viewport: Scroll - no page scale

Test Description: This test checks that window.visualViewport returns correct offset and scroll values without any pinch-zoom page scale applied.

window.visualViewport's offsetLeft and offsetTop is ().

window.visualViewport's pageLeft and pageTop is ().


text:
package com.sun.jini.test.spec.activation.activatableinvocationhandler;

import java.util.logging.Level;
import com.sun.jini.qa.harness.TestException;
import com.sun.jini.qa.harness.QATest;
import com.sun.jini.qa.harness.QAConfig;
import java.rmi.activation.ActivationID;
import net.jini.activation.ActivatableInvocationHandler;
import com.sun.jini.test.spec.activation.util.MethodSetProxy;

/**
 * <pre>
 * Purpose:
 *   This test verifies the behavior of the ActivatableInvocationHandler
 *   during normal and exceptional constructor call:
 *      ActivatableInvocationHandler(
 *              java.rmi.activation.ActivationID id,
 *              java.rmi.Remote underlyingProxy)
 *   Chack that constructor throws NullPointerException if the id
 *   is null.
 *
 * Infrastructure:
 *   This test requires the following infrastructure:
 *     1) MethodSetProxy
 *
 * Actions:
 *   Test performs the following steps:
 *       1) construct a ActivatableInvocationHandler object
 *          passing FakeActivationID and MethodSetProxy as a
 *          parameters
 *          verify instance of ActivatableInvocationHandler is created
 *       2) construct a ActivatableInvocationHandler object
 *          passing FakeActivationID and null as a parameters
 *          verify instance of ActivatableInvocationHandler is created
 *       3) construct a ActivatableInvocationHandler object
 *          passing null and null as a parameters
 *          verify NullPointerException is thrown
 * </pre>
 */
public class Constructor_AccessorTest extends QATest {

    /**
     * This method performs all actions mentioned in class description.
     */
    public void run() throws Exception {
        ActivatableInvocationHandler handler;
        ActivationID aid = new ActivationID(null);
        MethodSetProxy fp = new MethodSetProxy(logger);
        handler = new ActivatableInvocationHandler(aid, fp);
        aid = new ActivationID(null);
        handler = new ActivatableInvocationHandler(aid, null);
        try {
            handler = new ActivatableInvocationHandler(null, null);
            throw new TestException(
                    "ActivatableInvocationHandler constructior"
                    + " should throws NullPointerException if"
                    + " the activation identifier is null");
        } catch (NullPointerException ignore) {
        }
    }
}


text:
package br.com.swconsultoria.efd.icms.bo.bloco0;

import br.com.swconsultoria.efd.icms.registros.bloco0.Registro0005;
import br.com.swconsultoria.efd.icms.util.Util;

/**
 * @author Samuel Oliveira
 */
public class GerarRegistro0005 {

    public static StringBuilder gerar(Registro0005 registro0005, StringBuilder sb) {

        sb.append("|").append(Util.preencheRegistro(registro0005.getReg()));
        sb.append("|").append(Util.preencheRegistro(registro0005.getFantasia()));
        sb.append("|").append(Util.preencheRegistro(registro0005.getCep()));
        sb.append("|").append(Util.preencheRegistro(registro0005.getEnd()));
        sb.append("|").append(Util.preencheRegistro(registro0005.getNum()));
        sb.append("|").append(Util.preencheRegistro(registro0005.getCompl()));
        sb.append("|").append(Util.preencheRegistro(registro0005.getBairro()));
        sb.append("|").append(Util.preencheRegistro(registro0005.getFone()));
        sb.append("|").append(Util.preencheRegistro(registro0005.getFax()));
        sb.append("|").append(Util.preencheRegistro(registro0005.getEmail()));
        sb.append("|").append('\n');

        return sb;
    }
}


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.net;

import android.test.InstrumentationTestCase;
import android.test.suitebuilder.annotation.SmallTest;

import org.chromium.base.test.util.Feature;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.charset.Charset;
import java.util.Arrays;

/**
 * Tests for {@link ChunkedWritableByteChannel}
 */
@SuppressWarnings("deprecation")
public class ChunkedWritableByteChannelTest extends InstrumentationTestCase {
    private ChunkedWritableByteChannel mChannel;

    @Override
    public void setUp() {
        mChannel = new ChunkedWritableByteChannel();
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testSetCapacity() {
        int capacity = 100;
        mChannel.setCapacity(capacity);
        assertEquals("Bytebuffer capacity wasn't set properly", capacity,
                mChannel.getByteBuffer().capacity());
        mChannel.close();
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testWrite() throws IOException {
        String test = "Write in the buffer.";
        mChannel.write(
                ByteBuffer.wrap(test.getBytes(Charset.forName("UTF-8"))));
        mChannel.write(
                ByteBuffer.wrap(test.getBytes(Charset.forName("UTF-8"))));
        assertEquals("Buffer didn't write the bytes properly", test + test,
                new String(mChannel.getBytes(), "UTF-8"));
        mChannel.close();
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testCloseChannel() {
        assertTrue("Channel should be open", mChannel.isOpen());
        mChannel.close();
        assertFalse("Channel shouldn't be open", mChannel.isOpen());
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testWriteToClosedChannel() throws IOException {
        try {
            mChannel.close();
            mChannel.write(ByteBuffer.wrap(new byte[1]));
            fail("ClosedChannelException should have been thrown.");
        } catch (ClosedChannelException e) {
            // Intended
        }
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testCapacityGrows() throws Exception {
        mChannel.setCapacity(123);
        byte[] data = new byte[1234];
        Arrays.fill(data, (byte) 'G');
        mChannel.write(ByteBuffer.wrap(data));
        assertTrue(Arrays.equals(data, mChannel.getBytes()));
    }
}


text:
<?php

$installer = $this;
/* @var $installer Mage_Core_Model_Resource_Setup */

$installer->startSetup();

$installer->run("
ALTER TABLE `{$this->getTable('core_url_rewrite')}` ADD INDEX `IDX_ID_PATH` ( `id_path` );
");

$installer->endSetup();


text:
<?php
// +-----------------------------------------------------------------------+
// | Piwigo - a PHP based photo gallery                                    |
// +-----------------------------------------------------------------------+
// | Copyright(C) 2008-2014 Piwigo Team                  http://piwigo.org |
// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
// +-----------------------------------------------------------------------+
// | This program is free software; you can redistribute it and/or modify  |
// | it under the terms of the GNU General Public License as published by  |
// | the Free Software Foundation                                          |
// |                                                                       |
// | This program is distributed in the hope that it will be useful, but   |
// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
// | General Public License for more details.                              |
// |                                                                       |
// | You should have received a copy of the GNU General Public License     |
// | along with this program; if not, write to the Free Software           |
// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
// | USA.                                                                  |
// +-----------------------------------------------------------------------+
/*
Language Name: Wolof [SN]
Version: 2.6.0
Language URI: http://piwigo.org/ext/extension_view.php?eid=737
Author: Piwigo team
Author URI: http://piwigo.org
*/

// Langage informations
$lang_info['language_name'] = 'Wolof';
$lang_info['country'] = 'Sénégal';
$lang_info['direction'] = 'ltr';
$lang_info['code'] = 'wo';
$lang_info['zero_plural'] = true;

$lang['day'][0] = 'Dibeer ji ';
$lang['day'][1] = 'Altine';
$lang['day'][2] = 'Talaata';
$lang['day'][3] = 'àllarba';
$lang['day'][4] = 'Alxames';
$lang['day'][5] = 'àjjuma ';
$lang['day'][6] = 'Gaawu-aset';
$lang['month'][10] = 'Tabaski';
$lang['month'][11] = 'Tamkharit';
$lang['month'][12] = 'Digui Gamou';
$lang['month'][1] = 'Gamou';
$lang['month'][2] = 'Raki Gamou';
$lang['month'][3] = 'Rakâti Gamou';
$lang['month'][4] = 'Mâmou Kôr';
$lang['month'][5] = 'Ndèyou Kôr';
$lang['month'][6] = 'Baraxlou';
$lang['month'][7] = 'Kôr';
$lang['month'][8] = 'Kori';
$lang['month'][9] = 'Digui Tabaski';
?>


text:
describe ActiveGraph::Node::IdProperty do
  before(:all) do
    ActiveGraph::Config.delete(:id_property)
    ActiveGraph::Config.delete(:id_property_type)
    ActiveGraph::Config.delete(:id_property_type_value)
  end

  before do
    clear_model_memory_caches
  end

  describe 'abnormal cases' do
    describe 'id_property' do
      it 'raise for id_property :something, :bla' do
        expect do
          stub_node_class('Unique') do
            id_property :something, :bla
          end
        end.to raise_error(/Expected a Hash/)
      end

      it 'raise for id_property :something, bla: 42' do
        expect do
          stub_node_class('Unique') do
            id_property :something, bla: 42
          end
        end.to raise_error(/Illegal value/)
      end
    end
  end

  describe 'when no id_property' do
    let!(:clazz) do
      stub_node_class('Clazz') do
        property :name
      end
    end

    it 'uses the neo_id as id after save' do
      allow(SecureRandom).to receive(:uuid) { 'secure123' }
      node = Clazz.new
      expect(node.id).to eq(nil)
      node.save!
      expect(node.id).to eq('secure123')
    end

    it 'can find by id uses the neo_id' do
      node = Clazz.create!
      node.name = 'kalle'
      expect(Clazz.find_by_id(node.id)).to eq(node)
    end

    it 'returns :id as primary_key' do
      expect(Clazz.primary_key).to eq :uuid
    end

    it 'responds false to id_property' do
      expect(Clazz.id_property?).to be_truthy
    end

    describe 'when having a configuration' do
      let_config(:id_property, :the_id)
      let_config(:id_property_type, :auto)
      let_config(:id_property_type_value, :uuid)

      let!(:clazz) do
        stub_node_class('Clazz')
      end

      it 'will set the id_property' do
        node = Clazz.new
        expect(node).to respond_to(:the_id)
        expect(Clazz.mapped_label.indexes).to match_array [a_hash_including(label: :Clazz, properties: [:the_id])]
      end
    end
  end

  describe 'when having neo_id configuration' do
    let_config(:id_property, :neo_id)

    before do
      stub_node_class('NeoIdTest')
    end

    it 'it will find node by neo_id' do
      node = NeoIdTest.create
      expect(NeoIdTest.where(id: node).first).to eq(node)
    end
  end

  describe 'id_property :myid' do
    before do
      stub_node_class('Clazz') do
        id_property :myid
      end
    end

    it 'has an index' do
      Clazz.ensure_id_property_info!
      expect(Clazz.mapped_label.indexes).to match array_including([a_hash_including(label: :Clazz, properties: [:myid])])
    end

    describe 'property myid' do
      it 'is not defined when before save ' do
        node = Clazz.new
        expect(node.myid).to be_nil
      end

      it 'can be set' do
        node = Clazz.new
        node.myid = '42'
        expect(node.myid).to eq('42')
      end

      it 'can be saved after set' do
        node = Clazz.new
        node.myid = '42'
        node.save!
        expect(node.myid).to eq('42')
      end

      it 'is same as id' do
        node = Clazz.new
        node.myid = '42'
        expect(node.id).to be_nil
      end

      it 'is returned by primary_key' do
        expect(Clazz.primary_key).to eq :myid
      end

      it 'makes the class respond true to id_property?' do
        expect(Clazz.id_property?).to be_truthy
      end

      context 'id_property defined twice' do
        before do
          ActiveGraph::ModelSchema::MODEL_CONSTRAINTS.clear

          Clazz.id_property :my_property, auto: :uuid
          Clazz.id_property :another_property, auto: :uuid
          Clazz.ensure_id_property_info!
        end

        it 'removes any previously declared properties' do
          begin
            node = Clazz.create
          rescue ActiveGraph::DeprecatedSchemaDefinitionError
            nil
          end
          expect(node.respond_to?(:uuid)).to be_falsey
          expect(node.respond_to?(:my_property)).to be_falsey
        end

        it_behaves_like 'raises schema error not including', :constraint, :Clazz, :uuid
        it_behaves_like 'raises schema error not including', :constraint, :Clazz, :myid
        it_behaves_like 'raises schema error not including', :constraint, :Clazz, :my_property
        it_behaves_like 'raises schema error including', :constraint, :Clazz, :another_property
      end
    end

    describe 'find_by_id' do
      it 'finds it if it exists' do
        Clazz.create(myid: 'a')
        node_b = Clazz.create(myid: 'b')
        Clazz.create(myid: 'c')
        found = Clazz.find_by_id('b')
        expect(found).to eq(node_b)
      end

      it 'does not find it if it does not exist' do
        Clazz.create(myid: 'd')

        found = Clazz.find_by_id('something else')
        expect(found).to be_nil
      end
    end

    describe 'find_by_neo_id' do
      it 'loads by the neo id' do
        node1 = Clazz.create
        found = Clazz.find_by_neo_id(node1.neo_id)
        expect(found).to eq node1
      end
    end

    describe 'order' do
      it 'should order by myid' do
        nodes = Array.new(3) { |i| Clazz.create myid: i }

        expect(Clazz.order(id: :desc).to_a).to eq(nodes.reverse)
      end
    end
  end

  EXISTS_REGEXP = /Node.\d+\)? already exists with label/

  describe 'id_property :my_id, on: :foobar' do
    before do
      stub_node_class('Clazz') do
        id_property :my_id, on: :foobar

        def foobar
          'some id'
        end
      end
    end

    it 'has an index' do
      Clazz.ensure_id_property_info!

      expect(Clazz.mapped_label.indexes).to match array_including([a_hash_including(label: :Clazz, properties: [:my_id])])
    end

    it 'throws exception if the same uuid is generated when saving node' do
      Clazz.default_property :my_id do
        'same uuid'
      end
      Clazz.create
      expect { Clazz.create }.to raise_error(EXISTS_REGEXP)
    end

    describe 'property my_id' do
      it 'is not defined when before save ' do
        node = Clazz.new
        expect(node.my_id).to be_nil
      end

      it "is set to foobar's return value after save" do
        node = Clazz.new
        node.save
        expect(node.my_id).to eq('some id')
      end

      it 'is same as id' do
        node = Clazz.new
        expect(node.id).to be_nil
        node.save
        expect(node.id).to eq(node.my_id)
      end
    end

    describe 'find_by_id' do
      it 'finds it if it exists' do
        node = Clazz.create!
        expect(Clazz.find_by_id(node.my_id)).to eq(node)
      end
    end
  end

  describe 'constraint setting' do
    let(:id_property_name) {}
    let(:id_property_options) { {} }

    let(:subclass_id_property_name) {}
    let(:subclass_id_property_options) { {} }

    before do
      delete_schema

      property_name = id_property_name
      property_options = id_property_options
      stub_node_class('Clazz', false) do
        id_property property_name, property_options.merge(auto: :uuid) if property_name
      end
      property_name = subclass_id_property_name
      property_options = subclass_id_property_options
      stub_named_class('SubClazz', Clazz) do
        id_property property_name, property_options.merge(auto: :uuid) if property_name
      end
      Clazz.ensure_id_property_info!
      SubClazz.ensure_id_property_info!
      ActiveGraph::ModelSchema.reload_models_data!
    end

    it_behaves_like 'raises schema error including', :constraint, :Clazz, :uuid
    it_behaves_like 'raises schema error not including', :constraint, :SubClazz

    let_context id_property_name: :my_uuid do
      let_context id_property_options: {constraint: false} do
        it_behaves_like 'logs id_property constraint option false warning', :Clazz
        it_behaves_like 'does not log id_property constraint option false warning', :SubClazz

        let_context subclass_id_property_name: :other_uuid do
          it_behaves_like 'logs id_property constraint option false warning', :Clazz
          it_behaves_like 'does not log id_property constraint option false warning', :SubClazz

          let_context subclass_id_property_options: {constraint: false} do
            it_behaves_like 'logs id_property constraint option false warning', :Clazz
            it_behaves_like 'logs id_property constraint option false warning', :SubClazz
          end

          let_context subclass_id_property_options: {constraint: true} do
            it_behaves_like 'logs id_property constraint option false warning', :Clazz
            it_behaves_like 'does not log id_property constraint option false warning', :SubClazz

            it_behaves_like 'raises schema error including', :constraint, :Clazz, :my_uuid
            it_behaves_like 'raises schema error including', :constraint, :SubClazz, :other_uuid
          end
        end

        let_context subclass_id_property_name: :my_uuid do
          it_behaves_like 'logs id_property constraint option false warning', :Clazz
          it_behaves_like 'does not log id_property constraint option false warning', :SubClazz

          let_context subclass_id_property_options: {constraint: false} do
            it_behaves_like 'logs id_property constraint option false warning', :Clazz
            it_behaves_like 'logs id_property constraint option false warning', :SubClazz
          end
        end
      end

      let_context id_property_options: {constraint: true} do
        it_behaves_like 'raises schema error including', :constraint, :Clazz, :my_uuid
        it_behaves_like 'raises schema error not including', :constraint, :SubClazz

        let_context subclass_id_property_options: {constraint: true} do
          let_context subclass_id_property_name: :other_uuid do
            it_behaves_like 'raises schema error including', :constraint, :Clazz, :my_uuid
            it_behaves_like 'raises schema error including', :constraint, :SubClazz, :other_uuid
          end

          let_context subclass_id_property_name: :my_uuid do
            it_behaves_like 'raises schema error including', :constraint, :Clazz, :my_uuid
            it_behaves_like 'raises schema error including', :constraint, :SubClazz, :my_uuid
          end
        end
      end

      let_context id_property_options: {constraint: nil} do
        it_behaves_like 'raises schema error including', :constraint, :Clazz, :my_uuid
        it_behaves_like 'raises schema error not including', :constraint, :SubClazz

        let_context subclass_id_property_options: {constraint: nil} do
          let_context subclass_id_property_name: :other_uuid do
            it_behaves_like 'raises schema error including', :constraint, :Clazz, :my_uuid
            it_behaves_like 'raises schema error including', :constraint, :SubClazz, :other_uuid
          end

          let_context subclass_id_property_name: :my_uuid do
            it_behaves_like 'raises schema error including', :constraint, :Clazz, :my_uuid
            it_behaves_like 'raises schema error including', :constraint, :SubClazz, :my_uuid
          end
        end

        let_context subclass_id_property_options: {constraint: true} do
          let_context subclass_id_property_name: :other_uuid do
            it_behaves_like 'raises schema error including', :constraint, :Clazz, :my_uuid
            it_behaves_like 'raises schema error including', :constraint, :SubClazz, :other_uuid
          end

          let_context subclass_id_property_name: :my_uuid do
            it_behaves_like 'raises schema error including', :constraint, :Clazz, :my_uuid
            it_behaves_like 'raises schema error including', :constraint, :SubClazz, :my_uuid
          end
        end
      end
    end
  end

  describe 'id_property :my_uuid, auto: :uuid' do
    before do
      stub_node_class('Clazz') do
        id_property :my_uuid, auto: :uuid
      end
    end

    it 'has an index' do
      Clazz.ensure_id_property_info!

      expect(Clazz.mapped_label.indexes).to match array_including([a_hash_including(label: :Clazz, properties: [:my_uuid])])
    end

    it 'throws exception if the same uuid is generated when saving node' do
      Clazz.default_property :my_uuid do
        'same uuid'
      end
      Clazz.create
      expect { Clazz.create }.to raise_error(EXISTS_REGEXP)
    end

    describe 'property my_uuid' do
      it 'is not defined when before save ' do
        node = Clazz.new
        expect(node.my_uuid).to be_nil
      end

      it 'is is set when saving ' do
        node = Clazz.new
        node.save
        expect(node.my_uuid).to_not be_empty
      end

      it 'is same as id' do
        node = Clazz.new
        expect(node.id).to be_nil
        node.save
        expect(node.id).to eq(node.my_uuid)
      end
    end

    describe 'find_by_id' do
      it 'finds it if it exists' do
        Clazz.create
        node = Clazz.create
        Clazz.create

        found = Clazz.find_by_id(node.my_uuid)
        expect(found).to eq(node)
      end

      it 'does not find it if it does not exist' do
        Clazz.create

        found = Clazz.find_by_id('something else')
        expect(found).to be_nil
      end
    end
  end

  describe 'id_property :neo_id' do
    before do
      stub_node_class('NeoIdTest', false) do
        id_property :neo_id
      end
    end

    it 'has an index' do
      NeoIdTest.ensure_id_property_info!

      expect(NeoIdTest.mapped_label.indexes).to be_empty
    end

    describe 'property id' do
      it 'is is set when saving ' do
        node = NeoIdTest.new
        expect { node.save }.to change { node.id.present? }.from(false).to(true)
      end

      it 'is same as neo_id' do
        node = NeoIdTest.create
        expect(node.id).to eq(node.neo_id)
      end
    end

    describe 'find_by_id' do
      it 'finds it if it exists' do
        NeoIdTest.create
        node = NeoIdTest.create
        NeoIdTest.create

        found = NeoIdTest.find_by_id(node.id)
        expect(found).to eq(node)
      end

      it 'does not find it if it does not exist' do
        found = NeoIdTest.find_by_id(NeoIdTest.create.id + 1)
        expect(found).to be_nil
      end
    end

    describe 'find_by_ids' do
      it 'finds them if they exist' do
        NeoIdTest.create
        nodes = Array.new(3) { NeoIdTest.create }
        NeoIdTest.create

        expect(NeoIdTest.find_by_ids(nodes.map(&:id))).to match_array(nodes)
      end

      it 'does not find it if it does not exist' do
        found = NeoIdTest.find_by_ids([NeoIdTest.create.id + 1])
        expect(found).to be_empty
      end
    end

    describe 'where' do
      it 'should use neo_id' do
        NeoIdTest.create
        node = NeoIdTest.create
        NeoIdTest.create

        found = NeoIdTest.where(id: node.id).first
        expect(found).to eq(node)
      end

      it 'should find if id is a string' do
        node = NeoIdTest.create
        expect(NeoIdTest.where(id: node.id.to_s).first).to eq(node)
      end

      it 'should find with array' do
        NeoIdTest.create
        nodes = Array.new(3) { NeoIdTest.create }
        NeoIdTest.create

        expect(NeoIdTest.where(id: nodes)).to match_array(nodes)
      end
    end

    describe 'where_not' do
      it 'should find complement' do
        node = NeoIdTest.create
        excluded = NeoIdTest.create
        expect(NeoIdTest.where_not(id: excluded)).to eq([node])
      end
    end

    describe 'order' do
      it 'should order by neo_id' do
        # ascending neo_ids during insertion cannot be guaranteed anymore in community version'
        nodes = Array.new(3) { NeoIdTest.create }.sort_by!(&:id)
        expect(NeoIdTest.order(id: :desc).to_a).to eq(nodes.reverse)
      end
    end
  end

  describe 'inheritance' do
    before do
      stub_node_class('Teacher') do
        id_property :my_id, on: :my_method

        def my_method
          'an id'
        end
      end

      stub_named_class('Substitute', Teacher)

      stub_node_class('Vehicle') do
        id_property :my_id, auto: :uuid
      end

      stub_named_class('Car', Vehicle)

      stub_node_class('Fruit') do
        id_property :my_id
      end

      stub_named_class('Apple', Fruit)

      stub_node_class('Sport') do
        id_property :neo_id
      end

      stub_named_class('Skiing', Sport)
    end

    it 'inherits the base id_property' do
      expect(Substitute.create.my_id).to eq 'an id'
    end

    it 'works with auto uuid' do
      expect(Car.create.my_id).not_to be_nil
    end

    it 'works without conf specified' do
      expect(Apple.create.my_id).not_to be_nil
    end

    it 'works with neo_id' do
      node = Skiing.create
      expect(node.id).not_to be_nil
      expect(node.id).to eq(node.neo_id)
    end

    context 'when a driver is not started' do
      before do
        stub_node_class('Executive') do
          id_property :my_id, on: :my_method

          def my_method
            'an id'
          end
        end

        stub_named_class('CEO', Executive)
      end

      it 'subclass inherits the primary_key' do
        expect(CEO.primary_key).to eq(:my_id)
      end
    end
  end
end


text:
redirect_from: /docs/1.0.0-alpha.3/classes/state.glob.html
---
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>Glob | UI-Router</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">
	<link rel="stylesheet" href="../assets/css/typedoctheme.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					UI-Router

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					state

					Glob

Class Glob

for typedoc

Hierarchy

						Glob

Index

Constructors

constructor

Properties

glob

text

Methods

matches

from<wbr>String

is

Constructors

new <wbr>Glob(text: string): Glob

Parameters

text: string

Returns Glob

Defined in common/glob.ts:4

Properties

glob: Array<string>

Defined in common/glob.ts:4

text: string

Defined in common/glob.ts:3

Methods

matches(name: string): boolean

Parameters

name: string

Returns boolean

Defined in common/glob.ts:11

from<wbr>String(text: string): Glob

Parameters

text: string

Returns Glob

Defined in common/glob.ts:38

is(text: string): boolean

Parameters

text: string

Returns boolean

Defined in common/glob.ts:34

						Globals

						common

						common_<wbr>hof

						common_<wbr>predicates

						common_<wbr>strings

						core

						justjs

						ng1

						ng1_<wbr>directives

						ng1_<wbr>state_<wbr>events

						ng2

						ng2_<wbr>directives

						params

						path

						resolve

						state

						trace

						transition

						url

						view

						Enter<wbr>Exit<wbr>Hooks

						Glob

								constructor

								glob

								text

								matches

								from<wbr>String

								is

						Resolve<wbr>Hooks

						State

						State<wbr>Builder

						State<wbr>Matcher

						State<wbr>Provider

						State<wbr>Queue<wbr>Manager

						State<wbr>Registry

						State<wbr>Service

						Target<wbr>State

						Transition<wbr>Manager

						View<wbr>Hooks

						Builders

						Href<wbr>Options

						State<wbr>Declaration

						Builder<wbr>Function

						State<wbr>OrName

						EAGER

						LAZY

						$<wbr>Included<wbr>ByState<wbr>Filter

						$<wbr>IsState<wbr>Filter

						parse<wbr>Url

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using TietoCRM.Models.Interfaces;

namespace TietoCRM.Models
{
    public class ViewCsvParser<T> where T : SQLBaseClass
    {
        private List<String> propertiesToSkip;
        public List<string> PropertiesToSkip
        {
            get
            {
                return propertiesToSkip;
            }
        }
        private String name;
        public string Name
        {
            get
            {
                return name;
            }
        }

        public ViewCsvParser(String name)
        {
            this.name = name;
            this.propertiesToSkip = new List<string>();
        }

        public ViewCsvParser(String name, List<String> propertiesToSkip)
        {
            this.name = name;
            this.propertiesToSkip = propertiesToSkip;
        }

        private DataTable ConvertToDataTable(IEnumerable<T> data)
        {
            DataTable dt = new DataTable();
            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
            foreach (PropertyDescriptor prop in props)
            {
                if(!this.propertiesToSkip.Contains(prop.DisplayName))
                    dt.Columns.Add(prop.DisplayName); // header
            }
            foreach (T item in data)
            {
                DataRow dr = dt.NewRow();
                foreach (PropertyDescriptor prop in props)
                {
                    if (!this.propertiesToSkip.Contains(prop.DisplayName))
                        dr[prop.DisplayName] = prop.Converter.ConvertToString(prop.GetValue(item));
                }
                dt.Rows.Add(dr);
            }

            return dt;
        }

        public void WriteExcelWithNPOI(IEnumerable<T> data, String extension = "xlsx")
        {
            DataTable dt = this.ConvertToDataTable(data);
            IWorkbook workbook;

            if (extension == "xlsx")
            {
                workbook = new XSSFWorkbook();
            }
            else if (extension == "xls")
            {
                workbook = new HSSFWorkbook();
            }
            else
            {
                throw new Exception("This format is not supported");
            }

            ISheet sheet1 = workbook.CreateSheet("Sheet 1");

            //make a header row
            IRow row1 = sheet1.CreateRow(0);

            for (int j = 0; j < dt.Columns.Count; j++)
            {

                ICell cell = row1.CreateCell(j);
                String columnName = dt.Columns[j].ToString();
                cell.SetCellValue(columnName);
            }

            //loops through data
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                IRow row = sheet1.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {

                    ICell cell = row.CreateCell(j);
                    String columnName = dt.Columns[j].ToString();
                    cell.SetCellValue(dt.Rows[i][columnName].ToString());
                }
            }

            using (var exportData = new MemoryStream())
            {
                HttpResponse response = System.Web.HttpContext.Current.Response;
                response.Clear();
                Encoding encoding = Encoding.UTF8;
                response.Charset = encoding.EncodingName;
                response.ContentEncoding = Encoding.Unicode;
                workbook.Write(exportData);
                if (extension == "xlsx") //xlsx file format
                {
                    response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", this.Name + ".xlsx"));
                    response.BinaryWrite(exportData.ToArray());
                }
                else if (extension == "xls")  //xls file format
                {
                    response.ContentType = "application/vnd.ms-excel";
                    response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", this.Name + "ContactNPOI.xls"));
                    response.BinaryWrite(exportData.GetBuffer());
                }
                response.End();
            }
        }
    }
}


text:
@implementation UIColor (randomColor)

#pragma mark - Public Methods
+ (NSArray*) randomColorsWithHue:(YGColorHue) colorHue luminosity:(YGColorLuminosity) luminosity count:(NSUInteger) count
{
    NSMutableArray * colors = [NSMutableArray arrayWithCapacity:count];

    for(NSUInteger i = 0; i < count ; ++i)
    {
        [colors addObject:[self randomColorWithHue:colorHue luminosity:luminosity]];
    }
    return colors;
}

+ (NSArray*) randomColorsWithCount:(NSUInteger) count
{
   return [self randomColorsWithHue:YGColorHueRandom luminosity:YGColorLuminosityRandom count:count];
}

+ (NSArray*) randomColorsWithHue:(YGColorHue) colorHue count:(NSUInteger) count
{
   return [self randomColorsWithHue:colorHue luminosity:YGColorLuminosityRandom count:count];
}

+ (NSArray*) randomColorsWithLuminosity:(YGColorLuminosity) luminosity count:(NSUInteger) count
{
   return [self randomColorsWithHue:YGColorHueRandom luminosity:luminosity count:count];
}

+ (UIColor*) randomColorWithHue:(YGColorHue) colorHue luminosity:(YGColorLuminosity) luminosity
{
        CGFloat H = [YGColorDefinition pickHueWithEnum:colorHue];
        CGFloat S = [YGColorDefinition pickSaturationWithHueValue:H luminosity:luminosity monochrome:(colorHue==YGColorHueMonochrome)];
        CGFloat B = [YGColorDefinition pickBrightnessWitHueValue:H saturationValue:S luminosity:luminosity];

        return [UIColor colorWithHue:(H/360.0f) saturation:(S/100.0f) brightness:(B/100.0f) alpha:1.0f];
}

+ (UIColor*) randomColor
{
    return [self randomColorWithHue:YGColorHueRandom luminosity:YGColorLuminosityRandom];
}
+ (UIColor*) randomColorWithHue:(YGColorHue) colorHue
{
   return [self randomColorWithHue:colorHue luminosity:YGColorLuminosityRandom];
}

+ (UIColor*) randomColorWithLuminosity:(YGColorLuminosity) luminosity
{
    return [self randomColorWithHue:YGColorHueRandom luminosity:luminosity];
}

@end


text:
CREATE VIEW rd.[TaskTemplateParameters]
	AS SELECT [Id], [TaskTemplateVersionId], [Name], [Optional], [Encrypted], Description FROM dbo.[TaskTemplateParameters]


text:
using System;

namespace ReferenceToSubscriber
{
    class EventPublisher
    {
        public event EventHandler Fire;
        public void RaiseFire()
        {
            if (this.Fire != null)
                this.Fire(this, EventArgs.Empty);
        }
    }

    class EventSubscriber
    {
        private string _name;

        public EventSubscriber(string name)
        {
            this._name = name;
        }

        public void Handler(object sender, EventArgs e)
        {
            Console.WriteLine("{0}: Kabooooooom!", this._name);
        }

        ~EventSubscriber()
        {
            Console.WriteLine(string.Format("{0}: \"Good bye.\"", this._name));
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            EventPublisher publisher = new EventPublisher();

            publisher.Fire += new EventSubscriber("Mac").Handler;
            new EventSubscriber("Tosh");

            GC.Collect();
            GC.WaitForPendingFinalizers();

            publisher.RaiseFire();

            Console.WriteLine("Finish");

            // Output
            // Tosh: "Good bye."
            // Mac: Kabooooooom!
            // Finish
            // Mac: "Good bye."
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="fr.esgi.todolistscrumandroid">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".AddTaskActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar"/>
    </application>

</manifest>


text:
<!DOCTYPE html>

	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1">

<base href="/">

			<input id="searchYouTube" class="col-90 search-field center vertical-margin"
					type="text" name="q" results="0" autocomplete="off" placeholder="Введите текст для поиска"
					ng-model="queryInputValue"
					ng-keydown="onSearchbarKeydown($event)"
					ng-focus="onSearchbarFocus($event)"
					ng-click="onSearchbarFocus($event)"
					ng-blur="onSearchbarBlur($event)"/>
			<button class="center button-sparse vertical-margin" ng-click="startSearch()">Поиск</button>

Ничего не найдено.

Введена пустая строка.

				{{result.name}}


text:
def signal(f):

    def w(obj, *args, **kw):
        rt = f(obj, *args, **kw)
        if rt:
            obj.signal.dispatch(signal_name=f.func_name, *args, **kw)
        return rt

    return w

class Signal():

    def __init__(self):
        self.listeners = []

    def add(self, listener):
        self.listeners.append(listener)

    def remove(self, listener):
        self.listeners.remove(listener)

    def dispatch(self, *args, **kw):
        for listener in self.listeners:
            listener(*args, **kw)


text:
local Class = require 'lib.class'

------------------------------------------------------------------------
-- Functions -----------------------------------------------------------
------------------------------------------------------------------------

local Tile = Class{}

Tile.connection_interval = math.pi/2
Tile.num_connections = 2*math.pi/Tile.connection_interval
--- Constructor
-- This is the base class for all tiles; it will normally not be instantiated
-- directly
-- @param name Name of the tile
-- @param x X-coordinate of the tile
-- @param y Y-coordinate of the tile
-- @param row Row of the tile in the tilemap
-- @param column Column of the tile in the tilemap
function Tile.init(self, name, x, y)
  self.name = name
  self.x = x
  self.y = y
  self.selected = false
  self.movement = false
  self.attack = false
  self.connections = {}
  for i = 0, Tile.num_connections-1, 1 do
    self.connections[i] = false
  end

  self.connections = {}
end

--- Draw the tile
function Tile:draw(object)
    local g = love.graphics
	local skin = object:GetSkin()
	local x = object:GetX()
	local y = object:GetY()
	local width = object:GetWidth()
	local height = object:GetHeight()
	local hover = object:GetHover()
	--local text = object:GetText()
	--local font = skin.controls.button_text_font
	--local twidth = font:getWidth(object.text)
	--local theight = font:getHeight(object.text)
	local down = object.down
	local enabled = object:GetEnabled()
	local clickable = object:GetClickable()
    local body_color = skin.controls.button_body_color
    local outline_color = skin.controls.button_outline
    local connection_color = skin.controls.connection_color
    local sub_unit = self.sub_unit

    if self.selected then
        outline_color = skin.controls.button_outline_selected
    end

    if self.attack then
        body_color = skin.controls.button_body_attack
    elseif self.movement then
        body_color = skin.controls.button_body_movement
    end

    love.graphics.setColor( body_color )
    g.rectangle("fill", object:GetX(), object:GetY(), object:GetWidth(), object:GetHeight())

    local text = self.name
    local font = skin.controls.button_text_font
    local twidth = font:getWidth(text)
    local theight = font:getHeight(text)
    local text_color = skin.controls.button_text_color
    love.graphics.setFont(font)
    love.graphics.setColor(text_color)
    love.graphics.print(text, x + width/2 - twidth/2, y + height/2 - theight/2)

    love.graphics.setColor(connection_color)
    for i = 0, Tile.num_connections-1, 1 do
        local exists = self.connections[i]
        if exists then
            local rotation = Tile.connection_interval*i
            local x1 = x + width/2
            local y1 = y + height/2
            local x2 = (width/2)*math.cos(rotation)+x1
            local y2 = -(height/2)*math.sin(rotation)+y1
            love.graphics.line( x1, y1, x2, y2 )
        end
    end

    love.graphics.setColor(outline_color)
    if self.img ~= nil then
        local image = skin.images[ self.img ]
        if image ~= nil then
            local sx = width/image:getWidth() * math.pow( -1, 0 )
            local sy = height/image:getHeight()
            love.graphics.draw(image, rx+width*0, ry, 0, sx, sy, 0, 0 )
        end
    end

    skin.OutlinedRectangle(x, y, width, height)

    if sub_unit ~= nil then
        sub_unit:draw(object)
    end
end

function Tile:__tostring()
  return self.name
end

return Tile


text:
namespace Question2AnswerMigrater.Executor.OldForumModels
{
    using System;
    using System.Collections.Generic;

    public partial class qa_messages
    {
        public long messageid { get; set; }
        public string type { get; set; }
        public long fromuserid { get; set; }
        public long touserid { get; set; }
        public string content { get; set; }
        public string format { get; set; }
        public System.DateTime created { get; set; }
    }
}


text:
<?php

class Nomnoml {

  static function onParserInit( Parser $parser ) {
    global $wgOut;

    $parser->setHook( 'nomnoml', array( __CLASS__, 'nomnomlRender' ) );
    $wgOut->addModules( 'ext.Nomnoml' );

    return true;
  }

  static function nomnomlRender( $input, array $args, Parser $parser, PPFrame $frame ) {
    $html  = '
';
    $html .= '<canvas></canvas>';
    $html .= '
' . $input . '
';
    $html .= '
';

    return array($html, 'markerType' => 'nowiki');
  }

}


text:
const loader = require('..');

function getLoaderOutput(originalSource) {
    return new Promise((resolve, reject) => {
        const context = {
            async: () => (err, content) => {
                if (err) {
                    reject(err);
                }
                resolve(content);
            },
            query: {},
            options: {},
        };
        loader.apply(context, [originalSource]);
    });
}

test('noop when there are no goog.provide or goog.require statements', async () => {
    const originalSource = 'console.log("hi");';
    const output = await getLoaderOutput(originalSource);
    expect(output).toEqual(originalSource);
});


text:
// A comment!
/* Another comment */
/** A documentation comment */
object MyModule
{
    def abs(n: Int): Int =
        if (n < 0)
            -n
        else
            n

    private def formatAbs(x: Int) =
    {
        val msg = "The absolute value of %d is %d"
        msg.format(x, abs(x))
    }

    def main(args: Array[String]): Unit =
        println(formatAbs(-42))
}


text:
"""
dpp : programming patterns made easy!
"""
from .composite import composite

__author__ = 'Massimiliano Culpo'
__copyright__ = 'Copyright (c) 2016 Massimiliano Culpo'
__license__ = 'Apache License Version 2.0'


text:
using namespace std;
using namespace gcNamespace;

///////////////////////////////////////////////////////////////////////////////
// thread vars

thread_local int thread_x;
int thread_count = 0;
const int THREAD_MAX =4;
std::mutex a_mutex;

///////////////////////////////////////////////////////////////////////////////
// debugging tools

void print(string str) {
    cout << "thread " << thread_x << ": " << str << "\n";
}

void wait_enter_key()
{
    cout << "\n[Press <Enter> key to continue to next test]\n\n";
    char c = '\0';
    while (c!='\n'){
        c = getchar();
    }
}

///////////////////////////////////////////////////////////////////////////////
// simple examples

void test_0() {

    gcPointer<int> i = new int;
    *i = 3;

    cout << *i << '\n';

    gcPointer<string> s = new string[4];

    s[0] = "hello";
    s[1] = " ";
    s[2] = "world";
    s[3] = "\n";

    for(*i = 0; *i < 4; (*i)++ )
        cout << s[*i];

    s = new string("new ");         //OLD CONTENT WILL BE REMOVED
    s->append("hello world");

    print(*s);

    gcPointer<char*> c = new char*{"another hello"};
    print(*c);
}

///////////////////////////////////////////////////////////////////////////////
// standard c++ class example
//
// a class that doesn't have any pointer member
// doesnt't need any special configuration

class Std_ClassBase {
public:
    int n;
    virtual ~Std_ClassBase(){}
};

class Std_Class : public Std_ClassBase
{
public:
    Std_Class(int a) {
        n = a;
        print("Std_Class" + to_string(n) + " created");
    }

    ~Std_Class() override {
        print("Std_Class" + to_string(n) + " deleted");
    }
};

void test_1() {

    gcPointer<Std_ClassBase> a = new Std_Class(1);
    gcPointer<Std_Class> b = new Std_Class(2);

    a = (gcPointer<Std_ClassBase>) b;

    // Wait some time until garbage collector do cleaning
    // so we can see if it was done correctly
    this_thread::sleep_for(chrono::milliseconds(1000));
    print("Std_Class1 deleted?");

    // Local pointers are destroyed
}

///////////////////////////////////////////////////////////////////////////////
// GC class example
//
// a class with pointer members must be configured like this template

class GC_BaseClass : public gcObject
{
    GC_CONNECT_OBJECT(GC_BaseClass,gcObject)

    gcPointer<GC_BaseClass> GC_BaseClass_ptr;

    void gc_create() {
        //print(string("create GC_BaseClass"));
    }

    void gc_destroy() {
        //print("destroy GC_BaseClass");
    }
};

///////////////////////////////////////////////////////////////////////////////
// interface

class MsgInterface {
public:
    virtual void print_msg()=0;
};

///////////////////////////////////////////////////////////////////////////////
// GC class example

class GC_Class : public  GC_BaseClass, public MsgInterface
{
    GC_CONNECT_OBJECT(GC_Class, GC_BaseClass)

    gcPointer<GC_Class> p;
    int n;

    void gc_create(int a) {
        n = a;
        print("GC_Class" + to_string(n) + " created");
        GC_BaseClass::gc_create();
    }

    void gc_destroy() {
        print("GC_Class" + to_string(n) + " deleted");
    }

    void print_msg() override {
        print("hi " + to_string(n) + "!");
        GC_BaseClass_ptr = p;
    }
};

void test_2_sub1(const gcPointer<GC_Class>& c3){

    // A normal pointer
    gcPointer<GC_Class> nonscoped_c3 = c3;

    // this function does nothing
}

void test_2_sub2( const gcPointer<GC_Class>& c4){

    // A scoped pointer
    gcScopedPointer<GC_Class> scoped_c4 = c4;

    // GC_Class2000 will be deleted now since it is scoped here
}

void test_2()
{
    gcPointer<GC_Class> p;

    p = new GC_Class(1);
    p->p = new GC_Class(2);
    p->p->p = new GC_Class(3);

    p->p->p->p = p->p;			// circular link
    p->p = new GC_Class(4);         // unlink objects 2 and 3 from root

    p->print_msg();                // method calls
    p->p->print_msg();

    // Wait some time until garbage collector do cleaning
    // so we can see if it was done correctly
    this_thread::sleep_for(chrono::milliseconds(1000));
    print("GC_Class2 GC_Class3 deleted?");

    // GC_Class5 now is lvalue and finalizable
    gcPointer<GC_Class> c1 = new GC_Class(5);

    // Add a reference
    gcPointer<GC_Class> c2 = c1;

    // make GC_Class5 not finalizable
    c1.gc_make_nonfinalizable();
    c1.gc_deallocate();

    this_thread::sleep_for(chrono::milliseconds(1000));
    print("GC_Class5 NOT deleted?");

    // Delete object
    c1.gc_make_finalizable();
    c1.gc_deallocate();

    // test a scoped pointer
    gcPointer<GC_Class> c3 = new GC_Class(1000);
    gcPointer<GC_Class> c4 = new GC_Class(2000);

    test_2_sub1(c3);
    test_2_sub2(c4);

    this_thread::sleep_for(chrono::milliseconds(1000));
    print("GC_Class2000 deleted?");

    print(to_string(c4 == 0));

    gcUniquePointer<GC_BaseClass> c5 = new GC_Class(4000);

    //gcUniquePointer<GC_Class> c6(new GC_Class(5000));
    //c5 = c6; error: casting is forbbiden for unique pointers

    //gcUniquePointer<GC_BaseClass> c6(new GC_Class(5000));
    //c5 = c6; error: assignation from lvalue

    this_thread::sleep_for(chrono::milliseconds(1000));
    print("GC_Class4000 deleted?");

    // Local pointers are destroyed
}

///////////////////////////////////////////////////////////////////////////////
// container examples

void test_3(){

    // A list of pointers
    gcListPointer<GC_Class> plist = new gcList<GC_Class>;

    for (int n = 0; n < 5; n++)
        plist->push_back( new GC_Class(n) );

    gcList<GC_Class>::iterator i = plist->begin();
    *(++i) = new GC_Class(10000);

    for (auto p : *plist) {
        print(to_string(p->n));
    }

    // Wait some time until garbage collector do cleaning
    // so we can see if it was done correctly
    this_thread::sleep_for(chrono::milliseconds(1000));
    print("GC_Class1 deleted?");

    *plist = {{new GC_Class(50),new GC_Class(60)}};

    // Local pointers are destroyed
}

void test_4(){

    gcMapPointer<string,GC_Class> pmap = new gcMap<string,GC_Class>;

    pmap["KEY"] = new GC_Class(1);
    pmap["KEY"] = new GC_Class(2);

    // Wait some time until garbage collector do cleaning
    // so we can see if it was done correctly
    this_thread::sleep_for(chrono::milliseconds(1000));
    print("GC_Class1 deleted?");

    // Local pointers are destroyed
}

void test_5(){

    gcPointer<GC_Class> p1 = new GC_Class(1), p2 = new GC_Class(2);

    gcSetPointer<GC_Class> pset = new gcSet<GC_Class>;

    pset->insert(p1);
    pset->insert(p2);
    pset->insert(p2);

    for (auto p : *pset) {
        print(to_string(p->n));
    }
    print("Set has GC_Class1 and GC_Class2 one time only?");

    // Local pointers are destroyed
}

void test_6(){

    gcPointer<GC_Class> p1 = new GC_Class(1), p2 = new GC_Class(2);

    gcArrayPointer<GC_Class,2> parr = new gcArray<GC_Class,2>;

    if(parr == parr){
    parr[0]=p1;
    parr[1]=p2;}

    for (gcPointer<GC_Class> p : *parr) {
        print(to_string(p->n));
    }

    // Local pointers are destroyed
}

///////////////////////////////////////////////////////////////////////////////
// weak pointer example

void test_7(){

    gcPointer<GC_Class> p1 = new GC_Class(1);
    gcWeakPointer<GC_Class> wp = p1;

    p1 = 0;

    // Wait some time until garbage collector do cleaning
    // so we can see if it was done correctly
    this_thread::sleep_for(chrono::milliseconds(1000));
    print("GC_Class1 deleted?");
}

///////////////////////////////////////////////////////////////////////////////
// benchmark

void test_8(){

    int time_tick_max = 0;
    int time_tick_min = 1000000;

    print("Please, wait. Testing GC interruptions time");

    ///////////////////////////////////////////////////////////////////////////////

    auto
    time_start = std::chrono::steady_clock::now();

    for (int n=0;n<30; n++)
    {
        auto
        time_tick_start = std::chrono::steady_clock::now();

        for (int i=0;  i<100;  i++)
        {
            gcPointer<int>  x = new int;
            for(int ii=0; ii<100; ii++) {
               gcPointer<int>  y = new int;
               x = y;
            }
        }

        auto
        time_tick_end = std::chrono::steady_clock::now();

        int
        time_tick_length =  std::chrono::duration_cast<std::chrono::microseconds>(
                time_tick_end - time_tick_start
                ).count();

        if (time_tick_length > time_tick_max){
            time_tick_max = time_tick_length;
        }

        if (time_tick_length < time_tick_min){
            time_tick_min = time_tick_length;
        }
    }

    auto
    time_end = std::chrono::steady_clock::now();

    ///////////////////////////////////////////////////////////////////////////////

    int
    time_length = std::chrono::duration_cast<std::chrono::microseconds>(
                time_end - time_start
                ).count();

    print(string("GC-RESULTS:"));
    print(string("total mcs  = ") + to_string(time_length));
    print(string("max tick   = ") + to_string(time_tick_max));
    print(string("min tick   = ") + to_string(time_tick_min));
    print(string("max - min  = ") + to_string(time_tick_max-time_tick_min));

    time_tick_max = 0;
    time_tick_min = 1000000;

    print("[Please, wait. Testing standard C++ time]");
    this_thread::sleep_for(chrono::milliseconds(1000));

    auto
    time_start_std = std::chrono::steady_clock::now();

    for (int n=0;n<30; n++) {

        // TICK PROCESS
        auto
        time_tick_start_std = std::chrono::steady_clock::now();

        for (int i=0;  i<100;  i++){
            int*  x = new int;
            for (int ii=0; ii<100; ii++) {
               int*  y = new int;
               delete y;
               y = x;
            }
            delete x;
        }

        auto
        time_tick_end_std = std::chrono::steady_clock::now();

        int
        time_tick_length_std =  std::chrono::duration_cast<std::chrono::microseconds>(
                    time_tick_end_std-time_tick_start_std
                    ).count();

        if (time_tick_length_std > time_tick_max){
            time_tick_max = time_tick_length_std;
        }

        if (time_tick_length_std < time_tick_min){
            time_tick_min = time_tick_length_std;
        }
    }

    auto
    time_end_std = std::chrono::steady_clock::now();

    time_length = std::chrono::duration_cast<std::chrono::microseconds>(
                time_end_std-time_start_std
                ).count();

    print(string("STD-RESULTS:"));
    print(string("total mcs  = ") + to_string(time_length));
    print(string("max tick   = ") + to_string(time_tick_max));
    print(string("min tick   = ") + to_string(time_tick_min));
    print(string("max - min  = ") + to_string(time_tick_max-time_tick_min));
}

///////////////////////////////////////////////////////////////////////////////
// thread fn

void thread_fn() {

    thread_count++;
    thread_x = thread_count;

    // Each thread Must be conneccted to grabage collector
    gcConnectThread doit;

    test_0();
    print("exit test_0");

    test_1();
    print("exit test_1");

    this_thread::sleep_for(chrono::milliseconds(1000));
    print("X2 deleted?");

    test_2();
    print("exit test_2");

    this_thread::sleep_for(chrono::milliseconds(1000));
    print("GC_Class1 , GC_Class4, GC_Class1000 deleted?");

    test_3();
    print("exit test_3");

    this_thread::sleep_for(chrono::milliseconds(1000));
    print("GC_Class0 , GC_Class1000 , GC_Class2, GC_Class3, GC_Class4 deleted?");

    test_4();
    print("exit test_4");

    this_thread::sleep_for(chrono::milliseconds(1000));
    print("GC_Class2 deleted?");

    test_5();
    print("exit test_5");

    this_thread::sleep_for(chrono::milliseconds(1000));
    print("GC_Class1 , GC_Class2 deleted?");

    test_6();
    print("exit test_6");

    this_thread::sleep_for(chrono::milliseconds(1000));
    print("GC_Class1 , GC_Class2 deleted?");

    test_7();
    print("exit test_7");

    test_8();

    print("exiting thread");
}

int main()
{
    // Init a garbage collected program
    gcCollector new_collector;

    // new_collector.sleep_time = 100

    void (*tst_tbl[])() = {test_0, test_1, test_2, test_3, test_4, test_5, test_6, test_7, test_8};

    for(int tst_num=0; tst_num<9; tst_num++)
    {
        cout << "TEST " << tst_num << "\n";
        cout << "....................................................." << "\n";

        tst_tbl[tst_num]();

        wait_enter_key();
    }

    cout << "MULTY THREAD TEST\n";
    cout << "A lot of mess will be shown\n";
    cout << "....................................................." << "\n";

    wait_enter_key();

    thread new_thread[THREAD_MAX];

    for (int n = 0; n < THREAD_MAX; n++){
        new_thread[n] = thread(&thread_fn);
    }

    for (int n = 0; n < THREAD_MAX; n++){
        while(true) {
            if( new_thread[n].joinable()) {
                new_thread[n].join();
                break;
            }
        }
    }

    cout << "TEST SUCCESFUL\n";
    cout << "....................................................." << "\n";

    return 0;
}


text:
#ifndef URI_H
#define URI_H 1

/**
 * Encodes a URI component by replacing each
 * instance of certain characters by one, two, three, or four escape
 * sequences representing the UTF-8 encoding of the character
 */

char *
uri_encode (const char *);

/**
 * Decodes a URI component source from `uri_encode'
 */

char *
uri_decode (const char *);

#endif


text:
    /**
     * remove method
     * remove element from dom
     * @return {object} element
     */
    remove: function() {
      return this.each(function(index, el) {
        el.parentNode.removeChild(el);
      });
    },


text:
#include "xcass.h"

static const xcass_type_mapping_t
xcass_types_mapping[] = {
  { "custom", CASS_VALUE_TYPE_CUSTOM },
  { "ascii", CASS_VALUE_TYPE_ASCII },
  { "bigint", CASS_VALUE_TYPE_BIGINT },
  { "blob", CASS_VALUE_TYPE_BLOB },
  { "boolean", CASS_VALUE_TYPE_BOOLEAN },
  { "counter", CASS_VALUE_TYPE_COUNTER },
  { "decimal", CASS_VALUE_TYPE_DECIMAL },
  { "double", CASS_VALUE_TYPE_DOUBLE },
  { "float", CASS_VALUE_TYPE_FLOAT },
  { "inet", CASS_VALUE_TYPE_INET },
  { "int", CASS_VALUE_TYPE_INT },
  { "text", CASS_VALUE_TYPE_TEXT },
  { "timestamp", CASS_VALUE_TYPE_TIMESTAMP },
  { "timeuuid", CASS_VALUE_TYPE_TIMEUUID },
  { "uuid", CASS_VALUE_TYPE_UUID },
  { "varchar", CASS_VALUE_TYPE_VARCHAR },
  { "varint", CASS_VALUE_TYPE_VARINT },
  { "map", CASS_VALUE_TYPE_MAP },
  { "set", CASS_VALUE_TYPE_SET },
  { "list", CASS_VALUE_TYPE_LIST }
};

static const char *
xcass_collection_types[] = { "map", "list", "set", 0 };

static CassValueType
xcass_get_type_byname(const char *name) {

  unsigned int i, count;
  count = sizeof(xcass_types_mapping) / sizeof(*xcass_types_mapping);

  for(i = 0; i < count; i++)
    if(!strcmp(name, xcass_types_mapping[i].name))
      return xcass_types_mapping[i].type;

  return CASS_VALUE_TYPE_UNKNOWN;
}

/**
 * Allocate a new query object
 * @return Returns allocated object
 *
 * @param[in] xs xcass_t instance object
 */
xcass_query_t *
xcass_query_new(xcass_t *xs) {

  xcass_query_t *query = (xcass_query_t *) malloc(sizeof(xcass_query_t));
  query->xs = xs;
  query->statement = NULL;
  query->result = NULL;
  query->cql = NULL;
  query->types = NULL;
  query->prepared = NULL;
  query->argc = 0;
  query->page_size = xs->page_size;
  query->consistency = xs->consistency;
  return query;
}

/**
 * Free a query object
 *
 * @param[in] query Query object to free
 */
void
xcass_query_free(xcass_query_t *query) {

  if(query->result)
    cass_result_free(query->result);
  if(query->statement)
    cass_statement_free(query->statement);
  if(query->prepared)
    cass_prepared_free(query->prepared);
  if(query->types)
    free(query->types);
  if(query->cql)
    free(query->cql);

  free(query);
}

/**
 * Set query consistency to given CassConsistency
 *
 * @param[in] query Query object
 * @param[in] consistency Consistency value to set
 */
void
xcass_query_consistency(xcass_query_t *query,
                        CassConsistency consistency) {

  query->consistency = consistency;
}

/**
 * Set query page size
 *
 * @param[in] query Query object
 * @param[in] page_size Page size to set (default: -1 disabled)
 */
void
xcass_query_page_size(xcass_query_t *query,
                      int page_size) {

  query->page_size = page_size;
}

CassError
xcass_query_ibind(xcass_query_t *query,
                  unsigned int index,
                  va_list aq) {

  CassError rc = CASS_OK;
  xcass_custom_t custom;

  switch(query->types[index].type) {
    case CASS_VALUE_TYPE_COUNTER:
    case CASS_VALUE_TYPE_TIMESTAMP:
    case CASS_VALUE_TYPE_BIGINT:
      rc = cass_statement_bind_int64(query->statement, index,
                                     va_arg(aq, cass_int64_t));
    break;
    case CASS_VALUE_TYPE_BOOLEAN:
      rc = cass_statement_bind_bool(query->statement, index,
                                   (cass_bool_t) va_arg(aq, int));
    break;
    case CASS_VALUE_TYPE_DECIMAL:
      rc = cass_statement_bind_decimal(query->statement, index,
                                       va_arg(aq, CassDecimal));
    break;
    case CASS_VALUE_TYPE_DOUBLE:
      rc = cass_statement_bind_double(query->statement, index,
                                      va_arg(aq, cass_double_t));
    break;
    case CASS_VALUE_TYPE_FLOAT:
      rc = cass_statement_bind_float(query->statement, index,
                                     va_arg(aq, cass_double_t));
    break;
    case CASS_VALUE_TYPE_INET:
      rc = cass_statement_bind_inet(query->statement, index,
                                    va_arg(aq, CassInet));
    break;
    case CASS_VALUE_TYPE_INT:
      rc = cass_statement_bind_int32(query->statement, index,
                                     va_arg(aq, cass_int32_t));
    break;
    case CASS_VALUE_TYPE_TIMEUUID:
    case CASS_VALUE_TYPE_UUID:
      rc = cass_statement_bind_uuid(query->statement, index,
                                    va_arg(aq, CassUuid));
    break;
    case CASS_VALUE_TYPE_BLOB:
    case CASS_VALUE_TYPE_VARINT:
      rc = cass_statement_bind_bytes(query->statement, index,
                                     va_arg(aq, CassBytes));
    break;
    case CASS_VALUE_TYPE_LIST:
    case CASS_VALUE_TYPE_SET:
    case CASS_VALUE_TYPE_MAP:
      rc = cass_statement_bind_collection(query->statement, index,
                                          va_arg(aq, CassCollection *));
    break;
    case CASS_VALUE_TYPE_ASCII:
    case CASS_VALUE_TYPE_VARCHAR:
    case CASS_VALUE_TYPE_TEXT:
      rc = cass_statement_bind_string(query->statement, index,
                                      cass_string_init(va_arg(aq, char *)));
    break;
    case CASS_VALUE_TYPE_CUSTOM:
      custom = va_arg(aq, xcass_custom_t);
      rc = cass_statement_bind_custom(query->statement, index,
                                      custom.size, custom.output);
    break;
    case CASS_VALUE_TYPE_UNKNOWN:
    default:
      return CASS_ERROR_LIB_BAD_PARAMS;
  }

  return rc;
}

CassError
xcass_bind(xcass_query_t *query, ...) {

  CassError rc = CASS_OK;
  va_list aq, ap;

  va_start(aq, query);
  va_copy(ap, aq);

  int i;
  for(i = 0; i < query->argc; i++) {
    void *p = va_arg(ap, void *);
    if(!p) {
      va_arg(aq, void *);
      rc = cass_statement_bind_null(query->statement, i);
    }
    else
      rc = xcass_query_ibind(query, i, aq);

    if(rc < 0)
      break;
  }

  va_end(ap);
  va_end(aq);
  return rc;
}

CassError
xcass_ibind(xcass_query_t *query,
            unsigned int index, ...) {

  CassError rc = CASS_OK;
  va_list aq, ap;

  va_start(aq, index);
  va_copy(ap, aq);

  if(!va_arg(ap, void *))
    rc = cass_statement_bind_null(query->statement, index);
  else
    rc = xcass_query_ibind(query, index, aq);

  va_end(ap);
  va_end(aq);
  return rc;
}

int
xcass_query_parse(xcass_query_t *query,
                  const char *cql) {

  xcass_type_mapping_t *types = NULL;
  int argc = 0;

  query->cql = (char *) malloc(strlen(cql) + 1);
  memset(query->cql, 0, strlen(cql) + 1);

#define TRIM(st, le)                                 \
  do {                                               \
    while(*st && (*st == ' ' || *st == ','))         \
      st++;                                          \
    while(st[le] && st[le] != ' ' && st[le] != ','   \
        && st[le] != XCASS_FIELD_DELIM_RIGHT)        \
      le++;                                          \
  } while(0);

  char *p = (char *) cql;
  int qt = 0;
  int ndx = 0;

  while(*p) {

    // quotes
    if(*p == '\'' && *(p-1) != '\\')
      qt = !qt;

    char *pp = strchr(p, XCASS_FIELD_DELIM_RIGHT);
    if(!qt && *p == XCASS_FIELD_DELIM_LEFT && *(p+1) != '=' && pp) {

      // collection ?
      char **col = (char **) xcass_collection_types;
      while(*col) {
        char *s = *col;
        s += strlen(s)-1;
        while(*s) {
          char c = *((p-1)-(strlen(s)-1));
          if(!c || c != *s--)
            break;
        }
        if(!strlen(s))
          break;
        col++;
      }

      int sz = 0;
      char *f = p+1;
      TRIM(f, sz);
      char *key = strndup(f, sz);

      CassValueType ktype = xcass_get_type_byname(key);
      free(key);
      if(ktype == CASS_VALUE_TYPE_UNKNOWN) {
        fprintf(stderr, "(xcass_query) unknown type '%s'\n", f);
        free(types);
        free(query->cql);
        return -1;
      }

      types = (xcass_type_mapping_t *) realloc(types, (argc + 1)
                * sizeof(xcass_type_mapping_t));

      if(*col) {
        types[argc].type = xcass_get_type_byname(*col);
        ndx -= strlen(*col);
      }
      else
        types[argc].type = ktype;

      argc++;
      p += pp-p;
      query->cql[ndx++] = '?';
    }
    else {
      query->cql[ndx++] = *p;
    }
    p++;
  }

  query->types = types;
  query->argc = argc;

  return argc;
}

xcass_query_t *
xcass_prepare(xcass_t *xs,
              const char *cql) {

  xcass_query_t *query = xcass_query_new(xs);

  int argc = xcass_query_parse(query, cql);
  if(argc < 0)
    goto fail;

  CassFuture *future = cass_session_prepare(xs->session,
                                            cass_string_init(query->cql));
  cass_future_wait(future);

  CassError rc = cass_future_error_code(future);
  if(rc != CASS_OK) {
    cass_future_free(future);
    goto fail;
  }

  query->prepared = cass_future_get_prepared(future);
  cass_future_free(future);

  return query;

  fail:
    xcass_query_free(query);
    return NULL;
}

xcass_query_t *
xcass_query(xcass_t *xs,
            const char *fmt, ...) {

  va_list aq;
  xcass_query_t *query = xcass_query_new(xs);

  int argc = xcass_query_parse(query, fmt);
  if(argc < 0)
    goto fail;

  query->statement = cass_statement_new(cass_string_init(query->cql),
                                        query->argc);

  if(argc) {
    va_start(aq, fmt);
    int i;
    for(i = 0; i < query->argc; i++) {
      if(xcass_query_ibind(query, i, aq) != CASS_OK) {
        va_end(aq);
        goto fail;
      }
    }
    va_end(aq);
  }

  return query;

  fail:
    xcass_query_free(query);
    return NULL;
}

xcass_query_t *
xcass_query_nobind(xcass_t *xs,
                   const char *cql) {

  xcass_query_t *query = xcass_query_new(xs);
  query->cql = strdup(cql);
  query->argc = 0;
  query->statement = cass_statement_new(cass_string_init(query->cql), 0);
  return query;
}

CassStatement *
xcass_new_statement(xcass_query_t *query) {

  if(query->statement)
    cass_statement_free(query->statement);

  if(query->prepared)
    query->statement = cass_prepared_bind(query->prepared);
  else
    query->statement = cass_statement_new(cass_string_init(query->cql),
                                          query->argc);

  return query->statement;
}

CassError
xcass_execute(xcass_t *xs,
              xcass_query_t *query) {

  CassError rc = CASS_OK;
  cass_statement_set_consistency(query->statement, query->consistency);
  cass_statement_set_paging_size(query->statement, query->page_size);

  CassFuture *future = cass_session_execute(xs->session, query->statement);
  cass_future_wait(future);
  rc = cass_future_error_code(future);
  if(rc != CASS_OK) {
    cass_future_free(future);
    return rc;
  }

  query->result = cass_future_get_result(future);
  cass_future_free(future);
  return rc;
}

int
xcass_query_has_more_pages(xcass_query_t *query) {

    if(cass_result_has_more_pages(query->result)) {
      cass_statement_set_paging_state(query->statement, query->result);
      cass_result_free(query->result);
      query->result = NULL;
      return 1;
    }
    return 0;
}


text:
/**
 * Hugo Lindström (C) 2013
 * huli1000
 */
package com.itm.projekt.Adapters;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import com.itm.projekt.Interfaces.ItemInterface;

import java.util.ArrayList;

/**
 * BaseAdapter
 * @param <T>
 */
abstract public class BaseArrayAdapter<T> extends ArrayAdapter<T> implements ItemInterface<T> {

    private final Context mContext;
    private final ArrayList<T> mData;
    private final int mLayoutResourceId;
    private final LayoutInflater mInflater;

    public BaseArrayAdapter(Context context, int layoutResourceId, ArrayList<T> data) {
        super(context, layoutResourceId, data);
        mData = data;
        mContext = context;
        mLayoutResourceId = layoutResourceId;
        mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public ArrayAdapter<T> getAdapter() {
        return this;
    }

    public int getLayoutResourceId() {
        return mLayoutResourceId;
    }

    public LayoutInflater getInflater() {
        return mInflater;
    }

    public Context getContext() {
        return mContext;
    }

    public void addItem(T item) {
        mData.add(item);
        notifyDataSetChanged();
    }

    public void removeItem(T item) {
        mData.remove(item);
        notifyDataSetChanged();
    }

    public void removeItem(int pos) {
        mData.remove(pos);
        notifyDataSetChanged();
    }

    public final ArrayList<T> getData() {
        return mData;
    }

    protected void addItemNoNotify(T item) {
        mData.add(item);
    }

    public int getCount() {
        return mData.size();
    }

    public T getItem(int position) {
        return mData.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder;

        if(convertView == null) {
            convertView = mInflater.inflate(mLayoutResourceId, parent, false);
            holder = getViewHolder(convertView);
            convertView.setTag(holder);
        }
        else {
            holder = (ViewHolder)convertView.getTag();
        }
        return updateView(position, holder, convertView);
    }

    protected View convertView(ViewGroup parent) {
        return mInflater.inflate(getLayoutResourceId(), parent, false);
    }

    protected View updateView(int position, ViewHolder holder, View view) {
        updateViewHolder(holder, mData.get(position));
        return view;
    }
}


text:
import Config from '../config';

// ——————————————————————————————————————————————————
// Synapse
// ——————————————————————————————————————————————————

class Synapse {
  constructor(neuron, receptor) {
    this.neuron = neuron;
    this.receptor = receptor;
    this.strength = 0;
    this.connected = false;
    this.onNeuronPulsed = this.onNeuronPulsed.bind(this);
    this.neuron.pulsed.add(this.onNeuronPulsed);
    this.pulses = [];
  }
  update(dt) {
    const dx = this.receptor.x - this.neuron.x;
    const dy = this.receptor.y - this.neuron.y;
    const distSq = dx * dx + dy * dy;
    const radii = this.neuron.radius + this.receptor.radius;
    const range = Config.transmissionRange.value + radii;
    if (distSq <= range * range) {
      if (!this.connected) {
        this.neuron.connections++;
        this.connected = true;
      }
      this.length = Math.sqrt(distSq);
      this.strength = Math.pow(1 - this.length / range, 0.66);
      for (let i = this.pulses.length - 1; i >= 0; i--) {
        this.pulses[i].countdown -= dt;
        if (this.pulses[i].countdown <= 0) {
          this.pulses.splice(i, 1);
          this.receptor.activate(this.neuron.octave);
        }
      }
    } else if (this.connected) {
      this.neuron.connections--;
      this.connected = false;
      if (this.pulses.length) {
        this.pulses.length = 0;
      }
    }
  }
  onNeuronPulsed(neuron) {
    if (this.connected) {
      const delay = this.length / Config.transmissionSpeed.value;
      this.pulses.push({
        countdown: delay,
        delay
      });
    }
  }
}

// ——————————————————————————————————————————————————
// Exports
// ——————————————————————————————————————————————————

export default Synapse;