text:
/**
 * Element
 * @param {String} tagName
 * @constructor
 */
var Element_ = function(tagName) {
    this.node_ = document.createElement(tagName);
};

Element_.prototype = {
    id: function(id) {this.node_.id = id; return this;},
    css: function(cName) {
      var cList = cName.split(' ');
      for (var i = 0; i < cList.length; i++) {
        if (cList[i]) this.node_.classList.add(cList[i]);
      }
      return this;
    },
    type: function(tName) {this.node_.type = tName; return this;},
    attr: function(aName, value) {this.node_.setAttribute(aName, value); return this;},
    insertToLast: function(node) {node.appendChild(this.node_);return this;},
    insertToFirst: function(node) {node.insertBefore(this.node_, node.firstChild);return this;},
    insertTo: function(node) {return this.insertToLast(node);},
    innerText: function(text) {this.node_.innerHTML = text; return this;},
    bgColor: function(value) {this.node_.style.backgroundColor = value; return this;},
    shadow: function(value,hide) {return this;},  // TODO: implement shadow
    done: function() {return this.node_;}
};


text:
namespace ndnboost { namespace mpl {

template<>
struct pop_front_impl< aux::vector_tag >
{
    template< typename Vector > struct apply
    {
        typedef v_mask<Vector,1> type;
    };
};

}}

#endif // NDNBOOST_MPL_CFG_TYPEOF_BASED_SEQUENCES

#endif // NDNBOOST_MPL_VECTOR_AUX_POP_FRONT_HPP_INCLUDED

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace lrcore\libraries;

/**
 * @author Louis Racicot
 * @version 1.0
 * @date 2011-11-30
 */
interface DataStorage
{
    public function getData($id);
    public function purgeData($id);
}


text:
//    Openbravo POS is a point of sales application designed for touch screens.
//    Copyright (C) 2007-2009 Openbravo, S.L.
//    http://www.openbravo.com/product/pos
//
//    This file is part of Openbravo POS.
//
//    Openbravo POS 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, either version 3 of the License, or
//    (at your option) any later version.
//
//    Openbravo POS 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 Openbravo POS.  If not, see <http://www.gnu.org/licenses/>.

package com.openbravo.data.loader;

import com.openbravo.basic.BasicException;

public class SerializerWriteLong implements SerializerWrite<Long> {

    public static final SerializerWrite INSTANCE = new SerializerWriteLong();

    /** Creates a new instance of SerializerWriteString */
    private SerializerWriteLong() {
    }

    public void writeValues(DataWrite dp, Long obj) throws BasicException {
        Datas.LONG.setValue(dp, 1, obj);
    }
}


text:
@interface GameHomeViewController : UIViewController

@end


text:
package phone.semiconductors;

/**
 * Created by krishan on 8/13/15.
 */
public class Ram {
    int memory;

    public Ram(int memory) {
        this.memory = memory;
    }

    @Override
    public String toString() {
        return "Ram{" +
                "memory=" + memory +
                '}';
    }
}


text:
using System.IO;
using SurpassStandard.Utils;

namespace Surpass.Storage {
	///
	/// File entry extension methods

	/// 文件的扩展函数

	///
	public static class IFileEntryExtensions {
		///
		/// Read file into string

		/// 读取文件内容到字符串

		///
		/// <param name="entry">File entry</param>
		/// <returns></returns>
		public static string ReadAllText(this IFileEntry entry) {
			using (var stream = entry.OpenRead())
			using (var reader = new StreamReader(stream)) {
				return reader.ReadToEnd();
			}
		}

		///
		/// Write string to file

		/// 写入字符串到文件

		///
		/// <param name="entry">File entry</param>
		/// <param name="value">String value</param>
		public static void WriteAllText(this IFileEntry entry, string value) {
			using (var stream = entry.OpenWrite())
			using (var writer = new StreamWriter(stream)) {
				writer.Write(value);
			}
		}

		///
		/// Append string to file

		/// 追加字符串到文件末尾

		///
		/// <param name="entry">File entry</param>
		/// <param name="value">String value</param>
		public static void AppendAllText(this IFileEntry entry, string value) {
			using (var stream = entry.OpenAppend())
			using (var writer = new StreamWriter(stream)) {
				writer.Write(value);
			}
		}

		///
		/// Read file into byte array

		/// 读取文件到字节数组

		///
		/// <param name="entry">File entry</param>
		/// <returns></returns>
		public static byte[] ReadAllBytes(this IFileEntry entry) {
			using (var stream = entry.OpenRead())
			using (var memoryStream = new MemoryStream()) {
				stream.CopyTo(memoryStream);
				return memoryStream.ToArray();
			}
		}

		///
		/// Write byte array to file

		/// 写入字节数组到文件

		///
		/// <param name="entry">File entry</param>
		/// <param name="bytes">Byte array</param>
		public static void WriteAllBytes(this IFileEntry entry, byte[] bytes) {
			using (var stream = entry.OpenWrite()) {
				stream.Write(bytes, 0, bytes.Length);
			}
		}

	    ///
	    /// 压缩文件
	    ///
	    /// <param name="entry"></param>
	    /// <param name="zipedFile"></param>
	    /// <param name="password"></param>
	    /// <returns></returns>
	    public static bool Zip(this IFileEntry entry, string zipedFile, string password = null)
	    {
	        //return ZipUtils.ZipFile(entry.UniqueIdentifier, zipedFile, password);
	        return true;
	    }

        ///
        /// 解压缩文件
        ///
        /// <param name="entry"></param>
        /// <param name="zipedFolder">请使用PathUtils.SecureCombine()</param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static bool UnZip(this IFileEntry entry, string zipedFolder, string password = null)
        {
            //return ZipUtils.UnZip(entry.UniqueIdentifier, zipedFolder, password);
            return true;
        }

    }
}


text:
package ru.noties.scrollable.sample;

import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.View;

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

import ru.noties.scrollable.CanScrollVerticallyDelegate;
import ru.noties.scrollable.OnScrollChangedListener;
import ru.noties.scrollable.ScrollableLayout;

public class MainActivity extends BaseActivity implements ConfigurationFragmentCallbacks {

    private static final String ARG_LAST_SCROLL_Y = "arg.LastScrollY";

    private ScrollableLayout mScrollableLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final View header = findViewById(R.id.header);
        final TabsLayout tabs = findView(this, R.id.tabs);

        mScrollableLayout = findView(this, R.id.scrollable_layout);
        mScrollableLayout.setDraggableView(tabs);

        final ViewPager viewPager = findView(this, R.id.view_pager);
        final ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager(), getResources(), getFragments());
        viewPager.setAdapter(adapter);

        tabs.setViewPager(viewPager);

        mScrollableLayout.setCanScrollVerticallyDelegate(new CanScrollVerticallyDelegate() {
            @Override
            public boolean canScrollVertically(int direction) {
                return adapter.canScrollVertically(viewPager.getCurrentItem(), direction);
            }
        });

        mScrollableLayout.setOnScrollChangedListener(new OnScrollChangedListener() {
            @Override
            public void onScrollChanged(int y, int oldY, int maxY) {

                final float tabsTranslationY;
                if (y < maxY) {
                    tabsTranslationY = .0F;
                } else {
                    tabsTranslationY = y - maxY;
                }

                tabs.setTranslationY(tabsTranslationY);

                header.setTranslationY(y / 2);
            }
        });

        if (savedInstanceState != null) {
            final int y = savedInstanceState.getInt(ARG_LAST_SCROLL_Y);
            mScrollableLayout.post(new Runnable() {
                @Override
                public void run() {
                    mScrollableLayout.scrollTo(0, y);
                }
            });
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(ARG_LAST_SCROLL_Y, mScrollableLayout.getScrollY());
        super.onSaveInstanceState(outState);
    }

    private List<BaseFragment> getFragments() {

        final FragmentManager manager = getSupportFragmentManager();
        final ColorRandomizer colorRandomizer = new ColorRandomizer(getResources().getIntArray(R.array.fragment_colors));
        final List<BaseFragment> list = new ArrayList<>();

        ConfigurationFragment configurationFragment
                = (ConfigurationFragment) manager.findFragmentByTag(ConfigurationFragment.TAG);
        if (configurationFragment == null) {
            configurationFragment = ConfigurationFragment.newInstance(colorRandomizer.next());
        }

        ListViewFragment listViewFragment
                = (ListViewFragment) manager.findFragmentByTag(ListViewFragment.TAG);
        if (listViewFragment == null) {
            listViewFragment = ListViewFragment.newInstance(colorRandomizer.next());
        }

        ScrollViewFragment scrollViewFragment
                = (ScrollViewFragment) manager.findFragmentByTag(ScrollViewFragment.TAG);
        if (scrollViewFragment == null) {
            scrollViewFragment = ScrollViewFragment.newInstance(colorRandomizer.next());
        }

        RecyclerViewFragment recyclerViewFragment
                = (RecyclerViewFragment) manager.findFragmentByTag(RecyclerViewFragment.TAG);
        if (recyclerViewFragment == null) {
            recyclerViewFragment = RecyclerViewFragment.newInstance(colorRandomizer.next());
        }

        Collections.addAll(list, configurationFragment, listViewFragment, scrollViewFragment, recyclerViewFragment);

        return list;
    }

    @Override
    public void onFrictionChanged(float friction) {
        mScrollableLayout.setFriction(friction);
    }

    @Override
    public void openDialog(float friction) {
        final ScrollableDialog dialog = ScrollableDialog.newInstance(friction);
        dialog.show(getSupportFragmentManager(), null);
    }

    private static class ViewPagerAdapter extends FragmentPagerAdapterExt {

        private final Resources mResources;
        private final List<BaseFragment> mFragments;

        public ViewPagerAdapter(FragmentManager fm, Resources r, List<BaseFragment> fragments) {
            super(fm);
            this.mResources = r;
            this.mFragments = fragments;
        }

        @Override
        public BaseFragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments != null ? mFragments.size() : 0;
        }

        @Override
        public String makeFragmentTag(int position) {
            return mFragments.get(position).getSelfTag();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragments.get(position).getTitle(mResources);
        }

        boolean canScrollVertically(int position, int direction) {
            return getItem(position).canScrollVertically(direction);
        }
    }

}


text:
Governator is a library of extensions and utilities that enhance Google Guice with
lifecycle management.  The concept of lifecycle management has two aspects here.
1.  Injector lifecycle management via LifecycleListener
2.  Object lifecycle managmenet via @PostConstruct and @PreDestroy.

Governator also provides hooks through which additional features may be added to
lifecycle management at the appropriate places. (see LifecycleFeature)

## Creating the Injector
------------------------
Governator provides a simple builder DSL on top of Guice's built in SPI to,
1.  provide a more readable fluent code
2.  Make injector creation policy driven
3.  constructing the list of modules provided to Guice.

```java
LifecycleInjector injector = InjectorBuilder.fromModules(new MyApplicationModule());
```

Once created the container can interact with the LifecycleInjector's lifecycle methods
directly or asynchronously by registering a LifecycleListener in a Guice module.  The
injector's lifecycle may be terminated either by calling LifecycleInjector.shutdown()
or by injecting LifecycleShutdownSignal and calling LifecycleShutdownSignal.shutdown().

For example, to block until the injector's lifecycle completes,

```java
injector.awaitTermination();
```

Or to get asynchronous notification of termination
```java
injector.addListener(new DefaultLifecycleListener() {
        public void onShutdown() {
            // Do your shutdown handling here
        }
    });
```

To shutdown the injector from outside of Guice call,
```java
injector.shutdown();
```

Or to trigger shutdown from an Injector managed class,
```java
@Singleton
public class SomeServiceThatGetsAShutdownSignal {
    private final LifecycleShutdownSignal signal;

    @Inject
    public SomeServiceThatGetsAShutdownSignal(LifecycleShutdownSignal signal) {
    	this.signal = signal;
    }

    private void someShutdownInvokingCode() {
        this.signal.shutdown();
    }
}
```

You can also enable a JVM shutdown hook by adding ShutdownHookModule to Guice's list of modules
```java
Governator.createInjector(new ShutdownHookModule(), new MyApplicationModule());
```

## Injector lifecycle
----------------------

When using DI all operations should be performed within the context DI such that initialization
is done via dependency injection and eager singleton behavior. As long as eager singletons have
been properly registered the entire application should be functional once the injector has been
created.  Sometimes, however, it may be necessary to perform post injector creation operations,
such as registering that the application is ready to serve traffic.  This can be done by implementing
the LifecycleInterface from any eager singleton.

```java
@Singleton
public class MyApplication extends AbstractLifecycleListener {
    @Override
    public void onStarted() {
        applicationStatus.markAsUp();
    }
}
```

## Debugging Guice
----------------------

Governator includes several utilities to help debug problems and get insight into injector creation.

### TracingProvisionListener

Sometimes Guice fails to create the injector and provides little information about which class or object
creation path resulted in failure.  Enabling the TracingProvisionListener will result in class names
being emitted to standard output (can be customized to different outputs) and indented to give a clear
path to the path through which objects were provisioned.

### ProvisionDebugModule

The ProvisionDebugModule tracks metrics about object instantiation and retains this information after
the injector has been created.  The information is later accessible via ProvisionMetrics.  This can
be used to provide a UI that gives a visual representation of the application bootstrapping processes,
helping identify slow initialization paths.

##

## Using Governator with main()
----------------------------------
```java
public class MyApplication {
	public static void main(String[] args) throws Exception {
		InjectorBuilder
		    .fromModules(new ShutdownHookModule(), new MyApplicationModule())
			.awaitTermination();
	}
}
```

## Using Governator with Tomcat
----------------------------
```java
public class StartServer extends GovernatorServletContextListener
{
    @Override
    protected Injector createInjector() {
        return InjectorBuilder.fromModules(
        	new ShutdownHookModule(),
            new JerseyServletModule() {
                @Override
                protected void configureServlets() {
                    serve("/REST/*").with(GuiceContainer.class);
                    bind(GuiceContainer.class).asEagerSingleton();

                    bind(MyResource.class).asEagerSingleton();
                }
            }
        ).createInjector();
    }
}
```

```xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <filter>
        <filter-name>guiceFilter</filter-name>
        <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>guiceFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>StartServer</listener-class>
    </listener>
</web-app>
```

## Using Governator with Jetty
---------------------------
```java
public class MyApplication {
	public static void main(String[] args) throws Exception {
		Governator.createInjector(
		    new JettyModule(),
        	new ShutdownHookModule(),
            new JerseyServletModule() {
                @Override
                protected void configureServlets() {
                    serve("/REST/*").with(GuiceContainer.class);
                    bind(GuiceContainer.class).asEagerSingleton();

                    bind(MyResource.class).asEagerSingleton();
                }
            }
        ).awaitTermination();
    }
}
```

# Using governator with JUnit
--------------------------------
TBD

# Building
-----------

Governator is built via Gradle (http://www.gradle.org). To build from the command line:
    ./gradlew build

# Artifacts
----------

Governator binaries are published to Maven Central. Please see the docs for details.

# Author
-----------

Eran Landau (mailto:elandau@netflix.com)

# License
-----------

Copyright 2015 Netflix, Inc.

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.


text:
[![License badge](https://img.shields.io/badge/license-Apache2-green.svg)](http://www.apache.org/licenses/LICENSE-2.0)
[![Twitter](https://img.shields.io/badge/follow-@boni_gg-green.svg)](https://twitter.com/boni_gg)

# Web Programming Examples [![][Logo]][GitHub Repository]

This project contains code examples for web applications using Java in the server-side.

## List of technologies

The main technologies involved in these examples are:

* Spring : Java Framework. These examples are base on Spring Boot, Spring MVC, Spring Data, Spring Security, and Spring Test.
* Thymeleaf : Template engine for Spring MVC.
* MySQL : Relational database.
* MongoDB : NoSQLdatabase.
* JUnit : Unit testing framework.
* Selenium : Web testing framework.
* Retrofit : HTTP client for Java (REST services).
* Ionic : Framework for hybrid apps development.
* Angular : Web application framework.
* TypeScript : Superset of EcmaScript 6 adding static typing.
* Standard client-side technologies : HTML5, CSS3, JavaScript.
* Bootstrap : CSS framework for developing responsive web sites.

## About

This is a project made by [Boni Garcia], Assistant Professor at [U-tad] and [Universidad Rey Juan Carlos]. Copyright © 2015-2018.

[U-tad]: http://www.u-tad.com/
[Universidad Rey Juan Carlos]: https://www.urjc.es/
[Boni Garcia]: http://bonigarcia.github.io/
[Logo]: http://bonigarcia.github.io/img/web-programming-examples.png
[GitHub Repository]: https://github.com/bonigarcia/web-programming-examples


text:
package org.kie.api.remote;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

/**
 * This annotation should be used by users to specify (user-defined) classes that
 * should be available to remote services (REST, JMS, WS) when using a workbench.
 *

 * A user will use this annotation on a class that's either part of a kjar or deployment
 * or on a class that is a dependency of the aforementioned kjar or deployment. When this deployment
 * is deployed, the workbench will scan the deployment and the dependency tree of the deployment
 * for classes marked with this annotation.
 *

 * While classes at the top level in the deployment itself marked with the appropriate JAXB annotations
 * are always available for use with the remote services (regardless of whether the classes
 * are annotated with the {@code @Remotable} annotation, in the dependency tree of the deployment,
 * only classes marked with this annotation (and with the appropriate JAXB annotations)
 * will be able to be used with the workbench's remote services.
 */

@Inherited
@Documented
@Retention(RUNTIME)
@Target({ElementType.TYPE})
public @interface Remotable {

}


text:
package mongo

import (
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"

	"fmt"
	"github.com/cayleygraph/cayley/graph"
	"github.com/cayleygraph/cayley/graph/iterator"
	"github.com/cayleygraph/cayley/quad"
)

var _ graph.Iterator = &LinksTo{}

// LinksTo is a MongoDB-dependent version of a LinksTo iterator. Like the normal
// LinksTo, it represents a set of links to a set of nodes, represented by its
// subiterator. However, this iterator may often be faster than the generic
// LinksTo, as it can use the secondary indices in Mongo as features within the
// Mongo query, reducing the size of the result set and speeding up iteration.
type LinksTo struct {
	uid        uint64
	collection string
	tags       graph.Tagger
	qs         *QuadStore
	primaryIt  graph.Iterator
	dir        quad.Direction
	nextIt     *mgo.Iter
	result     graph.Value
	runstats   graph.IteratorStats
	lset       []graph.Linkage
	err        error
}

// NewLinksTo constructs a new indexed LinksTo iterator for Mongo around a direction
// and a subiterator of nodes.
func NewLinksTo(qs *QuadStore, it graph.Iterator, collection string, d quad.Direction, lset []graph.Linkage) *LinksTo {
	return &LinksTo{
		uid:        iterator.NextUID(),
		qs:         qs,
		primaryIt:  it,
		dir:        d,
		nextIt:     nil,
		lset:       lset,
		collection: collection,
	}
}

func (it *LinksTo) buildConstraint() bson.M {
	constraint := bson.M{}
	// TODO(barakmich): Currently this only works for an individual linkage in any direction.
	for _, link := range it.lset {
		constraint[link.Dir.String()] = link.Value
	}
	return constraint
}

func (it *LinksTo) buildIteratorFor(d quad.Direction, val graph.Value) *mgo.Iter {
	constraint := it.buildConstraint()
	constraint[d.String()] = string(val.(NodeHash))
	return it.qs.db.C(it.collection).Find(constraint).Iter()
}

func (it *LinksTo) UID() uint64 {
	return it.uid
}

func (it *LinksTo) Tagger() *graph.Tagger {
	return &it.tags
}

// Return the direction under consideration.
func (it *LinksTo) Direction() quad.Direction { return it.dir }

// Tag these results, and our subiterator's results.
func (it *LinksTo) TagResults(dst map[string]graph.Value) {
	it.tags.TagResult(dst, it.Result())

	it.primaryIt.TagResults(dst)
}

// Optimize the LinksTo, by replacing it if it can be.
func (it *LinksTo) Optimize() (graph.Iterator, bool) {
	return it, false
}

func (it *LinksTo) Next() bool {
	var result struct {
		ID      string     `bson:"_id"`
		Added   []bson.Raw `bson:"Added"`
		Deleted []bson.Raw `bson:"Deleted"`
	}
	graph.NextLogIn(it)
next:
	for {
		it.runstats.Next += 1
		if it.nextIt != nil && it.nextIt.Next(&result) {
			it.runstats.ContainsNext += 1
			if it.collection == "quads" && len(result.Added) <= len(result.Deleted) {
				continue next
			}
			it.result = QuadHash(result.ID)
			return graph.NextLogOut(it, true)
		}

		if it.nextIt != nil {
			// If there's an error in the 'next' iterator, we save it and we're done.
			it.err = it.nextIt.Err()
			if it.err != nil {
				return false
			}

		}
		// Subiterator is empty, get another one
		if !it.primaryIt.Next() {
			// Possibly save error
			it.err = it.primaryIt.Err()

			// We're out of nodes in our subiterator, so we're done as well.
			return graph.NextLogOut(it, false)
		}
		if it.nextIt != nil {
			it.nextIt.Close()
		}
		it.nextIt = it.buildIteratorFor(it.dir, it.primaryIt.Result())

		// Recurse -- return the first in the next set.
	}
}

func (it *LinksTo) Err() error {
	return it.err
}

func (it *LinksTo) Result() graph.Value {
	return it.result
}

func (it *LinksTo) Close() error {
	var err error
	if it.nextIt != nil {
		err = it.nextIt.Close()
	}

	_err := it.primaryIt.Close()
	if _err != nil && err == nil {
		err = _err
	}

	return err
}

func (it *LinksTo) NextPath() bool {
	ok := it.primaryIt.NextPath()
	if !ok {
		it.err = it.primaryIt.Err()
	}
	return ok
}

func (it *LinksTo) Type() graph.Type {
	return "mongo-linksto"
}

func (it *LinksTo) Clone() graph.Iterator {
	m := NewLinksTo(it.qs, it.primaryIt.Clone(), it.collection, it.dir, it.lset)
	m.tags.CopyFrom(it)
	return m
}

func (it *LinksTo) Contains(val graph.Value) bool {
	graph.ContainsLogIn(it, val)
	it.runstats.Contains += 1

	for _, link := range it.lset {
		dval := it.qs.QuadDirection(val, link.Dir)
		if dval != link.Value {
			return graph.ContainsLogOut(it, val, false)
		}
	}

	node := it.qs.QuadDirection(val, it.dir)
	if it.primaryIt.Contains(node) {
		it.result = val
		return graph.ContainsLogOut(it, val, true)
	}
	it.err = it.primaryIt.Err()
	return graph.ContainsLogOut(it, val, false)
}

func (it *LinksTo) String() string {
	return fmt.Sprintf("MongoLinks(%v)", it.lset)
}

func (it *LinksTo) Reset() {
	it.primaryIt.Reset()
	if it.nextIt != nil {
		it.nextIt.Close()
	}
	it.nextIt = nil
}

// Return a guess as to how big or costly it is to next the iterator.
func (it *LinksTo) Stats() graph.IteratorStats {
	subitStats := it.primaryIt.Stats()
	// TODO(barakmich): These should really come from the quadstore itself
	fanoutFactor := int64(20)
	checkConstant := int64(1)
	nextConstant := int64(2)

	size := fanoutFactor * subitStats.Size
	csize, _ := it.qs.getSize(it.collection, it.buildConstraint())
	if size > csize {
		size = csize
	}

	return graph.IteratorStats{
		NextCost:     nextConstant + subitStats.NextCost,
		ContainsCost: checkConstant + subitStats.ContainsCost,
		Size:         size,
		ExactSize:    false,
		Next:         it.runstats.Next,
		Contains:     it.runstats.Contains,
		ContainsNext: it.runstats.ContainsNext,
	}
}

func (it *LinksTo) Size() (int64, bool) {
	st := it.Stats()
	return st.Size, st.ExactSize
}

// Return a list containing only our subiterator.
func (it *LinksTo) SubIterators() []graph.Iterator {
	return []graph.Iterator{it.primaryIt}
}


text:
package io.swagger.client.api;

import io.swagger.client.ApiException;
import io.swagger.client.ApiClient;
import io.swagger.client.Configuration;

import io.swagger.client.model.*;

import java.util.*;

import io.swagger.client.model.Conversion;
import java.math.BigDecimal;
import io.swagger.client.model.Status;

import com.sun.jersey.multipart.FormDataMultiPart;
import com.sun.jersey.multipart.file.FileDataBodyPart;

import javax.ws.rs.core.MediaType;

import java.io.File;
import java.util.Map;
import java.util.HashMap;

public class InformationApi {
  private ApiClient apiClient;

  public InformationApi() {
    this(Configuration.getDefaultApiClient());
  }

  public InformationApi(ApiClient apiClient) {
    this.apiClient = apiClient;
  }

  public ApiClient getApiClient() {
    return apiClient;
  }

  public void setApiClient(ApiClient apiClient) {
    this.apiClient = apiClient;
  }

  /**
   * Get a list of the valid conversions.
   * Gets a list of the valid conversions that can be made with the API. For each conversion is also shown the available options for that specific type of conversion.\n\nThis conversions can be added to a Job through the specific endpoint or in the information given to create the new Job.\n
   * @param category Category for the conversion.
   * @param target Target for for the conversion.
   * @param page Pagination for list of elements.
   * @return List<Conversion>
   */
  public List<Conversion> conversionsGet (String category, String target, BigDecimal page) throws ApiException {
    Object postBody = null;

    // create path and map variables
    String path = "/conversions".replaceAll("\\{format\\}","json");

    // query params
    Map<String, String> queryParams = new HashMap<String, String>();
    Map<String, String> headerParams = new HashMap<String, String>();
    Map<String, String> formParams = new HashMap<String, String>();

    if (category != null)
      queryParams.put("category", apiClient.parameterToString(category));
    if (target != null)
      queryParams.put("target", apiClient.parameterToString(target));
    if (page != null)
      queryParams.put("page", apiClient.parameterToString(page));

    final String[] accepts = {

    };
    final String accept = apiClient.selectHeaderAccept(accepts);

    final String[] contentTypes = {

    };
    final String contentType = apiClient.selectHeaderContentType(contentTypes);

    if(contentType.startsWith("multipart/form-data")) {
      boolean hasFields = false;
      FormDataMultiPart mp = new FormDataMultiPart();

      if(hasFields)
        postBody = mp;
    }
    else {

    }

    try {
      String[] authNames = new String[] {  };
      String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
      if(response != null){
        return (List<Conversion>) apiClient.deserialize(response, "array", Conversion.class);
      }
      else {
        return null;
      }
    } catch (ApiException ex) {
      throw ex;
    }
  }

  /**
   * Get a list of the valid statuses.
   * The endpoint provide a list of all available status that the Job may have during the process as a description of the status.
   * @return List<Status>
   */
  public List<Status> statusesGet () throws ApiException {
    Object postBody = null;

    // create path and map variables
    String path = "/statuses".replaceAll("\\{format\\}","json");

    // query params
    Map<String, String> queryParams = new HashMap<String, String>();
    Map<String, String> headerParams = new HashMap<String, String>();
    Map<String, String> formParams = new HashMap<String, String>();

    final String[] accepts = {

    };
    final String accept = apiClient.selectHeaderAccept(accepts);

    final String[] contentTypes = {

    };
    final String contentType = apiClient.selectHeaderContentType(contentTypes);

    if(contentType.startsWith("multipart/form-data")) {
      boolean hasFields = false;
      FormDataMultiPart mp = new FormDataMultiPart();

      if(hasFields)
        postBody = mp;
    }
    else {

    }

    try {
      String[] authNames = new String[] {  };
      String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
      if(response != null){
        return (List<Status>) apiClient.deserialize(response, "array", Status.class);
      }
      else {
        return null;
      }
    } catch (ApiException ex) {
      throw ex;
    }
  }

}


text:
"use strict";

module.exports = {
    //每一个新的loader都在这里注册
    "jsLoader": require("./jsLoader").Mixin,
    "es6Loader": require("./es6Loader").Mixin,
    "reactLoader": require("./reactLoader").Mixin,
    "vueLoader": require("./vueLoader").Mixin,
    "react-es6Loader": require("./reactEs6Loader").Mixin
};


text:
if(!dojo._hasResource["dojox.drawing.plugins.tools.Pan"]){
dojo._hasResource["dojox.drawing.plugins.tools.Pan"]=true;
dojo.provide("dojox.drawing.plugins.tools.Pan");
dojo.require("dojox.drawing.plugins._Plugin");
dojox.drawing.plugins.tools.Pan=dojox.drawing.util.oo.declare(dojox.drawing.plugins._Plugin,function(_1){
this.domNode=_1.node;
var _2;
this.toolbar=_1.scope;
this.connect(this.toolbar,"onToolClick",this,function(){
this.onSetPan(false);
});
this.connect(this.button,"onClick",this,"onSetPan");
this.connect(this.keys,"onKeyUp",this,"onKeyUp");
this.connect(this.keys,"onKeyDown",this,"onKeyDown");
this.connect(this.anchors,"onAnchorUp",this,"checkBounds");
this.connect(this.stencils,"register",this,"checkBounds");
this.connect(this.canvas,"resize",this,"checkBounds");
this.connect(this.canvas,"setZoom",this,"checkBounds");
this.connect(this.canvas,"onScroll",this,function(){
if(this._blockScroll){
this._blockScroll=false;
return;
}
_2&&clearTimeout(_2);
_2=setTimeout(dojo.hitch(this,"checkBounds"),200);
});
this._mouseHandle=this.mouse.register(this);
},{selected:false,type:"dojox.drawing.plugins.tools.Pan",onPanUp:function(_3){
if(_3.id==this.button.id){
this.onSetPan(false);
}
},onKeyUp:function(_4){
if(_4.keyCode==32){
this.onSetPan(false);
}
},onKeyDown:function(_5){
if(_5.keyCode==32){
this.onSetPan(true);
}
},onSetPan:function(_6){
if(_6===true||_6===false){
this.selected=!_6;
}
if(this.selected){
this.selected=false;
this.button.deselect();
}else{
this.selected=true;
this.button.select();
}
this.mouse.setEventMode(this.selected?"pan":"");
},onPanDrag:function(_7){
var x=_7.x-_7.last.x;
var y=_7.y-_7.last.y;
this.canvas.domNode.parentNode.scrollTop-=_7.move.y;
this.canvas.domNode.parentNode.scrollLeft-=_7.move.x;
this.canvas.onScroll();
},onStencilUp:function(_8){
this.checkBounds();
},onStencilDrag:function(_9){
},checkBounds:function(){
var _a=function(){
};
var _b=function(){
};
var t=Infinity,r=-Infinity,b=-10000,l=10000,sx=0,sy=0,dy=0,dx=0,mx=this.stencils.group?this.stencils.group.getTransform():{dx:0,dy:0},sc=this.mouse.scrollOffset(),_c=sc.left?10:0,_d=sc.top?10:0,ch=this.canvas.height,cw=this.canvas.width,z=this.canvas.zoom,_e=this.canvas.parentHeight,_f=this.canvas.parentWidth;
this.stencils.withSelected(function(m){
var o=m.getBounds();
_b("SEL BOUNDS:",o);
t=Math.min(o.y1+mx.dy,t);
r=Math.max(o.x2+mx.dx,r);
b=Math.max(o.y2+mx.dy,b);
l=Math.min(o.x1+mx.dx,l);
});
this.stencils.withUnselected(function(m){
var o=m.getBounds();
_b("UN BOUNDS:",o);
t=Math.min(o.y1,t);
r=Math.max(o.x2,r);
b=Math.max(o.y2,b);
l=Math.min(o.x1,l);
_a("----------- B:",b,o.y2);
});
b*=z;
var _10=0,_11=0;
_a("Bottom test","b:",b,"z:",z,"ch:",ch,"pch:",_e,"top:",sc.top,"sy:",sy,"mx.dy:",mx.dy);
if(b>_e||sc.top){
_a("*bottom scroll*");
ch=Math.max(b,_e+sc.top);
sy=sc.top;
_10+=this.canvas.getScrollWidth();
}else{
if(!sy&&ch>_e){
_a("*bottom remove*");
ch=_e;
}
}
r*=z;
if(r>_f||sc.left){
cw=Math.max(r,_f+sc.left);
sx=sc.left;
_11+=this.canvas.getScrollWidth();
}else{
if(!sx&&cw>_f){
cw=_f;
}
}
cw+=_10*2;
ch+=_11*2;
this._blockScroll=true;
this.stencils.group&&this.stencils.group.applyTransform({dx:dx,dy:dy});
this.stencils.withUnselected(function(m){
m.transformPoints({dx:dx,dy:dy});
});
this.canvas.setDimensions(cw,ch,sx,sy);
}});
dojox.drawing.plugins.tools.Pan.setup={name:"dojox.drawing.plugins.tools.Pan",tooltip:"Pan Tool",iconClass:"iconPan"};
dojox.drawing.register(dojox.drawing.plugins.tools.Pan.setup,"plugin");
}


text:
//******************************************************************************************************
//  NamespaceDoc.cs - Gbtc
//
//  Copyright © 2012, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the MIT License (MIT), 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.opensource.org/licenses/MIT
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  09/29/2009 - Pinal C. Patel
//       Generated original version of source code.
//  10/11/2010 - Mihir Brahmbhatt
//       Updated header and license agreement.
//  12/14/2012 - Starlynn Danyelle Gilliam
//       Modified Header.
//
//******************************************************************************************************

using System.Runtime.CompilerServices;

namespace GSF.Historian.Files
{
    /// <summary>
    /// Contains classes used for manipulating archive files.
    /// </summary>
    [CompilerGenerated]
    class NamespaceDoc
    {
    }
}


text:
namespace gpopt
{
	using namespace gpos;

	//---------------------------------------------------------------------------
	//	@class:
	//		CXformInnerApplyWithOuterKey2InnerJoin
	//
	//	@doc:
	//		Transform inner apply into inner join under the condition that
	//		outer child of apply has key
	//
	//---------------------------------------------------------------------------
	class CXformInnerApplyWithOuterKey2InnerJoin : public CXformExploration
	{

		private:

			// private copy ctor
			CXformInnerApplyWithOuterKey2InnerJoin(const CXformInnerApplyWithOuterKey2InnerJoin &);

		public:

			// ctor
			explicit
			CXformInnerApplyWithOuterKey2InnerJoin(CMemoryPool *mp);

			// dtor
			virtual
			~CXformInnerApplyWithOuterKey2InnerJoin()
			{}

			// transformation promise
			EXformPromise Exfp(CExpressionHandle &exprhdl) const;

			// ident accessors
			virtual
			EXformId Exfid() const
			{
				return ExfInnerApplyWithOuterKey2InnerJoin;
			}

			virtual
			const CHAR *SzId() const
			{
				return "CXformInnerApplyWithOuterKey2InnerJoin";
			}

			// is transformation an Apply decorrelation (Apply To Join) xform?
			virtual
			BOOL FApplyDecorrelating() const
			{
				return true;
			}

			// actual transform
			void Transform
				(
				CXformContext *pxfctxt,
				CXformResult *pxfres,
				CExpression *pexpr
				)
				const;

	}; // class CXformInnerApplyWithOuterKey2InnerJoin

}

#endif // !GPOPT_CXformInnerApplyWithOuterKey2InnerJoin_H

// EOF


text:
package com.amazon.jenkins.ec2fleet;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.CancelSpotFleetRequestsRequest;
import com.amazonaws.services.ec2.model.DescribeSpotFleetRequestsRequest;
import com.amazonaws.services.ec2.model.RequestSpotFleetRequest;
import com.amazonaws.services.ec2.model.RequestSpotFleetResult;
import com.amazonaws.services.ec2.model.SpotFleetLaunchSpecification;
import com.amazonaws.services.ec2.model.SpotFleetRequestConfig;
import com.amazonaws.services.ec2.model.SpotFleetRequestConfigData;
import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl;
import com.cloudbees.plugins.credentials.CredentialsScope;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import org.apache.commons.lang.StringUtils;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.BuildWatcher;
import org.jvnet.hudson.test.JenkinsRule;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Ignore("for manual run as you need to provide real AWS EC2 API credentials")
public class RealEc2ApiIntegrationTest {

    @Rule
    public JenkinsRule j = new JenkinsRule();

    @ClassRule
    public static BuildWatcher bw = new BuildWatcher();

    @Test
    public void shouldSuccessfullyUpdatePluginWithFleetStatus() throws Exception {
        int targetCapacity = 0;

        final AWSCredentials awsCredentials = getAwsCredentials();

        SystemCredentialsProvider.getInstance().getCredentials().add(
                new AWSCredentialsImpl(CredentialsScope.SYSTEM, "credId",
                        awsCredentials.getAWSAccessKeyId(), awsCredentials.getAWSSecretKey(), "d"));

        withFleet(awsCredentials, targetCapacity, new WithFleetBody() {
            @Override
            public void run(AmazonEC2 amazonEC2, String fleetId) throws Exception {
                EC2FleetCloud cloud = new EC2FleetCloud("", null, "credId", null, null, null, fleetId,
                        null, null, null, false, false,
                        0, 0, 0, 0, false, false,
                        false, 0, 0, false,
                        10, false);
                j.jenkins.clouds.add(cloud);

                // 10 sec refresh time so wait
                Thread.sleep(TimeUnit.SECONDS.toMillis(60));

                // assertEquals(0, cloud.getStatusCache().getNumActive());
                // assertEquals(fleetId, cloud.getStatusCache().getFleetId());
            }
        });
    }

    /**
     * Related to https://github.com/jenkinsci/ec2-fleet-plugin/issues/60
     *
     * @throws Exception e
     */
    @Test
    public void shouldSuccessfullyUpdateBigFleetPluginWithFleetStatus() throws Exception {
        final int targetCapacity = 30;

        final AWSCredentials awsCredentials = getAwsCredentials();

        SystemCredentialsProvider.getInstance().getCredentials().add(
                new AWSCredentialsImpl(CredentialsScope.SYSTEM, "credId",
                        awsCredentials.getAWSAccessKeyId(), awsCredentials.getAWSSecretKey(), "d"));

        withFleet(awsCredentials, targetCapacity, new WithFleetBody() {
            @Override
            public void run(AmazonEC2 amazonEC2, String fleetId) throws Exception {
                EC2FleetCloud cloud = new EC2FleetCloud(null, null, "credId", null, null, null, fleetId,
                        null, null, null, false, false,
                        0, 0, 0, 0, false, false,
                        false, 0, 0, false, 10, false);
                j.jenkins.clouds.add(cloud);

                final long start = System.currentTimeMillis();
                final long max = TimeUnit.MINUTES.toMillis(2);
                while (System.currentTimeMillis() - start < max) {
                    // if (cloud.getStatusCache().getNumActive() >= targetCapacity) break;
                    Thread.sleep(TimeUnit.SECONDS.toMillis(10));
                }

                // todo replace with proper accessor assertEquals(targetCapacity, cloud.getStatusCache().getNumActive());
                // assertEquals(fleetId, cloud.getStatusCache().getFleetId());
            }
        });
    }

    private interface WithFleetBody {
        void run(AmazonEC2 amazonEC2, String fleetId) throws Exception;
    }

    private void withFleet(AWSCredentials awsCredentials, int targetCapacity, WithFleetBody body) throws Exception {
        final AmazonEC2 amazonEC2 = new AmazonEC2Client(awsCredentials);

        final SpotFleetRequestConfigData data = new SpotFleetRequestConfigData();
        data.setLaunchSpecifications(Arrays.asList(
                new SpotFleetLaunchSpecification()
                        .withInstanceType("t2.micro")
                        .withImageId("ami-009d6802948d06e52")
        ));
        data.setIamFleetRole("arn:aws:iam::...:role/aws-service-role/spotfleet.amazonaws.com/AWSServiceRoleForEC2SpotFleet");
        data.setTargetCapacity(targetCapacity);

        final RequestSpotFleetResult result = amazonEC2.requestSpotFleet(
                new RequestSpotFleetRequest().withSpotFleetRequestConfig(data));

        try {
            final List<SpotFleetRequestConfig> configs = amazonEC2.describeSpotFleetRequests(
                    new DescribeSpotFleetRequestsRequest().withSpotFleetRequestIds(
                            result.getSpotFleetRequestId())).getSpotFleetRequestConfigs();

            if (configs.isEmpty()) throw new IllegalArgumentException();

            final int f = configs.get(0).getSpotFleetRequestConfig().getFulfilledCapacity().intValue();
            System.out.println("Fulfilment " + f);

            body.run(amazonEC2, result.getSpotFleetRequestId());
        } finally {
            amazonEC2.cancelSpotFleetRequests(new CancelSpotFleetRequestsRequest()
                    .withSpotFleetRequestIds(result.getSpotFleetRequestId()).withTerminateInstances(true));
        }
    }

    private AWSCredentials getAwsCredentials() {
        final String accessKey = System.getProperty("AWS_ACCESS_KEY");
        final String secretKey = System.getProperty("AWS_SECRET_KEY");

        if (StringUtils.isBlank(accessKey) || StringUtils.isBlank(secretKey)) {
            throw new IllegalArgumentException("AWS_ACCESS_KEY or AWS_SECRET_KEY is not specified in system properties, -D");
        }

        return new BasicAWSCredentials(accessKey, secretKey);
    }

}


text:
module Prax
  module HTTP
    def parse_http_headers
      while line = socket.gets
        headers << [$1, $2] if line.strip =~ /^([^:]+):\s*(.*)$/
        break if line.strip.empty?
      end
    end

    def headers
      @headers ||= []
    end

    def header(name)
      headers.each { |header, value| return value if header.upcase == name.upcase }
      return nil
    end

    def header?(name)
      !header(name).nil?
    end

    def content_length
      @content_length ||= header('Content-Length').to_i
    end
  end
end


text:
FROM qa.stratio.com/stratio/spark-krb-dispatcher-support:2.1.0
MAINTAINER Sparta Team "sparta@stratio.com"

RUN apt-get update && apt-get install -y curl wget vim jq libsvn1 libcurl4-nss-dev default-jre-headless

WORKDIR /opt/spark/dist


text:
(function(Utils, API) {
  'use strict';

  window.OSjs       = window.OSjs       || {};
  OSjs.VFS          = OSjs.VFS          || {};
  OSjs.VFS.Modules  = OSjs.VFS.Modules  || {};

  /////////////////////////////////////////////////////////////////////////////
  // API
  /////////////////////////////////////////////////////////////////////////////

  var PublicStorage = {};
  PublicStorage.scandir = function(item, callback, options) {
    OSjs.VFS.internalCall('scandir', [item.path], function(error, result) {
      var list = [];
      if ( result ) {
        result = OSjs.VFS.filterScandir(result, options);
        result.forEach(function(iter) {
          list.push(new OSjs.VFS.File(iter));
        });
      }
      callback(error, list);
    });
  };
  PublicStorage.write = function(item, data, callback, options) {
    var wopts = [item.path, data];
    if ( options ) {
      wopts.push(options);
    }
    OSjs.VFS.internalCall('write', wopts, callback);
  };
  PublicStorage.read = function(item, callback, options) {
    var ropts = [item.path];
    var dataSource = options ? (options.dataSource ? true : false) : false;
    if ( options ) {
      ropts.push(options);
    }

    //OSjs.VFS.internalCall('read', ropts, callback);
    OSjs.VFS.internalCall('read', ropts, function(error, result) {
      if ( error ) {
        return callback(error);
      }
      callback(false, dataSource ? result : atob(result));
    });
  };
  PublicStorage.copy = function(src, dest, callback) {
    OSjs.VFS.internalCall('copy', [src.path, dest.path], callback);
  };
  PublicStorage.move = function(src, dest, callback) {
    OSjs.VFS.internalCall('move', [src.path, dest.path], callback);
  };
  PublicStorage.unlink = function(item, callback) {
    OSjs.VFS.internalCall('delete', [item.path], callback);
  };
  PublicStorage.mkdir = function(item, callback) {
    OSjs.VFS.internalCall('mkdir', [item.path], callback);
  };
  PublicStorage.exists = function(item, callback) {
    OSjs.VFS.internalCall('exists', [item.path], callback);
  };
  PublicStorage.fileinfo = function(item, callback) {
    OSjs.VFS.internalCall('fileinfo', [item.path], callback);
  };
  PublicStorage.url = function(item, callback) {
    var path    = typeof item === 'string' ? item : item.path;
    var handler = OSjs.API.getHandlerInstance();
    var fsuri   = handler.getConfig('Core').FSURI;
    callback(false, path ? (fsuri + path) : fsuri);
  };

  /////////////////////////////////////////////////////////////////////////////
  // WRAPPERS
  /////////////////////////////////////////////////////////////////////////////

  function makeRequest(name, args, callback, options) {
    args = args || [];
    callback = callback || {};

    if ( !PublicStorage[name] ) {
      throw new Error('Invalid PublicStorage API call name');
    }

    var fargs = args;
    fargs.push(callback);
    fargs.push(options);
    PublicStorage[name].apply(PublicStorage, fargs);
  }

  /////////////////////////////////////////////////////////////////////////////
  // EXPORTS
  /////////////////////////////////////////////////////////////////////////////

  OSjs.VFS.Modules.Public = OSjs.VFS.Modules.Public || {
    description: 'Shared',
    root: '/',
    icon: 'places/folder-publicshare.png',
    visible: true,
    internal: true,
    match: /^\//,
    enabled: function() {
      return true;
    },
    request: makeRequest
  };

})(OSjs.Utils, OSjs.API);


text:
package org.apache.avro.generic;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Collection;
import java.util.ArrayDeque;

import static org.junit.Assert.*;

import java.util.Arrays;

import org.apache.avro.Schema;
import org.apache.avro.Schema.Field;
import org.apache.avro.AvroRuntimeException;
import org.apache.avro.Schema.Type;
import org.apache.avro.SchemaBuilder;
import org.apache.avro.io.BinaryData;
import org.apache.avro.io.BinaryEncoder;
import org.apache.avro.io.EncoderFactory;
import org.apache.avro.generic.GenericData.Record;
import org.apache.avro.util.Utf8;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;

import org.junit.Test;

public class TestGenericData {

  @Test(expected=AvroRuntimeException.class)
    public void testrecordConstructorNullSchema() throws Exception {
    new GenericData.Record(null);
  }

  @Test(expected=AvroRuntimeException.class)
    public void testrecordConstructorWrongSchema() throws Exception {
    new GenericData.Record(Schema.create(Schema.Type.INT));
  }

  @Test(expected=AvroRuntimeException.class)
    public void testArrayConstructorNullSchema() throws Exception {
    new GenericData.Array<Object>(1, null);
  }

  @Test(expected=AvroRuntimeException.class)
    public void testArrayConstructorWrongSchema() throws Exception {
    new GenericData.Array<Object>(1, Schema.create(Schema.Type.INT));
  }

  @Test(expected=AvroRuntimeException.class)
  public void testRecordCreateEmptySchema() throws Exception {
    Schema s = Schema.createRecord("schemaName", "schemaDoc", "namespace", false);
    Record r = new GenericData.Record(s);
  }

  @Test(expected=AvroRuntimeException.class)
  public void testGetEmptySchemaFields() throws Exception {
    Schema s = Schema.createRecord("schemaName", "schemaDoc", "namespace", false);
    s.getFields();
  }

  @Test(expected=AvroRuntimeException.class)
  public void testGetEmptySchemaField() throws Exception {
    Schema s = Schema.createRecord("schemaName", "schemaDoc", "namespace", false);
    s.getField("foo");
  }

  @Test(expected=AvroRuntimeException.class)
  public void testRecordPutInvalidField() throws Exception {
    Schema s = Schema.createRecord("schemaName", "schemaDoc", "namespace", false);
    List<Schema.Field> fields = new ArrayList<Schema.Field>();
    fields.add(new Schema.Field("someFieldName", s, "docs", null));
    s.setFields(fields);
    Record r = new GenericData.Record(s);
    r.put("invalidFieldName", "someValue");
  }

  @Test
  /** Make sure that even with nulls, hashCode() doesn't throw NPE. */
  public void testHashCode() {
    GenericData.get().hashCode(null, Schema.create(Type.NULL));
    GenericData.get().hashCode(null, Schema.createUnion(
        Arrays.asList(Schema.create(Type.BOOLEAN), Schema.create(Type.STRING))));
    List<CharSequence> stuff = new ArrayList<CharSequence>();
    stuff.add("string");
    Schema schema = recordSchema();
    GenericRecord r = new GenericData.Record(schema);
    r.put(0, stuff);
    GenericData.get().hashCode(r, schema);
  }

  @Test
  public void testEquals() {
    Schema s = recordSchema();
    GenericRecord r0 = new GenericData.Record(s);
    GenericRecord r1 = new GenericData.Record(s);
    GenericRecord r2 = new GenericData.Record(s);
    Collection<CharSequence> l0 = new ArrayDeque<CharSequence>();
    List<CharSequence> l1 = new ArrayList<CharSequence>();
    GenericArray<CharSequence> l2 =
      new GenericData.Array<CharSequence>(1,s.getFields().get(0).schema());
    String foo = "foo";
    l0.add(new StringBuffer(foo));
    l1.add(foo);
    l2.add(new Utf8(foo));
    r0.put(0, l0);
    r1.put(0, l1);
    r2.put(0, l2);
    assertEquals(r0, r1);
    assertEquals(r0, r2);
    assertEquals(r1, r2);
  }

  private Schema recordSchema() {
    List<Field> fields = new ArrayList<Field>();
    fields.add(new Field("anArray", Schema.createArray(Schema.create(Type.STRING)), null, null));
    Schema schema = Schema.createRecord("arrayFoo", "test", "mytest", false);
    schema.setFields(fields);

    return schema;
  }

  @Test public void testEquals2() {
   Schema schema1 = Schema.createRecord("r", null, "x", false);
   List<Field> fields1 = new ArrayList<Field>();
   fields1.add(new Field("a", Schema.create(Schema.Type.STRING), null, null,
                         Field.Order.IGNORE));
   schema1.setFields(fields1);

   // only differs in field order
   Schema schema2 = Schema.createRecord("r", null, "x", false);
   List<Field> fields2 = new ArrayList<Field>();
   fields2.add(new Field("a", Schema.create(Schema.Type.STRING), null, null,
                         Field.Order.ASCENDING));
   schema2.setFields(fields2);

   GenericRecord record1 = new GenericData.Record(schema1);
   record1.put("a", "1");

   GenericRecord record2 = new GenericData.Record(schema2);
   record2.put("a", "2");

   assertFalse(record2.equals(record1));
   assertFalse(record1.equals(record2));
  }

  @Test
  public void testRecordGetFieldDoesntExist() throws Exception {
    List<Field> fields = new ArrayList<Field>();
    Schema schema = Schema.createRecord(fields);
    GenericData.Record record = new GenericData.Record(schema);
    assertNull(record.get("does not exist"));
  }

  @Test
  public void testArrayReversal() {
      Schema schema = Schema.createArray(Schema.create(Schema.Type.INT));
      GenericArray<Integer> forward = new GenericData.Array<Integer>(10, schema);
      GenericArray<Integer> backward = new GenericData.Array<Integer>(10, schema);
      for (int i = 0; i <= 9; i++) {
        forward.add(i);
      }
      for (int i = 9; i >= 0; i--) {
        backward.add(i);
      }
      forward.reverse();
      assertTrue(forward.equals(backward));
  }

  @Test
  public void testArrayListInterface() {
    Schema schema = Schema.createArray(Schema.create(Schema.Type.INT));
    GenericArray<Integer> array = new GenericData.Array<Integer>(1, schema);
    array.add(99);
    assertEquals(new Integer(99), array.get(0));
    List<Integer> list = new ArrayList<Integer>();
    list.add(99);
    assertEquals(array, list);
    assertEquals(list, array);
    assertEquals(list.hashCode(), array.hashCode());
    try {
      array.get(2);
      fail("Expected IndexOutOfBoundsException getting index 2");
    } catch (IndexOutOfBoundsException e) {}
    array.clear();
    assertEquals(0, array.size());
    try {
      array.get(0);
      fail("Expected IndexOutOfBoundsException getting index 0 after clear()");
    } catch (IndexOutOfBoundsException e) {}

  }
  @Test
  public void testArrayAddAtLocation()
  {
    Schema schema = Schema.createArray(Schema.create(Schema.Type.INT));
    GenericArray<Integer> array = new GenericData.Array<Integer>(6, schema);
    array.clear();
    for(int i=0; i<5; ++i)
      array.add(i);
    assertEquals(5, array.size());
    array.add(0, 6);
    assertEquals(new Integer(6), array.get(0));
    assertEquals(6, array.size());
    assertEquals(new Integer(0), array.get(1));
    assertEquals(new Integer(4), array.get(5));
    array.add(6, 7);
    assertEquals(new Integer(7), array.get(6));
    assertEquals(7, array.size());
    assertEquals(new Integer(6), array.get(0));
    assertEquals(new Integer(4), array.get(5));
    array.add(1, 8);
    assertEquals(new Integer(8), array.get(1));
    assertEquals(new Integer(0), array.get(2));
    assertEquals(new Integer(6), array.get(0));
    assertEquals(8, array.size());
    try {
	array.get(9);
	fail("Expected IndexOutOfBoundsException after adding elements");
    } catch (IndexOutOfBoundsException e){}
  }
  @Test
  public void testArrayRemove()
  {
    Schema schema = Schema.createArray(Schema.create(Schema.Type.INT));
    GenericArray<Integer> array = new GenericData.Array<Integer>(10, schema);
    array.clear();
    for(int i=0; i<10; ++i)
      array.add(i);
    assertEquals(10, array.size());
    assertEquals(new Integer(0), array.get(0));
    assertEquals(new Integer(9), array.get(9));

    array.remove(0);
    assertEquals(9, array.size());
    assertEquals(new Integer(1), array.get(0));
    assertEquals(new Integer(2), array.get(1));
    assertEquals(new Integer(9), array.get(8));

    // Test boundary errors.
    try {
      array.get(9);
      fail("Expected IndexOutOfBoundsException after removing an element");
    } catch (IndexOutOfBoundsException e){}
    try {
      array.set(9, 99);
      fail("Expected IndexOutOfBoundsException after removing an element");
    } catch (IndexOutOfBoundsException e){}
    try {
      array.remove(9);
      fail("Expected IndexOutOfBoundsException after removing an element");
    } catch (IndexOutOfBoundsException e){}

    // Test that we can still remove for properly sized arrays, and the rval
    assertEquals(new Integer(9), array.remove(8));
    assertEquals(8, array.size());

    // Test insertion after remove
    array.add(88);
    assertEquals(new Integer(88), array.get(8));
  }
  @Test
  public void testArraySet()
  {
    Schema schema = Schema.createArray(Schema.create(Schema.Type.INT));
    GenericArray<Integer> array = new GenericData.Array<Integer>(10, schema);
    array.clear();
    for(int i=0; i<10; ++i)
      array.add(i);
    assertEquals(10, array.size());
    assertEquals(new Integer(0), array.get(0));
    assertEquals(new Integer(5), array.get(5));

    assertEquals(new Integer(5), array.set(5, 55));
    assertEquals(10, array.size());
    assertEquals(new Integer(55), array.get(5));
  }

  @Test
  public void testToStringIsJson() throws JsonParseException, IOException {
    Field stringField = new Field("string", Schema.create(Type.STRING), null, null);
    Field enumField = new Field("enum", Schema.createEnum("my_enum", "doc", null, Arrays.asList("a", "b", "c")), null, null);
    Schema schema = Schema.createRecord("my_record", "doc", "mytest", false);
    schema.setFields(Arrays.asList(stringField, enumField));

    GenericRecord r = new GenericData.Record(schema);
    // \u2013 is EN DASH
    r.put(stringField.name(), "hello\nthere\"\tyou\u2013}");
    r.put(enumField.name(), new GenericData.EnumSymbol(enumField.schema(),"a"));

    String json = r.toString();
    JsonFactory factory = new JsonFactory();
    JsonParser parser = factory.createJsonParser(json);
    ObjectMapper mapper = new ObjectMapper();

    // will throw exception if string is not parsable json
    mapper.readTree(parser);
  }

  @Test public void testToStringDoesNotEscapeForwardSlash() throws Exception {
    GenericData data = GenericData.get();
    assertEquals("\"/\"", data.toString("/"));
  }

  @Test public void testToStringNanInfinity() throws Exception {
    GenericData data = GenericData.get();
    assertEquals("\"Infinity\"",data.toString(Float.POSITIVE_INFINITY));
    assertEquals("\"-Infinity\"",data.toString(Float.NEGATIVE_INFINITY));
    assertEquals("\"NaN\"", data.toString(Float.NaN));
    assertEquals("\"Infinity\"",data.toString(Double.POSITIVE_INFINITY));
    assertEquals("\"-Infinity\"",data.toString(Double.NEGATIVE_INFINITY));
    assertEquals("\"NaN\"", data.toString(Double.NaN));
  }

  @Test
  public void testCompare() {
    // Prepare a schema for testing.
    Field integerField = new Field("test", Schema.create(Type.INT), null, null);
    List<Field> fields = new ArrayList<Field>();
    fields.add(integerField);
    Schema record = Schema.createRecord("test", null, null, false);
    record.setFields(fields);

    ByteArrayOutputStream b1 = new ByteArrayOutputStream(5);
    ByteArrayOutputStream b2 = new ByteArrayOutputStream(5);
    BinaryEncoder b1Enc = EncoderFactory.get().binaryEncoder(b1, null);
    BinaryEncoder b2Enc = EncoderFactory.get().binaryEncoder(b2, null);
    // Prepare two different datums
    Record testDatum1 = new Record(record);
    testDatum1.put(0, 1);
    Record testDatum2 = new Record(record);
    testDatum2.put(0, 2);
    GenericDatumWriter<Record> gWriter = new GenericDatumWriter<Record>(record);
    Integer start1 = 0, start2 = 0;
    try {
      // Write two datums in each stream
      // and get the offset length after the first write in each.
      gWriter.write(testDatum1, b1Enc);
      b1Enc.flush();
      start1 = b1.size();
      gWriter.write(testDatum1, b1Enc);
      b1Enc.flush();
      b1.close();
      gWriter.write(testDatum2, b2Enc);
      b2Enc.flush();
      start2 = b2.size();
      gWriter.write(testDatum2, b2Enc);
      b2Enc.flush();
      b2.close();
      // Compare to check if offset-based compare works right.
      assertEquals(-1, BinaryData.compare(b1.toByteArray(), start1, b2.toByteArray(), start2, record));
    } catch (IOException e) {
      fail("IOException while writing records to output stream.");
    }
  }

  @Test
  public void testEnumCompare() {
    Schema s = Schema.createEnum("Kind",null,null,Arrays.asList("Z","Y","X"));
    GenericEnumSymbol z = new GenericData.EnumSymbol(s, "Z");
    GenericEnumSymbol y = new GenericData.EnumSymbol(s, "Y");
    assertEquals(0, z.compareTo(z));
    assertTrue(y.compareTo(z) > 0);
    assertTrue(z.compareTo(y) < 0);
  }

  @Test
  public void testByteBufferDeepCopy() {
    // Test that a deep copy of a byte buffer respects the byte buffer
    // limits and capacity.
    byte[] buffer_value = {0, 1, 2, 3, 0, 0, 0};
    ByteBuffer buffer = ByteBuffer.wrap(buffer_value, 1, 4);
    Schema schema = Schema.createRecord("my_record", "doc", "mytest", false);
    Field byte_field =
      new Field("bytes", Schema.create(Type.BYTES), null, null);
    schema.setFields(Arrays.asList(byte_field));

    GenericRecord record = new GenericData.Record(schema);
    record.put(byte_field.name(), buffer);

    GenericRecord copy = GenericData.get().deepCopy(schema, record);
    ByteBuffer buffer_copy = (ByteBuffer) copy.get(byte_field.name());

    assertEquals(buffer, buffer_copy);
  }

  @Test
  public void testValidateNullableEnum() {
    List<Schema> unionTypes = new ArrayList<Schema>();
    Schema schema;
    Schema nullSchema = Schema.create(Type.NULL);
    Schema enumSchema = Schema.createEnum("AnEnum", null, null, Arrays.asList("X","Y","Z"));
    GenericEnumSymbol w = new GenericData.EnumSymbol(enumSchema, "W");
    GenericEnumSymbol x = new GenericData.EnumSymbol(enumSchema, "X");
    GenericEnumSymbol y = new GenericData.EnumSymbol(enumSchema, "Y");
    GenericEnumSymbol z = new GenericData.EnumSymbol(enumSchema, "Z");

    // null is first
    unionTypes.clear();
    unionTypes.add(nullSchema);
    unionTypes.add(enumSchema);
    schema = Schema.createUnion(unionTypes);

    assertTrue(GenericData.get().validate(schema, z));
    assertTrue(GenericData.get().validate(schema, y));
    assertTrue(GenericData.get().validate(schema, x));
    assertFalse(GenericData.get().validate(schema, w));
    assertTrue(GenericData.get().validate(schema, null));

    // null is last
    unionTypes.clear();
    unionTypes.add(enumSchema);
    unionTypes.add(nullSchema);
    schema = Schema.createUnion(unionTypes);

    assertTrue(GenericData.get().validate(schema, z));
    assertTrue(GenericData.get().validate(schema, y));
    assertTrue(GenericData.get().validate(schema, x));
    assertFalse(GenericData.get().validate(schema, w));
    assertTrue(GenericData.get().validate(schema, null));
  }

  private enum anEnum { ONE,TWO,THREE };
  @Test
  public void validateRequiresGenericSymbolForEnumSchema() {
    final Schema schema = Schema.createEnum("my_enum", "doc", "namespace", Arrays.asList("ONE","TWO","THREE"));
    final GenericData gd = GenericData.get();

    /* positive cases */
    assertTrue(gd.validate(schema, new GenericData.EnumSymbol(schema, "ONE")));
    assertTrue(gd.validate(schema, new GenericData.EnumSymbol(schema, anEnum.ONE)));

    /* negative cases */
    assertFalse("We don't expect GenericData to allow a String datum for an enum schema", gd.validate(schema, "ONE"));
    assertFalse("We don't expect GenericData to allow a Java Enum for an enum schema", gd.validate(schema, anEnum.ONE));
  }

  @Test
  public void testValidateUnion() {
      Schema type1Schema = SchemaBuilder.record("Type1")
          .fields()
          .requiredString("myString")
          .requiredInt("myInt")
          .endRecord();

      Schema type2Schema = SchemaBuilder.record("Type2")
          .fields()
          .requiredString("myString")
          .endRecord();

      Schema unionSchema = SchemaBuilder.unionOf()
          .type(type1Schema).and().type(type2Schema)
          .endUnion();

    GenericRecord record = new GenericData.Record(type2Schema);
    record.put("myString", "myValue");
    assertTrue(GenericData.get().validate(unionSchema, record));
  }
}


text:
package com.fly.firefly;

import android.app.ProgressDialog;

import com.fly.firefly.base.BaseFragment;

/**
 * Created by Dell on 11/5/2015.
 */
public class LoadingClass extends BaseFragment {

    public void initiateLoading()
    {
        ProgressDialog mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.show();
    }
}


text:
#ifndef BT_CONE_MINKOWSKI_H
#define BT_CONE_MINKOWSKI_H

#include "btConvexInternalShape.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types

///The btConeShape implements a cone shape primitive, centered around the origin and aligned with the Y axis. The btConeShapeX is aligned around the X axis and btConeShapeZ around the Z axis.
class btConeShape : public btConvexInternalShape

{

	btScalar m_sinAngle;
	btScalar m_radius;
	btScalar m_height;
	int		m_coneIndices[3];
	btVector3 coneLocalSupport(const btVector3& v) const;

public:
	btConeShape (btScalar radius,btScalar height);

	virtual btVector3	localGetSupportingVertex(const btVector3& vec) const;
	virtual btVector3	localGetSupportingVertexWithoutMargin(const btVector3& vec) const;
	virtual void	batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const;

	btScalar getRadius() const { return m_radius;}
	btScalar getHeight() const { return m_height;}

	virtual void	calculateLocalInertia(btScalar mass,btVector3& inertia) const
	{
		btTransform identity;
		identity.setIdentity();
		btVector3 aabbMin,aabbMax;
		getAabb(identity,aabbMin,aabbMax);

		btVector3 halfExtents = (aabbMax-aabbMin)*btScalar(0.5);

		btScalar margin = getMargin();

		btScalar lx=btScalar(2.)*(halfExtents.x()+margin);
		btScalar ly=btScalar(2.)*(halfExtents.y()+margin);
		btScalar lz=btScalar(2.)*(halfExtents.z()+margin);
		const btScalar x2 = lx*lx;
		const btScalar y2 = ly*ly;
		const btScalar z2 = lz*lz;
		const btScalar scaledmass = mass * btScalar(0.08333333);

		inertia = scaledmass * (btVector3(y2+z2,x2+z2,x2+y2));

//		inertia.x() = scaledmass * (y2+z2);
//		inertia.y() = scaledmass * (x2+z2);
//		inertia.z() = scaledmass * (x2+y2);
	}

		virtual const char*	getName()const
		{
			return "Cone";
		}

		///choose upAxis index
		void	setConeUpIndex(int upIndex);

		int	getConeUpIndex() const
		{
			return m_coneIndices[1];
		}

	virtual void	setLocalScaling(const btVector3& scaling);

};

///btConeShape implements a Cone shape, around the X axis
class btConeShapeX : public btConeShape
{
	public:
		btConeShapeX(btScalar radius,btScalar height);
};

///btConeShapeZ implements a Cone shape, around the Z axis
class btConeShapeZ : public btConeShape
{
	public:
		btConeShapeZ(btScalar radius,btScalar height);
};
#endif //BT_CONE_MINKOWSKI_H


text:
package com.oracle.truffle.llvm.nodes.impl.intrinsics.interop;

import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.NodeChildren;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.interop.ForeignAccess;
import com.oracle.truffle.api.interop.Message;
import com.oracle.truffle.api.interop.TruffleObject;
import com.oracle.truffle.api.interop.UnsupportedMessageException;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.llvm.nodes.base.LLVMExpressionNode;
import com.oracle.truffle.llvm.nodes.impl.intrinsics.llvm.LLVMIntrinsic.LLVMAddressIntrinsic;
import com.oracle.truffle.llvm.nodes.impl.intrinsics.llvm.LLVMIntrinsic.LLVMBooleanIntrinsic;
import com.oracle.truffle.llvm.nodes.impl.intrinsics.llvm.LLVMIntrinsic.LLVMDoubleIntrinsic;
import com.oracle.truffle.llvm.nodes.impl.intrinsics.llvm.LLVMIntrinsic.LLVMFloatIntrinsic;
import com.oracle.truffle.llvm.nodes.impl.intrinsics.llvm.LLVMIntrinsic.LLVMI32Intrinsic;
import com.oracle.truffle.llvm.nodes.impl.intrinsics.llvm.LLVMIntrinsic.LLVMI64Intrinsic;
import com.oracle.truffle.llvm.nodes.impl.intrinsics.llvm.LLVMIntrinsic.LLVMI8Intrinsic;
import com.oracle.truffle.llvm.types.LLVMTruffleObject;

public final class LLVMTruffleUnbox {

    private static Object doUnbox(VirtualFrame frame, Node foreignUnbox, LLVMTruffleObject value, ToLLVMNode toLLVM, Class<?> expectedType) {
        try {
            if (value.getOffset() != 0 || value.getName() != null) {
                throw new IllegalAccessError("Pointee must be unmodified");
            }
            Object rawValue = ForeignAccess.sendUnbox(foreignUnbox, frame, value.getObject());
            return toLLVM.convert(frame, rawValue, expectedType);
        } catch (UnsupportedMessageException e) {
            throw new IllegalStateException(e);
        }
    }

    @NodeChildren({@NodeChild(type = LLVMExpressionNode.class)})
    public abstract static class LLVMTruffleUnboxP extends LLVMAddressIntrinsic {

        @Child private Node foreignUnbox = Message.UNBOX.createNode();
        @Child private ToLLVMNode toLLVM = new ToLLVMNode();

        private static final Class<?> expectedType = TruffleObject.class;

        @Specialization
        public Object executeIntrinsic(VirtualFrame frame, LLVMTruffleObject value) {
            return doUnbox(frame, foreignUnbox, value, toLLVM, expectedType);
        }

        @Specialization
        public Object executeIntrinsic(VirtualFrame frame, TruffleObject value) {
            return executeIntrinsic(frame, new LLVMTruffleObject(value));
        }
    }

    @NodeChildren({@NodeChild(type = LLVMExpressionNode.class)})
    public abstract static class LLVMTruffleUnboxI extends LLVMI32Intrinsic {

        @Child private Node foreignUnbox = Message.UNBOX.createNode();
        @Child private ToLLVMNode toLLVM = new ToLLVMNode();

        private static final Class<?> expectedType = int.class;

        @Specialization
        public int executeIntrinsic(VirtualFrame frame, LLVMTruffleObject value) {
            return (int) doUnbox(frame, foreignUnbox, value, toLLVM, expectedType);
        }

        @Specialization
        public int executeIntrinsic(VirtualFrame frame, TruffleObject value) {
            return executeIntrinsic(frame, new LLVMTruffleObject(value));
        }
    }

    @NodeChildren({@NodeChild(type = LLVMExpressionNode.class)})
    public abstract static class LLVMTruffleUnboxL extends LLVMI64Intrinsic {

        @Child private Node foreignUnbox = Message.UNBOX.createNode();
        @Child private ToLLVMNode toLLVM = new ToLLVMNode();

        private static final Class<?> expectedType = long.class;

        @Specialization
        public long executeIntrinsic(VirtualFrame frame, LLVMTruffleObject value) {
            return (long) doUnbox(frame, foreignUnbox, value, toLLVM, expectedType);
        }

        @Specialization
        public long executeIntrinsic(VirtualFrame frame, TruffleObject value) {
            return executeIntrinsic(frame, new LLVMTruffleObject(value));
        }
    }

    @NodeChildren({@NodeChild(type = LLVMExpressionNode.class)})
    public abstract static class LLVMTruffleUnboxC extends LLVMI8Intrinsic {

        @Child private Node foreignUnbox = Message.UNBOX.createNode();
        @Child private ToLLVMNode toLLVM = new ToLLVMNode();

        private static final Class<?> expectedType = byte.class;

        @Specialization
        public byte executeIntrinsic(VirtualFrame frame, LLVMTruffleObject value) {
            return (byte) doUnbox(frame, foreignUnbox, value, toLLVM, expectedType);
        }

        @Specialization
        public byte executeIntrinsic(VirtualFrame frame, TruffleObject value) {
            return executeIntrinsic(frame, new LLVMTruffleObject(value));
        }
    }

    @NodeChildren({@NodeChild(type = LLVMExpressionNode.class)})
    public abstract static class LLVMTruffleUnboxF extends LLVMFloatIntrinsic {

        @Child private Node foreignUnbox = Message.UNBOX.createNode();
        @Child private ToLLVMNode toLLVM = new ToLLVMNode();

        private static final Class<?> expectedType = float.class;

        @Specialization
        public float executeIntrinsic(VirtualFrame frame, LLVMTruffleObject value) {
            return (float) doUnbox(frame, foreignUnbox, value, toLLVM, expectedType);
        }

        @Specialization
        public float executeIntrinsic(VirtualFrame frame, TruffleObject value) {
            return executeIntrinsic(frame, new LLVMTruffleObject(value));
        }
    }

    @NodeChildren({@NodeChild(type = LLVMExpressionNode.class)})
    public abstract static class LLVMTruffleUnboxD extends LLVMDoubleIntrinsic {

        @Child private Node foreignUnbox = Message.UNBOX.createNode();
        @Child private ToLLVMNode toLLVM = new ToLLVMNode();

        private static final Class<?> expectedType = double.class;

        @Specialization
        public double executeIntrinsic(VirtualFrame frame, LLVMTruffleObject value) {
            return (double) doUnbox(frame, foreignUnbox, value, toLLVM, expectedType);
        }

        @Specialization
        public double executeIntrinsic(VirtualFrame frame, TruffleObject value) {
            return executeIntrinsic(frame, new LLVMTruffleObject(value));
        }
    }

    @NodeChildren({@NodeChild(type = LLVMExpressionNode.class)})
    public abstract static class LLVMTruffleUnboxB extends LLVMBooleanIntrinsic {

        @Child private Node foreignUnbox = Message.UNBOX.createNode();
        @Child private ToLLVMNode toLLVM = new ToLLVMNode();

        private static final Class<?> expectedType = boolean.class;

        @Specialization
        public boolean executeIntrinsic(VirtualFrame frame, LLVMTruffleObject value) {
            return (boolean) doUnbox(frame, foreignUnbox, value, toLLVM, expectedType);
        }

        @Specialization
        public boolean executeIntrinsic(VirtualFrame frame, TruffleObject value) {
            return executeIntrinsic(frame, new LLVMTruffleObject(value));
        }
    }
}


text:
package org.apache.drill.exec.store.sys;

import com.google.common.collect.Lists;
import org.apache.drill.common.types.TypeProtos;
import org.apache.drill.common.types.Types;
import org.apache.drill.exec.exception.SchemaChangeException;
import org.apache.drill.exec.ops.FragmentContext;
import org.apache.drill.exec.physical.impl.OutputMutator;
import org.apache.drill.exec.proto.CoordinationProtos;
import org.apache.drill.exec.record.MaterializedField;
import org.apache.drill.exec.server.DrillbitContext;
import org.apache.drill.exec.vector.BigIntVector;
import org.apache.drill.exec.vector.VarCharVector;
import org.eigenbase.sql.type.SqlTypeName;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.List;

/**
 * A {@link org.apache.drill.exec.store.sys.SystemRecord} that holds information about drillbit threads
 */
public class ThreadsRecord extends SystemRecord {
//  private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ThreadsRecord.class);

  private static final ThreadsRecord INSTANCE = new ThreadsRecord();

  public static SystemRecord getInstance() {
    return INSTANCE;
  }

  private static final String HOST_NAME = "hostname";
  private static final MaterializedField hostNameField = MaterializedField.create(HOST_NAME,
    Types.required(TypeProtos.MinorType.VARCHAR));
  private VarCharVector hostName;

  private static final String USER_PORT = "user_port";
  private static final MaterializedField userPortField = MaterializedField.create(USER_PORT,
    Types.required(TypeProtos.MinorType.BIGINT));
  private BigIntVector userPort;

  private static final String TOTAL_THREADS = "total_threads";
  private static final MaterializedField totalThreadsField = MaterializedField.create(TOTAL_THREADS,
    Types.required(TypeProtos.MinorType.BIGINT));
  private BigIntVector totalThreads;

  private static final String BUSY_THREADS = "busy_threads";
  private static final MaterializedField busyThreadsField = MaterializedField.create(BUSY_THREADS,
    Types.required(TypeProtos.MinorType.BIGINT));
  private BigIntVector busyThreads;

  private static final List<SqlTypeName> FIELDS = Lists.newArrayList(SqlTypeName.VARCHAR, SqlTypeName.BIGINT,
    SqlTypeName.BIGINT, SqlTypeName.BIGINT);

  private static final List<String> NAMES = Lists.newArrayList(HOST_NAME, USER_PORT, TOTAL_THREADS, BUSY_THREADS);

  private ThreadsRecord() {
  }

  @Override
  public void setup(final OutputMutator output) throws SchemaChangeException {
    hostName = output.addField(hostNameField, VarCharVector.class);
    userPort = output.addField(userPortField, BigIntVector.class);
    totalThreads = output.addField(totalThreadsField, BigIntVector.class);
    busyThreads = output.addField(busyThreadsField, BigIntVector.class);
  }

  @Override
  public void setRecordValues(final FragmentContext context) {
    final DrillbitContext drillbitContext = context.getDrillbitContext();
    final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

    final CoordinationProtos.DrillbitEndpoint endpoint = drillbitContext.getEndpoint();
    final String address = endpoint.getAddress();
    final VarCharVector.Mutator hostNameMutator = hostName.getMutator();
    hostNameMutator.setSafe(0, address.getBytes());
    hostNameMutator.setValueCount(1);

    final int port = endpoint.getUserPort();
    final BigIntVector.Mutator userPortMutator = userPort.getMutator();
    userPortMutator.setSafe(0, port);
    userPortMutator.setValueCount(1);

    final BigIntVector.Mutator totalThreadsMutator = totalThreads.getMutator();
    totalThreadsMutator.setSafe(0, threadMXBean.getPeakThreadCount());
    totalThreadsMutator.setValueCount(1);

    final BigIntVector.Mutator busyThreadsMutator = busyThreads.getMutator();
    busyThreadsMutator.setSafe(0, threadMXBean.getThreadCount());
    busyThreadsMutator.setValueCount(1);
  }

  @Override
  public List<SqlTypeName> getFieldSqlTypeNames() {
    return FIELDS;
  }

  @Override
  public List<String> getFieldNames() {
    return NAMES;
  }
}


text:
package com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionTree;

import java.util.List;

import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;

import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.Conditions.CConditionCriterium;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.Conditions.ICriteriumCreator;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.Conditions.And.CAndCriterium;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.Conditions.Not.CNotCriterium;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.Conditions.Or.COrCriterium;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionModel.CCriteriumTree;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionModel.CCriteriumTreeNode;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionTree.Actions.CAddConditionAction;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionTree.Actions.CAppendAndOperatorAction;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionTree.Actions.CAppendNotOperatorAction;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionTree.Actions.CAppendOrOperatorAction;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionTree.Actions.CInsertAndOperatorAction;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionTree.Actions.CInsertNotOperatorAction;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionTree.Actions.CInsertOrOperatorAction;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionTree.Actions.CRemoveAction;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionTree.Actions.CRemoveAllAction;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.Implementations.CCriteriumFunctions;

/**
 * Menu builder that builds the context menus for each node of the criterium tree.
 */
public final class CNodeMenuBuilder {
  /**
   * Node for which the menu item is built.
   */
  private final JCriteriumTreeNode m_criteriumNode;

  /**
   * The context menu built by the menu builder.
   */
  private final JPopupMenu m_popup = new JPopupMenu();

  /**
   * Menu item used to insert AND conditions.
   */
  private final JMenuItem m_insertAnd;

  /**
   * Menu item used to insert OR conditions.
   */
  private final JMenuItem m_insertOr;

  /**
   * Menu item used to insert NOT conditions.
   */
  private final JMenuItem m_insertNot;

  /**
   * Menu item used to append AND conditions.
   */
  private final JMenuItem m_appendAnd;

  /**
   * Menu item used to append OR conditions.
   */
  private final JMenuItem m_appendOr;

  /**
   * Menu item used to append NOT conditions.
   */
  private final JMenuItem m_appendNot;

  /**
   * Sub menu where the individual conditions are listed.
   */
  private final JMenu m_conditionSubmenu;

  /**
   * Menu item used to remove one node from the tree.
   */
  private final JMenuItem m_remove;

  /**
   * Menu item used to reset the tree.
   */
  private final JMenuItem m_removeAll;

  /**
   * Creates a new menu builder object.
   *
   * @param node Node for which the menu item is built.
   * @param ctree Criterium tree to modify by the menu.
   * @param criteria List of available criteria.
   */
  public CNodeMenuBuilder(final JCriteriumTreeNode node, final CCriteriumTree ctree,
      final List<ICriteriumCreator> criteria) {
    m_criteriumNode = node;

    final CCriteriumTreeNode clickedCriterium = CCriteriumFunctions.findNode(
        ctree.getRoot(), node.getCriterium());

    m_appendAnd = new JMenuItem(new CAppendAndOperatorAction(ctree, clickedCriterium));
    m_appendOr = new JMenuItem(new CAppendOrOperatorAction(ctree, clickedCriterium));
    m_appendNot = new JMenuItem(new CAppendNotOperatorAction(ctree, clickedCriterium));

    m_popup.add(m_appendAnd);
    m_popup.add(m_appendOr);
    m_popup.add(m_appendNot);

    m_popup.add(new JSeparator());

    m_insertAnd = new JMenuItem(new CInsertAndOperatorAction(ctree, clickedCriterium));
    m_insertOr = new JMenuItem(new CInsertOrOperatorAction(ctree, clickedCriterium));
    m_insertNot = new JMenuItem(new CInsertNotOperatorAction(ctree, clickedCriterium));

    m_popup.add(m_insertAnd);
    m_popup.add(m_insertOr);
    m_popup.add(m_insertNot);

    m_popup.add(new JSeparator());

    m_conditionSubmenu = new JMenu("Create Condition");

    for (final ICriteriumCreator condition : criteria) {
      m_conditionSubmenu.add(
          new JMenuItem(new CAddConditionAction(ctree, clickedCriterium, condition)));
    }

    m_popup.add(m_conditionSubmenu);

    m_popup.add(new JSeparator());

    m_remove = new JMenuItem(new CRemoveAction(ctree, clickedCriterium));
    m_popup.add(m_remove);

    m_popup.add(new JSeparator());

    m_removeAll = new JMenuItem(new CRemoveAllAction(ctree));
    m_popup.add(m_removeAll);

  }

  /**
   * Updates the state of the context menu depending on the state of the criterium tree.
   */
  private void updateMenuState() {
    m_appendAnd.setEnabled(m_criteriumNode.allowAppend(CAndCriterium.class));
    m_appendOr.setEnabled(m_criteriumNode.allowAppend(COrCriterium.class));
    m_appendNot.setEnabled(m_criteriumNode.allowAppend(CNotCriterium.class));

    m_insertAnd.setEnabled(m_criteriumNode.allowInsert(CAndCriterium.class));
    m_insertOr.setEnabled(m_criteriumNode.allowInsert(COrCriterium.class));
    m_insertNot.setEnabled(m_criteriumNode.allowInsert(CNotCriterium.class));

    m_conditionSubmenu.setEnabled(m_criteriumNode.allowAppend(CConditionCriterium.class));

    m_remove.setEnabled(!m_criteriumNode.isRoot());

    m_removeAll.setEnabled(m_criteriumNode.getChildCount() != 0);
  }

  /**
   * Returns the popup menu built by the menu builder.
   *
   * @return The built popup menu.
   */
  public JPopupMenu getPopup() {
    updateMenuState();

    return m_popup;
  }
}


text:
package org.b3log.solo.processor;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.time.DateFormatUtils;
import org.b3log.latke.Keys;
import org.b3log.latke.annotation.RequestProcessing;
import org.b3log.latke.annotation.RequestProcessor;
import org.b3log.latke.repository.FilterOperator;
import org.b3log.latke.repository.PropertyFilter;
import org.b3log.latke.repository.Query;
import org.b3log.latke.repository.SortDirection;
import org.b3log.latke.servlet.HTTPRequestContext;
import org.b3log.latke.servlet.HTTPRequestMethod;
import org.b3log.latke.servlet.renderer.TextXMLRenderer;
import org.b3log.solo.model.ArchiveDate;
import org.b3log.solo.model.Article;
import org.b3log.solo.model.Page;
import org.b3log.solo.model.Preference;
import org.b3log.solo.model.Tag;
import org.b3log.solo.model.sitemap.Sitemap;
import org.b3log.solo.model.sitemap.URL;
import org.b3log.solo.repository.ArchiveDateRepository;
import org.b3log.solo.repository.PageRepository;
import org.b3log.solo.repository.TagRepository;
import org.b3log.solo.repository.impl.ArchiveDateRepositoryImpl;
import org.b3log.solo.repository.impl.ArticleRepositoryImpl;
import org.b3log.solo.repository.impl.PageRepositoryImpl;
import org.b3log.solo.repository.impl.TagRepositoryImpl;
import org.b3log.solo.service.PreferenceQueryService;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Site map (sitemap) processor.
 *
 * @author Liang Ding
 * @version 1.0.0.4, Jun 11, 2012
 * @since 0.3.1
 */
@RequestProcessor
public final class SitemapProcessor {

    /**
     * Logger.
     */
    private static final Logger LOGGER = Logger.getLogger(SitemapProcessor.class.getName());
    /**
     * Preference query service.
     */
    private PreferenceQueryService preferenceQueryService = PreferenceQueryService.getInstance();
    /**
     * Article repository.
     */
    private ArticleRepositoryImpl articleRepository = ArticleRepositoryImpl.getInstance();
    /**
     * Page repository.
     */
    private PageRepository pageRepository = PageRepositoryImpl.getInstance();
    /**
     * Tag repository.
     */
    private TagRepository tagRepository = TagRepositoryImpl.getInstance();
    /**
     * Archive date repository.
     */
    private ArchiveDateRepository archiveDateRepository = ArchiveDateRepositoryImpl.getInstance();

    /**
     * Returns the sitemap.
     *
     * @param context the specified context
     */
    @RequestProcessing(value = {"/sitemap.xml"}, method = HTTPRequestMethod.GET)
    public void sitemap(final HTTPRequestContext context) {
        final TextXMLRenderer renderer = new TextXMLRenderer();
        context.setRenderer(renderer);

        final Sitemap sitemap = new Sitemap();

        try {
            final JSONObject preference = preferenceQueryService.getPreference();

            addArticles(sitemap, preference);
            addNavigations(sitemap, preference);
            addTags(sitemap, preference);
            addArchives(sitemap, preference);

            LOGGER.log(Level.INFO, "Generating sitemap....");
            final String content = sitemap.toString();
            LOGGER.log(Level.INFO, "Generated sitemap");
            renderer.setContent(content);
        } catch (final Exception e) {
            LOGGER.log(Level.SEVERE, "Get blog article feed error", e);

            try {
                context.getResponse().sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            } catch (final IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }

    /**
     * Adds articles into the specified sitemap.
     *
     * @param sitemap the specified sitemap
     * @param preference the specified preference
     * @throws Exception exception
     */
    private void addArticles(final Sitemap sitemap, final JSONObject preference) throws Exception {
        final String host = preference.getString(Preference.BLOG_HOST);

        // XXX: query all articles?
        final Query query = new Query().setCurrentPageNum(1).
                setFilter(new PropertyFilter(Article.ARTICLE_IS_PUBLISHED, FilterOperator.EQUAL, true)).
                addSort(Article.ARTICLE_CREATE_DATE, SortDirection.DESCENDING);

        // Closes cache avoid Java heap space out of memory while caching
        // query results
        articleRepository.setCacheEnabled(false);

        final JSONObject articleResult = articleRepository.get(query);

        articleRepository.setCacheEnabled(true); // Restores cache

        final JSONArray articles = articleResult.getJSONArray(Keys.RESULTS);
        for (int i = 0; i < articles.length(); i++) {
            final JSONObject article = articles.getJSONObject(i);
            final String permalink = article.getString(Article.ARTICLE_PERMALINK);

            final URL url = new URL();
            url.setLoc("http://" + host + permalink);

            final Date updateDate = (Date) article.get(Article.ARTICLE_UPDATE_DATE);
            final String lastMod = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(updateDate);
            url.setLastMod(lastMod);

            sitemap.addURL(url);
        }
    }

    /**
     * Adds navigations into the specified sitemap.
     *
     * @param sitemap the specified sitemap
     * @param preference the specified preference
     * @throws Exception exception
     */
    private void addNavigations(final Sitemap sitemap, final JSONObject preference) throws Exception {
        final String host = preference.getString(Preference.BLOG_HOST);

        final JSONObject result = pageRepository.get(new Query());
        final JSONArray pages = result.getJSONArray(Keys.RESULTS);
        for (int i = 0; i < pages.length(); i++) {
            final JSONObject page = pages.getJSONObject(i);
            final String permalink = page.getString(Page.PAGE_PERMALINK);

            final URL url = new URL();
            // The navigation maybe a page or a link
            // Just filters for user mistakes tolerance
            if (!permalink.contains("://")) {
                url.setLoc("http://" + host + permalink);
            } else {
                url.setLoc(permalink);
            }

            sitemap.addURL(url);
        }
    }

    /**
     * Adds tags (tag-articles) and tags wall (/tags.html) into the specified
     * sitemap.
     *
     * @param sitemap the specified sitemap
     * @param preference the specified preference
     * @throws Exception exception
     */
    private void addTags(final Sitemap sitemap, final JSONObject preference) throws Exception {
        final String host = preference.getString(Preference.BLOG_HOST);

        final JSONObject result = tagRepository.get(new Query());
        final JSONArray tags = result.getJSONArray(Keys.RESULTS);
        for (int i = 0; i < tags.length(); i++) {
            final JSONObject tag = tags.getJSONObject(i);
            final String link = URLEncoder.encode(tag.getString(Tag.TAG_TITLE), "UTF-8");

            final URL url = new URL();
            url.setLoc("http://" + host + "/tags/" + link);

            sitemap.addURL(url);
        }

        // Tags wall
        final URL url = new URL();
        url.setLoc("http://" + host + "/tags.html");
        sitemap.addURL(url);
    }

    /**
     * Adds archives (archive-articles) into the specified sitemap.
     *
     * @param sitemap the specified sitemap
     * @param preference the specified preference
     * @throws Exception exception
     */
    private void addArchives(final Sitemap sitemap, final JSONObject preference) throws Exception {
        final String host = preference.getString(Preference.BLOG_HOST);

        final JSONObject result = archiveDateRepository.get(new Query());
        final JSONArray archiveDates = result.getJSONArray(Keys.RESULTS);
        for (int i = 0; i < archiveDates.length(); i++) {
            final JSONObject archiveDate = archiveDates.getJSONObject(i);
            final long time = archiveDate.getLong(ArchiveDate.ARCHIVE_TIME);
            final String dateString = ArchiveDate.DATE_FORMAT.format(time);

            final URL url = new URL();
            url.setLoc("http://" + host + "/archives/" + dateString);

            sitemap.addURL(url);
        }
    }
}


text:
require 'spec_helper'

describe Spree::AddOnAdjuster do

  let(:master_add_on) { create(:add_on) }
  let(:adjuster) { Spree::AddOnAdjuster.new(master_add_on) }

  context "add on totals" do

    let(:product) { create(:product, add_ons: [master_add_on]) }
    let!(:line_item) { create(:line_item, variant: create(:variant, product: product)) }

    it "should create the adjustments" do
      allow(adjuster).to receive(:is_new?).and_return(true)
      adjuster.adjust(line_item)
      # source type not set in adjuster
      expect(line_item.adjustments.count).to eql 1
      expect(master_add_on.adjustment).to be nil
    end

    it "will not duplicate adjustments" do
      allow(adjuster).to receive(:is_new?).and_return(true)
      adj = adjuster.adjust(line_item)
      allow(adjuster).to receive(:adjustment_for).and_return(adj)
      adjuster.adjust(line_item)
      expect(line_item.adjustments.count).to eql 1
      expect(master_add_on.adjustment).to be nil
    end

    it "wont create adjustment for inactive addons" do
      allow(master_add_on).to receive(:active).and_return(false)
      allow(adjuster).to receive(:is_new?)
      adjuster.adjust(line_item)
      expect(line_item.adjustments.add_ons.count).to eql 0
      expect(master_add_on.adjustment).to be nil
    end

    it "wont create adjustment for 0 price addons" do
      allow(adjuster).to receive(:compute_amount).and_return(0)
      allow(adjuster).to receive(:is_new?)
      adjuster.adjust(line_item)
      expect(line_item.adjustments.add_ons.count).to eql 0
      expect(master_add_on.adjustment).to be nil
    end

    it "should compute correclty" do
      expect(adjuster.compute_amount(line_item)).to eq 10
    end
  end

end


text:
#ifndef SRC_LIBUTIL_SQLITE_UTILS_H_
#define SRC_LIBUTIL_SQLITE_UTILS_H_

#include "config.h"
#include "mem_pool.h"
#include "sqlite3.h"

#define RSPAMD_SQLITE3_STMT_MULTIPLE (1 << 0)

struct rspamd_sqlite3_prstmt {
	gint idx;
	const gchar *sql;
	const gchar *args;
	sqlite3_stmt *stmt;
	gint result;
	const gchar *ret;
	gint flags;
};

/**
 * Create prepared statements for specified database from init statements
 * @param db
 * @param max_idx
 * @param err
 * @return new prepared statements array or NULL
 */
GArray* rspamd_sqlite3_init_prstmt (sqlite3 *db,
		struct rspamd_sqlite3_prstmt *init_stmt,
		gint max_idx,
		GError **err);

/**
 * Run prepared statements by its index getting parameters and setting results from
 * varargs structure
 * @param db
 * @param stmts
 * @param idx
 * @return
 */
gint rspamd_sqlite3_run_prstmt (rspamd_mempool_t *pool, sqlite3 *db, GArray *stmts,
		gint idx, ...);

/**
 * Close and free prepared statements
 * @param db
 * @param stmts
 */
void rspamd_sqlite3_close_prstmt (sqlite3 *db, GArray *stmts);

/**
 * Creates or opens sqlite database trying to share it between processes
 * @param path
 * @param create_sql
 * @return
 */
sqlite3 * rspamd_sqlite3_open_or_create (rspamd_mempool_t *pool, const gchar *path, const
		gchar *create_sql, guint32 version, GError **err);

/**
 * Sync sqlite3 db ensuring that all wal things are done
 * @param db
 */
gboolean rspamd_sqlite3_sync (sqlite3 *db, gint *wal_frames, gint *wal_checkpoints);

#endif /* SRC_LIBUTIL_SQLITE_UTILS_H_ */