text:
package org.jboss.aerogear.devnexus2015.ui.fragment;

import android.app.Fragment;
import android.app.LoaderManager;
import android.content.AsyncTaskLoader;
import android.content.Loader;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import org.apache.commons.io.IOUtils;
import org.devnexus.util.GsonUtils;
import org.jboss.aerogear.devnexus2015.MainActivity;
import org.jboss.aerogear.devnexus2015.R;
import org.jboss.aerogear.devnexus2015.model.License;
import org.jboss.aerogear.devnexus2015.model.Sponsor;
import org.jboss.aerogear.devnexus2015.ui.adapter.LicenseRecyclerViewAdapter;
import org.jboss.aerogear.devnexus2015.ui.adapter.ScheduleItemWithHeaderViewAdapter;
import org.jboss.aerogear.devnexus2015.ui.adapter.SponsorsRecyclerViewAdapter;
import org.jboss.aerogear.devnexus2015.util.CenteringDecoration;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by summers on 1/10/16.
 */
public class AboutFragment extends Fragment implements LoaderManager.LoaderCallbacks<List> {

    private static final int SPONSOR_LOADER = 0x100;
    private static final int OSS_LOADER = 0x200;
    @Bind(R.id.sponsors_list)
    RecyclerView sponsorsRecycler;
    @Bind(R.id.license_list)
    RecyclerView ossRecycler;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.spinner_nav)
    Spinner spinner;
    @Bind(R.id.sponsor_content)
    View sponsorContent;
    @Bind(R.id.opensource_content)
    View ossContent;
    private int columnCount = 1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.about_layout, container, false);
        ButterKnife.bind(this, view);

        ((MainActivity) getActivity()).attachToolbar(toolbar);
        toolbar.setTitle("About DevNexus");

        this.columnCount = ((MainActivity) getActivity()).getColumnCount();
        sponsorsRecycler.setLayoutManager(new GridLayoutManager(getActivity(), columnCount));
        sponsorsRecycler.addItemDecoration(new CenteringDecoration(columnCount, 230, getActivity()));
        ossRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
        getLoaderManager().initLoader(SPONSOR_LOADER, new Bundle(), this).forceLoad();
        getLoaderManager().initLoader(OSS_LOADER, new Bundle(), this).forceLoad();
        loadSpinnerNav(spinner);

        return view;
    }

    private void loadSpinnerNav(Spinner spinner) {
        spinner.setAdapter(new AboutNavigationSpinnerAdapter(getActivity()));
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0 :
                        loadSponsors();
                        break;
                    case 1:
                        loadOSS();
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                //doNothing
            }
        });
    }

    private void loadSponsors() {
        sponsorContent.setVisibility(View.VISIBLE);
        ossContent.setVisibility(View.GONE);
    }

    private void loadOSS() {
        sponsorContent.setVisibility(View.GONE);
        ossContent.setVisibility(View.VISIBLE);
    }

    @Override
    public Loader<List> onCreateLoader(int id, Bundle args) {
        switch (id) {
            case SPONSOR_LOADER:
                return new AsyncTaskLoader<List>(getActivity()) {
                    @Override
                    public List loadInBackground() {
                        final List sponsors = new ArrayList(30);
                        final InputStream sponsorsStream = getContext().getResources().openRawResource(R.raw.sponsors);
                        try {
                            final String sponsorsJson = IOUtils.toString(sponsorsStream);
                            final JsonElement jsonRootElement = new JsonParser().parse(sponsorsJson);
                            final JsonArray sponsorsJsonArray = jsonRootElement.getAsJsonObject().getAsJsonArray("sponsors");
                            for (int index = 0; index < sponsorsJsonArray.size(); index++) {
                                final JsonElement sponsorObject = sponsorsJsonArray.get(index);
                                final Sponsor sponsor = GsonUtils.GSON.fromJson(sponsorObject, Sponsor.class);
                                sponsors.add(sponsor);
                            }
                        } catch (IOException e) {
                            Log.e("LOAD_SPONSORS", e.getMessage(), e);
                        }

                        return sponsors;
                    }
                };

            case OSS_LOADER:
                return new AsyncTaskLoader<List>(getActivity()) {
                    @Override
                    public List loadInBackground() {
                        final List licenses = new ArrayList(30);
                        final InputStream licensesStream = getContext().getResources().openRawResource(R.raw.licenses);
                        try {
                            final String licensesJson = IOUtils.toString(licensesStream);
                            final JsonElement jsonRootElement = new JsonParser().parse(licensesJson);
                            final JsonArray licensesJsonArray = jsonRootElement.getAsJsonObject().getAsJsonArray("licenses");
                            for (int index = 0; index < licensesJsonArray.size(); index++) {
                                final JsonElement sponsorObject = licensesJsonArray.get(index);
                                final License license = GsonUtils.GSON.fromJson(sponsorObject, License.class);
                                licenses.add(license);
                            }
                        } catch (IOException e) {
                            Log.e("LOAD_LICENSE", e.getMessage(), e);
                        }

                        return licenses;
                    }
                };

            default:
                return null;
        }

    }

    @Override
    public void onLoadFinished(Loader<List> loader, List data) {
        if (data.get(0) instanceof Sponsor) {
            refreshSponsorData((List<Sponsor>)data);
        } else if (data.get(0) instanceof License) {
            refreshLicenseData((List<License>)data);
        }
    }

    private void refreshSponsorData(List<Sponsor> sponsors) {
        sponsorsRecycler.setAdapter(new SponsorsRecyclerViewAdapter(new ArrayList<Sponsor>(sponsors), getActivity(), columnCount));
        ((GridLayoutManager)sponsorsRecycler.getLayoutManager()).setSpanSizeLookup(((SponsorsRecyclerViewAdapter)sponsorsRecycler.getAdapter()).getSpanSizeLookup());

    }

    private void refreshLicenseData(List<License> licenses) {
        ossRecycler.setAdapter(new LicenseRecyclerViewAdapter(new ArrayList<License>(licenses), getActivity()));

    }

    @Override
    public void onLoaderReset(Loader<List> loader) {

    }

    public static AboutFragment newInstance() {
        return new AboutFragment();
    }
}


text:
package com.bookmarking.desktop;

import java.net.*;
import java.util.*;
import com.bookmarking.*;
import com.bookmarking.bookmark.*;
import com.bookmarking.desktop.tag.*;
import com.bookmarking.desktop.util.*;
import com.bookmarking.error.*;
import com.bookmarking.search.*;
import javafx.event.*;
import javafx.fxml.*;
import javafx.geometry.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import org.apache.logging.log4j.*;

public class TagsUIController implements Initializable
{
    private static final Logger logger = LogManager.getLogger(TagsUIController.class.getCanonicalName());
    private static TagsUIController tagsUIController;
    private static Insets selectedTagsPaneInsets = new Insets(0, 15, 0, 0);

    @FXML
    private VBox availableTagsPane;

    @FXML
    private VBox selectedTagsPane;

    @FXML
    private ScrollPane availableTagsScrollPane;

    private Map<String, SelectedTag> selectedTagMap;
    private TagsPanel tagsPanel;

    @Override
    public void initialize(URL location, ResourceBundle resources)
    {
        logger.info("Initializing TagsUIController");
        selectedTagMap = new HashMap<>();
        tagsUIController = this;
        tagsPanel = new TagsPanel(availableTagsPane,  new AvailableTag(this, ""));
    }

    @FXML
    public void clearButtonAction(ActionEvent actionEvent)
    {
        SearchUIController.use().getSearchOptions().clearOperationsList();
        MainUIController.use().refresh();
    }

    public void refresh()
    {
        try
        {
            addSelectedTags();
            addAvailableTags();
        }
        catch (Exception e)
        {
            ErrorHandler.handle(e);
        }
    }

    public String nextTabItem()
    {
        String tabbedItem = this.tagsPanel.nextTabItem();
        Pane tagPane = this.tagsPanel.getTagPane(tabbedItem);
        ensureVisible(availableTagsScrollPane, tagPane);

        return tabbedItem;
    }

    /**
     * Scrolls the pane so that it's child is visible.
     *
     * This method gotten from: https://stackoverflow.com/questions/12837592/how-to-scroll-to-make-a-node-within-the-content-of-a-scrollpane-visible
     * And then I modified it.
     *
     * @param pane  The scrollpane that contains the child
     * @param node  The child to make visible.
     */
    private static void ensureVisible(ScrollPane pane, Node node) {
        double width = pane.getContent().getBoundsInLocal().getWidth();
        double height = pane.getContent().getBoundsInLocal().getHeight();

        double x = node.getBoundsInParent().getMinX();
        double y = node.getBoundsInParent().getMinY();

        // scrolling values range from 0 to 1
        pane.setVvalue(y/height);
        pane.setHvalue(x/width);
    }

    /**
     * Adds tags and their operations (And, Or, Not) to the selected tags panel.
     * @throws Exception
     */
    private void addSelectedTags()
        throws Exception
    {
        clearChildren(selectedTagsPane);

        List<Operation> operations = SearchUIController.use().getSearchOptions().getTagOperations();

        // Add selected tags
        for (Operation operation : operations)
        {
            selectedTagsPane.getChildren().add(UIElements.getNewSeparatorPane(getType(operation), 1));

            FlowPane flowPane = UIElements.getNewFlowPane();
            flowPane.setPadding(selectedTagsPaneInsets);
            selectedTagsPane.getChildren().add(flowPane);

            for (String s : operation.getTags())
            {
                SelectedTag selectedTag = selectedTagMap.computeIfAbsent(s, s1 -> new SelectedTag(this, s1, operation));

                flowPane.getChildren().add(selectedTag);
            }
        }
    }

    private void clearChildren(Pane pane)
    {
        // Clearing the children of sub panels so those panels can be garbage collected.
        for (Node node : pane.getChildren())
        {
            if (node instanceof Pane)
            {
                Pane p = (Pane) node;
                clearChildren(p);
            }
        }
        pane.getChildren().clear();
    }

    private void addAvailableTags()
        throws Exception
    {
        SearchOptions searchOptions = SearchUIController.use().getSearchOptions();
        List<AbstractBookmark> bookmarks = BookmarksListController.use().getBookmarks();
        Set<String> tags = LocalInstance.use().getIOInterface().extractTags(bookmarks);

        // Remove any previously selected tag.
        tags.removeAll(searchOptions.getTagsPresent());

        SortedMap<String, Set<String>> orderedTags = LocalInstance.use().getIOInterface().getTagsGroupedByFirstLetter(tags);
        tagsPanel.setTags(orderedTags, searchOptions.getSearchTerm());
    }

    private String getType(Operation operation)
    {
        switch (operation.getOperation())
        {
            case ALL_TAGS:
                return "And";
            case ANY_TAG:
                return "Or";
            case WITHOUT_TAGS:
                return "\uf05e";
            default:
                return "";
        }
    }

    public static TagsUIController use()
    {
        return tagsUIController;
    }
}

redpajama_set_name: RedPajamaGithub


text:
class User < ActiveRecord::Base

  def User.class_method_is_awesome
    return "success!"
  end

  async_class_method :class_method_is_awesome

  def User.class_methods_with_awesome_vars(num1, num2)
    return num1.to_i + num2.to_i
  end

  async_class_method :class_methods_with_awesome_vars

  def long_method
    sleep 2

    return "success!"
  end

  async_method :long_method, queue: 'long-methods'

  def another_long_method
    sleep 2

    return "success!"
  end
  async_method :another_long_method

  def kiss(other_user)
    return "#{self.name} kissed #{other_user.name}"
  end

  async_method :kiss
end


text:
package org.batfish.datamodel;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

import com.google.common.collect.ImmutableList;
import org.junit.Test;

/** Tests of {@link AsPath} */
public class AsPathTest {
  @Test
  public void testRemoveConfederations() {
    AsPath path = AsPath.of(AsSet.of(1L));
    AsPath updated = path.removeConfederations();
    assertThat(path, equalTo(updated));

    path = AsPath.of(AsSet.confed(1L));
    updated = path.removeConfederations();
    assertThat(updated, equalTo(AsPath.empty()));

    path = AsPath.of(ImmutableList.of(AsSet.confed(1L), AsSet.of(2L)));
    updated = path.removeConfederations();
    assertThat(updated, equalTo(AsPath.ofSingletonAsSets(2L)));

    path = AsPath.of(ImmutableList.of(AsSet.confed(1L), AsSet.of(2L), AsSet.confed(3L)));
    updated = path.removeConfederations();
    assertThat(updated, equalTo(AsPath.ofSingletonAsSets(2L)));
  }

  @Test
  public void testAsPathLength() {
    AsPath path = AsPath.of(AsSet.confed(1L));
    assertThat(path.length(), equalTo(0));

    path = AsPath.of(ImmutableList.of(AsSet.confed(1L), AsSet.of(2L)));
    assertThat(path.length(), equalTo(1));
    assertThat(path.size(), equalTo(2));

    path = AsPath.of(ImmutableList.of(AsSet.confed(1L), AsSet.of(2L, 3L), AsSet.confed(3L)));
    assertThat(path.length(), equalTo(1));
    assertThat(path.size(), equalTo(3));
  }
}


text:
package action;

import java.awt.Color;
import javax.swing.JColorChooser;
import javax.swing.JComponent;
import controller.Controller;

public class ModifyPenColor extends ActionDisplayModify {

    public ModifyPenColor (JComponent target, Controller c) {
        super(target, c);

    }

    @Override
    protected void modify () {
        Color color = JColorChooser.showDialog(null, "choose a color", Color.black);
        if (color == null)
            return;
        controller.changePenColor(color);
    }

    @Override
    public void undoExecute () {

        controller.undoLoadCode();
    }

    @Override
    public void redoExecute () {

        controller.undoLoadCode();
    }
}


text:
#ifndef __VARIABLE_MANAGER_HPP__
#define __VARIABLE_MANAGER_HPP__

#include "bddDump.h"
#include <map>
#include <vector>
#include <utility>
#include <boost/noncopyable.hpp>

//! The Variable manager class. Used as basis for the GR(1) context and keeps track of all
//! variables.
class SlugsVariableManager : public VariableInfoContainer {
protected:

    //@{
    /** @name Definitions for the BF-related stuff
     */
    BFManager mgr;
    std::vector<BF> variables;
    std::vector<std::string> variableNames;
    std::vector<VariableType> variableTypes;
    //@}

public: // To be changed later
    std::map<BFVarVector*,std::vector<int> >  varVectorsToConstruct;
    std::map<BFVarCube*,std::set<int> >  varCubesToConstruct;
    std::map<std::vector<BF>*,std::vector<int> >  varVectorOfBFsToConstruct;

public:

    void computeVariableInformation();

    //@{
    /**
     * @name The following functions are inherited from the VariableInfo container.
     * They allow us to the the BF_dumpDot function for debugging new variants of the synthesis algorithm
     */
    void getVariableTypes(std::vector<std::string> &types) const;
    void getVariableNumbersOfType(std::string typeString, std::vector<unsigned int> &nums) const;
    int addVariable(VariableType type, std::string name);
    virtual BF getVariableBF(unsigned int number) const {
        return variables[number];
    }
    virtual std::string getVariableName(unsigned int number) const {
        return variableNames[number];
    }
    //@}
};

// Template class to simplify building variable vectors
// Note that the class is non-copyable as it reports an address to the
// slugs variable manager
class SlugsVarVector : public boost::noncopyable {
    BFVarVector vector;
public:
    SlugsVarVector(VariableType t1, SlugsVariableManager *varMgr) {
        std::vector<int> types;
        types.push_back(t1);
        varMgr->varVectorsToConstruct[&vector] = types;
    }
    SlugsVarVector(VariableType t1, VariableType t2, SlugsVariableManager *varMgr) {
        std::vector<int> types;
        types.push_back(t1);
        types.push_back(t2);
        varMgr->varVectorsToConstruct[&vector] = types;
    }
    operator BFVarVector& () {return vector;}
};

// Template class to simplify building variable cube
// Note that the class is non-copyable as it reports an address to the
// slugs variable manager
class SlugsVarCube : public boost::noncopyable {
    BFVarCube cube;
public:
    SlugsVarCube(VariableType t1, SlugsVariableManager *varMgr) {
        std::set<int> types;
        types.insert(t1);
        varMgr->varCubesToConstruct[&cube] = types;
    }
    SlugsVarCube(VariableType t1, VariableType t2, SlugsVariableManager *varMgr) {
        std::set<int> types;
        types.insert(t1);
        types.insert(t2);
        varMgr->varCubesToConstruct[&cube] = types;
    }
    operator BFVarCube& () {return cube;}
};

// Template class to simplify building variable vectors
// Note that the class is non-copyable as it reports an address to the
// slugs variable manager
class SlugsVectorOfVarBFs : public boost::noncopyable {
    std::vector<BF> vector;
public:
    SlugsVectorOfVarBFs(VariableType t1, SlugsVariableManager *varMgr) {
        std::vector<int> types;
        types.push_back(t1);
        varMgr->varVectorOfBFsToConstruct[&vector] = types;
    }
    SlugsVectorOfVarBFs(VariableType t1, VariableType t2, SlugsVariableManager *varMgr) {
        std::vector<int> types;
        types.push_back(t1);
        types.push_back(t2);
        varMgr->varVectorOfBFsToConstruct[&vector] = types;
    }
    operator const std::vector<BF>& () {return vector;}
};

#endif


text:
srcdir = .

EXECUTABLES = callfuncs datatypes vec_comps convs_casts operators

all info install-info dvi install uninstall installcheck check:
	@echo "Nothing to be done for $@..."

clean mostlyclean:
	-rm -f *~ *.o a.out core corefile gcore.test
	-rm -f *.dwo *.dwp
	-rm -f $(EXECUTABLES)

distclean maintainer-clean realclean: clean
	-rm -f *~ core
	-rm -f Makefile config.status config.log
	-rm -f *-init.exp gdb.log gdb.sum
	-rm -fr *.log summary detail *.plog *.sum *.psum site.*


text:
_Pragma("once")

#include "tinycommon.hpp"

namespace tinyav{
struct defer_frame_t { };
constexpr const defer_frame_t defer_frame{};
class avframe {
public:
    struct ItemRef {
        constexpr ItemRef() = default;
        constexpr ItemRef(ItemRef&&) = default;
        constexpr ItemRef(const ItemRef&) = default;
        inline ItemRef(const avframe&frm, int sample = 0)
            : _data(frm.data())
            , _sample(sample)
            , _stride(frm.word_stride())
            , _planes(frm.planes()){ }

        float **      _data{nullptr};
              int     _sample{0};
              int16_t _stride{1};
              int16_t _planes{1};
        inline ItemRef& operator=(ItemRef&&) = default;
        inline ItemRef& operator=(const ItemRef&) = default;
        constexpr float &operator[](int ch)
        {
            return (_planes==1) ? _data[ch][_sample * _stride     ]
                               : _data[0 ][_sample * _stride + ch];
        }
        constexpr float operator[](int ch) const
        {
            return (_planes==1) ? _data[ch][_sample * _stride    ]
                                : _data[0][_sample * _stride + ch];
        }
    };
    AVFrame     *m_d{nullptr};
    avframe(const defer_frame_t &)
        : m_d{nullptr} {}
    avframe()
        : m_d(av_frame_alloc()) { };
    avframe(AVFrame *f)
        : m_d(f) { }
    avframe(avframe &&o)
        : m_d(o.release()) { }
    avframe(const avframe &o)
        : m_d(av_frame_clone(o)) { }
    avframe &operator = (AVFrame *f)
    {
        reset(f);
        return *this;
    }
    avframe &operator = (const AVFrame *f)
    {
        if(f != m_d)
            reset(av_frame_clone(f));
        return *this;
    }
    avframe &operator =(avframe &&o)
    {
        if(m_d) {
            ref(o);
        }else{
            reset(o.release());
        }
        return *this;
    }
    avframe &operator = (const avframe &o)
    {
        reset(av_frame_clone(o.m_d));
        return *this;
    }
    void swap(avframe &o) noexcept { std::swap(m_d,o.m_d);}
    void reset(AVFrame *f = nullptr)
    {
        if(m_d != f)
            av_frame_free(&m_d);
        m_d = f;
    }
    AVFrame *release() {
        auto ret = static_cast<AVFrame*>(nullptr);
        std::swap(m_d,ret);
        return ret;
    }
    AVFrame *get() const { return m_d;}
   ~avframe() { reset();}
    AVFrame *operator ->() { return m_d; }
    AVFrame *operator ->() const { return m_d;}
    AVFrame &operator *() { return *m_d;}
    const AVFrame &operator *() const { return *m_d;}
    operator bool() const { return !!m_d;}
    operator AVFrame *() const { return m_d;}
    inline void alloc()
    {
        if(!m_d)
            m_d = av_frame_alloc();
        else
            unref();
    }
    inline void unref()
    {
        av_frame_unref(m_d);
    }
    inline void ref(avframe &o)
    {
        if(o.m_d != m_d && o.m_d) {
            alloc();
            av_frame_ref(m_d,o.m_d);
        }
    }
    inline bool make_writable()
    {
        return !av_frame_make_writable(m_d);
    }
    inline bool writable()
    {
        return av_frame_is_writable(m_d);
    }
    bool get_buffer()
    {
        if(!m_d)
            return false;
        unref();
        return av_frame_get_buffer(m_d,0);
    }
    inline int64_t get_best_effort_timestamp() const
    {
        return av_frame_get_best_effort_timestamp(m_d);
    }
    inline int64_t pkt_duration() const { return av_frame_get_pkt_duration(m_d);}
    inline int64_t pkt_pos() const { return av_frame_get_pkt_pos(m_d);}
    inline int64_t pkt_pts() const { return m_d ? m_d->pkt_pts : AV_NOPTS_VALUE;}
    inline int64_t pkt_dts() const { return m_d ? m_d->pkt_dts : AV_NOPTS_VALUE;}
    inline int64_t channel_layout() const { return av_frame_get_channel_layout(m_d);}
    inline int     channels() const { return av_frame_get_channels(m_d);}
    inline int     sample_rate() const { return av_frame_get_sample_rate(m_d);}
    inline int     pkt_size() const { return av_frame_get_pkt_size(m_d);}
    inline AVSampleFormat format() const { return m_d ? static_cast<AVSampleFormat>(m_d->format) : AV_SAMPLE_FMT_NONE;}
    inline int     samples() const { return m_d->nb_samples;}
    inline bool    planar() const { return av_sample_fmt_is_planar(format());}
    inline int64_t pts() const { return m_d ? m_d->pts : AV_NOPTS_VALUE;}
    int     copy(AVFrame *o) { return av_frame_copy(m_d,o);}
    int     copy_props(AVFrame *o) { return av_frame_copy_props(m_d,o);}
    inline float **data() const { return reinterpret_cast<float**>(m_d->extended_data);}
    inline float  *data(int i) const
    {
        return planar() ? (data()[i]) : (data()[0] + i);
    }
    inline float  &data(int c,int s)
    {
        return planar() ? data()[0][ c + s * channels()] : data()[c][s];
    }
    inline const float  &data(int c,int s) const
    {
        return planar() ? data()[0][ c + s * channels()] : data()[c][s];
    }
    inline ItemRef operator[](int s) { return ItemRef(*this, s);}
    inline const ItemRef operator[](int s) const { return ItemRef(*this, s);}
    inline const ItemRef at(int s) const { return ItemRef(*this, s);}
    int     copy_to(AVFrame *dst, int dst_offset, int src_offset, int nb_samples)
    {
        if(!dst || dst->format != format())
            return -EINVAL;
        if(dst->nb_samples < dst_offset + nb_samples
        || m_d->nb_samples < src_offset + nb_samples)
            return -EINVAL;
        return av_samples_copy(dst->extended_data, m_d->extended_data, dst_offset, src_offset, nb_samples, channels(), format());
    }
    int     copy_from(AVFrame *src, int dst_offset, int src_offset, int nb_samples)
    {
        if(!src|| src->format != format())
            return -EINVAL;
        if(m_d->nb_samples < dst_offset + nb_samples
        || src->nb_samples < src_offset + nb_samples)
            return -EINVAL;
        return av_samples_copy(m_d->extended_data, src->extended_data, dst_offset, src_offset, nb_samples, channels(), format());
    }
    int     copy_to(float **dst, int dst_offset, int src_offset, int nb_samples)
    {
        if(!dst)
            return -EINVAL;
        if(m_d->nb_samples < src_offset + nb_samples)
            return -EINVAL;
        return av_samples_copy(reinterpret_cast<uint8_t**>(dst), m_d->extended_data, dst_offset, src_offset, nb_samples, channels(), format());
    }
    int     shift_samples(int nb_samples)
    {
        if(!writable())
            make_writable();
        nb_samples = std::min(nb_samples, samples());
        if( av_samples_copy(m_d->extended_data, m_d->extended_data, 0, nb_samples, samples() - nb_samples,  channels(),format()))
            return -1;
        m_d->nb_samples -= nb_samples;
        return nb_samples;
    }
    int     shift_samples(int nb_samples, const AVRational &stream_tb)
    {
        if(!writable())
            make_writable();
        nb_samples = std::min(nb_samples, samples());
        if( av_samples_copy(m_d->extended_data, m_d->extended_data, 0, nb_samples, samples() - nb_samples,  channels(),format()))
            return -1;
        m_d->nb_samples -= nb_samples;
        if(stream_tb.den) {
            auto diff = av_rescale_q(nb_samples, (AVRational){ 1, sample_rate()}, stream_tb);
            m_d->pts += diff;
            m_d->pkt_pts += diff;
            m_d->pkt_duration -= diff;
        }
        return nb_samples;
    }
    inline int bytes_per_sample() const
    {
        return av_get_bytes_per_sample(format());
    }
    inline int planes() const
    {
        return planar() ? 1 : channels();
    }
    inline int word_stride() const
    {
        return planar() ? channels() : 1;
    }
    inline int stride() const
    {
        return word_stride() * bytes_per_sample();
    }
    int skip_samples(int nb_samples)
    {
        nb_samples = std::min(nb_samples,samples());
        auto _planes = planar() ? channels() : 1;
        auto _shift  = stride() * nb_samples;
        for(auto i = 0; i < _planes; i++)
            m_d->extended_data[i] += _shift;
        if(m_d->data != m_d->extended_data) {
            for(auto i = 0; i < FFMIN(_planes, AV_NUM_DATA_POINTERS); i++) {
                m_d->data[i] = m_d->extended_data[i];
            }
        }
        m_d->nb_samples -= nb_samples;
        return nb_samples;
    }
    int skip_samples(int nb_samples, const AVRational &stream_tb)
    {
        nb_samples = std::min(nb_samples,samples());
        auto _planes = planar() ? channels() : 1;
        auto _shift  = stride() * nb_samples;
        for(auto i = 0; i < _planes; i++)
            m_d->extended_data[i] += _shift;
        if(m_d->data != m_d->extended_data) {
            for(auto i = 0; i < FFMIN(_planes, AV_NUM_DATA_POINTERS); i++) {
                m_d->data[i] = m_d->extended_data[i];
            }
        }
        m_d->nb_samples -= nb_samples;
        if(stream_tb.den) {
            auto diff = av_rescale_q(nb_samples, (AVRational){ 1, sample_rate()}, stream_tb);
            m_d->pts += diff;
            m_d->pkt_pts += diff;
            m_d->pkt_duration -= diff;
        }
        return nb_samples;
    }
    inline int64_t duration(const AVRational &tb)
    {
        return av_rescale_q(samples(), (AVRational){ 1, sample_rate()}, tb);
    }
    void realloc(int nb_samples)
    {
        make_writable();
        auto new_size = std::max(nb_samples * stride(), 0);
        for(auto i = 0, p = planes(); i < p; i++ ) {
            auto &bufref = (i<AV_NUM_DATA_POINTERS)
                ? m_d->buf[i]
                : m_d->extended_buf[i];
            if(auto err = av_buffer_realloc(&bufref, new_size))
                throw std::system_error(err,std::system_category(),
                        "Failure reallocating AVBuffer.");
            m_d->extended_data[i] = bufref->data;
        }
        m_d->nb_samples = nb_samples;
    }
    int capacity() const
    {
        auto cap = 0;
        for(auto i = 0, p = planes(); i < p; i++) {
            auto bufref = av_frame_get_plane_buffer(m_d, i);
            if(bufref) {
                cap = std::min<int>(bufref->data + bufref->size - m_d->extended_data[i], cap);
            }
        }
        return cap / stride();
    }
};
};
inline void swap(tinyav::avframe &lhs, tinyav::avframe &rhs){ lhs.swap(rhs);}


text:
package org.apache.avro.generic;

import java.io.IOException;

import org.apache.avro.AvroRuntimeException;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Field;
import org.apache.avro.data.RecordBuilderBase;
import org.apache.avro.generic.GenericData.Record;

/** A RecordBuilder for generic records. GenericRecordBuilder fills in default values
 * for fields if they are not specified.  */
public class GenericRecordBuilder extends RecordBuilderBase<Record> {
  private final GenericData.Record record;

  /**
   * Creates a GenericRecordBuilder for building Record instances.
   * @param schema the schema associated with the record class.
   */
  public GenericRecordBuilder(Schema schema) {
    super(schema, GenericData.get());
    record = new GenericData.Record(schema);
  }

  /**
   * Creates a GenericRecordBuilder by copying an existing GenericRecordBuilder.
   * @param other the GenericRecordBuilder to copy.
   */
  public GenericRecordBuilder(GenericRecordBuilder other) {
    super(other, GenericData.get());
    record = new GenericData.Record(other.record, /* deepCopy = */ true);
  }

  /**
   * Creates a GenericRecordBuilder by copying an existing record instance.
   * @param other the record instance to copy.
   */
  public GenericRecordBuilder(Record other) {
    super(other.getSchema(), GenericData.get());
    record = new GenericData.Record(other, /* deepCopy = */ true);

    // Set all fields in the RecordBuilder that are set in the record
    for (Field f : schema().getFields()) {
      Object value = other.get(f.pos());
      // Only set the value if it is not null, if the schema type is null,
      // or if the schema type is a union that accepts nulls.
      if (isValidValue(f, value)) {
        set(f, data().deepCopy(f.schema(), value));
      }
    }
  }

  /**
   * Gets the value of a field.
   * @param fieldName the name of the field to get.
   * @return the value of the field with the given name, or null if not set.
   */
  public Object get(String fieldName) {
    return get(schema().getField(fieldName));
  }

  /**
   * Gets the value of a field.
   * @param field the field to get.
   * @return the value of the given field, or null if not set.
   */
  public Object get(Field field) {
    return get(field.pos());
  }

  /**
   * Gets the value of a field.
   * @param pos the position of the field to get.
   * @return the value of the field with the given position, or null if not set.
   */
  protected Object get(int pos) {
    return record.get(pos);
  }

  /**
   * Sets the value of a field.
   * @param fieldName the name of the field to set.
   * @param value the value to set.
   * @return a reference to the RecordBuilder.
   */
  public GenericRecordBuilder set(String fieldName, Object value) {
    return set(schema().getField(fieldName), value);
  }

  /**
   * Sets the value of a field.
   * @param field the field to set.
   * @param value the value to set.
   * @return a reference to the RecordBuilder.
   */
  public GenericRecordBuilder set(Field field, Object value) {
    return set(field, field.pos(), value);
  }

  /**
   * Sets the value of a field.
   * @param pos the field to set.
   * @param value the value to set.
   * @return a reference to the RecordBuilder.
   */
  protected GenericRecordBuilder set(int pos, Object value) {
    return set(fields()[pos], pos, value);
  }

  /**
   * Sets the value of a field.
   * @param field the field to set.
   * @param pos the position of the field.
   * @param value the value to set.
   * @return a reference to the RecordBuilder.
   */
  private GenericRecordBuilder set(Field field, int pos, Object value) {
    validate(field, value);
    record.put(pos, value);
    fieldSetFlags()[pos] = true;
    return this;
  }

  /**
   * Checks whether a field has been set.
   * @param fieldName the name of the field to check.
   * @return true if the given field is non-null; false otherwise.
   */
  public boolean has(String fieldName) {
    return has(schema().getField(fieldName));
  }

  /**
   * Checks whether a field has been set.
   * @param field the field to check.
   * @return true if the given field is non-null; false otherwise.
   */
  public boolean has(Field field) {
    return has(field.pos());
  }

  /**
   * Checks whether a field has been set.
   * @param pos the position of the field to check.
   * @return true if the given field is non-null; false otherwise.
   */
  protected boolean has(int pos) {
    return fieldSetFlags()[pos];
  }

  /**
   * Clears the value of the given field.
   * @param fieldName the name of the field to clear.
   * @return a reference to the RecordBuilder.
   */
  public GenericRecordBuilder clear(String fieldName) {
    return clear(schema().getField(fieldName));
  }

  /**
   * Clears the value of the given field.
   * @param field the field to clear.
   * @return a reference to the RecordBuilder.
   */
  public GenericRecordBuilder clear(Field field) {
    return clear(field.pos());
  }

  /**
   * Clears the value of the given field.
   * @param pos the position of the field to clear.
   * @return a reference to the RecordBuilder.
   */
  protected GenericRecordBuilder clear(int pos) {
    record.put(pos, null);
    fieldSetFlags()[pos] = false;
    return this;
  }

  @Override
  public Record build() {
    Record record;
    try {
      record = new GenericData.Record(schema());
    } catch (Exception e) {
      throw new AvroRuntimeException(e);
    }

    for (Field field : fields()) {
      Object value;
      try {
        value = getWithDefault(field);
      } catch(IOException e) {
        throw new AvroRuntimeException(e);
      }
      if (value != null) {
        record.put(field.pos(), value);
      }
    }

    return record;
  }

  /**
   * Gets the value of the given field.
   * If the field has been set, the set value is returned (even if it's null).
   * If the field hasn't been set and has a default value, the default value
   * is returned.
   * @param field the field whose value should be retrieved.
   * @return the value set for the given field, the field's default value,
   * or null.
   * @throws IOException
   */
  private Object getWithDefault(Field field) throws IOException {
    return fieldSetFlags()[field.pos()] ?
        record.get(field.pos()) : defaultValue(field);
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = super.hashCode();
    result = prime * result + ((record == null) ? 0 : record.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (!super.equals(obj))
      return false;
    if (getClass() != obj.getClass())
      return false;
    GenericRecordBuilder other = (GenericRecordBuilder) obj;
    if (record == null) {
      if (other.record != null)
        return false;
    } else if (!record.equals(other.record))
      return false;
    return true;
  }
}


text:
var fails = require('../internals/fails');

// Thank's IE8 for his funny defineProperty
module.exports = !fails(function () {
  return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
});


text:
package com.icss.hit.bean;

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

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.icss.hit.bean.interfaces.SysPowerTypeDao;
import com.icss.hit.hibernate.HibernateSessionFactory;

import com.icss.hit.hibernate.vo.ScheduleConfig;
import com.icss.hit.hibernate.vo.SysDept;
import com.icss.hit.hibernate.vo.SysPower;
import com.icss.hit.hibernate.vo.SysPowerType;

public class SysPowerTypeBean implements SysPowerTypeDao {

	public List<SysPowerType> getAllSysPowerType() {
		// TODO Auto-generated method stub
		Session sess = HibernateSessionFactory.getSession();

		Transaction tx = sess.beginTransaction();
		List<SysPowerType> list = null;
		try{
			list = sess.createQuery("from SysPowerType").list();
			tx.commit();
			return list;
		}
		catch(Exception e){
			tx.rollback();
			e.printStackTrace();
			return null;
		}
		finally
		{
			sess.close();
		}
	}

	public boolean addSysPower(SysPower sysPower) {
		// TODO Auto-generated method stub
		Session sess = HibernateSessionFactory.getSession();
		Transaction tx = null;
		try {
			tx = sess.beginTransaction();

			sess.save(sysPower);

			tx.commit();
			return true;
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
			return false;
		} finally {
			sess.close();
		}
	}

	public List<SysPower> getAllSysPower() {
		// TODO Auto-generated method stub
		Session sess = HibernateSessionFactory.getSession();
		Transaction tx = null;
		String hql = "from SysPower sp inner join sp.sysPowerType spt";
		try {
			tx = sess.beginTransaction();

			List l = sess.createQuery(hql).list();
			tx.commit();
			List<SysPower> spList = new ArrayList<SysPower>();
			Iterator it = l.iterator();
			while (it.hasNext()) {
				Object[] obj = (Object[]) it.next();
				SysPower sp = (SysPower) obj[0];
				SysPowerType spt =(SysPowerType)obj[1];
				sp.setSysPowerType(spt);
				spList.add(sp);
			}
			if(spList.size()==0)
			return null ;
			return spList;
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
			return null;
		} finally {
			sess.close();
		}
	}

	public boolean checkSysPower(long spid) {
		// TODO Auto-generated method stub
		Session sess = HibernateSessionFactory.getSession();
		Transaction tx = null;
		String hql = "select count(srp.srpId) from SysRolePower srp inner join srp.sysPower sp where sp.spId = ?";
		try {
			tx = sess.beginTransaction();
			//ÅжÏȨÏÞÒѾ±»Ê¹ÓÃ
			Object o = sess.createQuery(hql).setLong(0, spid).uniqueResult();
			tx.commit();
			if(o!=null)
			{
				if(Integer.parseInt(o.toString()) > 0 )
				{
					return false;
				}
				return true;
			}
			return true;
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
			return false;
		} finally {
			sess.close();
		}
	}

	public boolean deleteSysPower(long spid) {
		// TODO Auto-generated method stub
		Session sess = HibernateSessionFactory.getSession();
		Transaction delDtTrans = null;
		try {
			delDtTrans = sess.beginTransaction();

			sess.delete((SysPower) sess.get(SysPower.class, spid));
			delDtTrans.commit();
			return true;
		} catch (Exception e) {
			delDtTrans.rollback();
			e.printStackTrace();
			return false;
		} finally {
			sess.close();
		}
	}

}


text:
ngDescribe({
    name: 'Test RecusionsHelperService',
    modules: 'app',
    inject: 'RecusionsHelperService',
    tests: function (deps) {

        it('basic test', () => {
            //
        });
    }
});


text:
// Copyright (C) 2010 The Android Open Source Project
//
// 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.

package com.google.gerrit.server.git;

import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.transport.AdvertiseRefsHook;
import org.eclipse.jgit.transport.BaseReceivePack;
import org.eclipse.jgit.transport.UploadPack;

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

/** Exposes only the non refs/changes/ reference names. */
public class ReceiveCommitsAdvertiseRefsHook implements AdvertiseRefsHook {
  @Override
  public void advertiseRefs(UploadPack us) {
    throw new UnsupportedOperationException(
        "ReceiveCommitsAdvertiseRefsHook cannot be used for UploadPack");
  }

  @Override
  public void advertiseRefs(BaseReceivePack rp) {
    Map<String, Ref> oldRefs = rp.getAdvertisedRefs();
    if (oldRefs == null) {
      oldRefs = rp.getRepository().getAllRefs();
    }
    HashMap<String, Ref> r = new HashMap<String, Ref>();
    for (Map.Entry<String, Ref> e : oldRefs.entrySet()) {
      if (!e.getKey().startsWith("refs/changes/")) {
        r.put(e.getKey(), e.getValue());
      }
    }
    rp.setAdvertisedRefs(r, rp.getAdvertisedObjects());
  }
}


text:
title: STIX Blog
redirect_to:
 - http://stixproject.github.io/supporters/
---

[View products that support STIX](http://stixproject.github.io/supporters/)


text:
using System;
using System.Collections;
using System.IO;
using System.Reflection;

using Reporting.Rdl;

namespace Reporting.Rdl
{
    ///// <summary>
    ///// Constant DateTime
    ///// </summary>
    //[Serializable]
    //internal class ConstantDateTime : IExpr
    //{
    //    DateTime _Value;		// value of the constant

    //    /// <summary>
    //    /// passed class name, function name, and args for evaluation
    //    /// </summary>
    //    public ConstantDateTime(string v)
    //    {
    //        _Value = Convert.ToDateTime(v);
    //    }

    //    public ConstantDateTime(DateTime v)
    //    {
    //        _Value = v;
    //    }

    //    public TypeCode GetTypeCode()
    //    {
    //        return TypeCode.DateTime;
    //    }

    //    public bool IsConstant()
    //    {
    //        return true;
    //    }

    //    public IExpr ConstantOptimization()
    //    {	// already constant expression
    //        return this;
    //    }

    //    public object Evaluate(Report rpt, Row row)
    //    {
    //        return _Value;
    //    }

    //    public string EvaluateString(Report rpt, Row row)
    //    {
    //        return Convert.ToString(_Value);
    //    }

    //    public double EvaluateDouble(Report rpt, Row row)
    //    {
    //        return Convert.ToDouble(_Value);
    //    }

    //    public decimal EvaluateDecimal(Report rpt, Row row)
    //    {
    //        return Convert.ToDecimal(_Value);
    //    }

    //    public int EvaluateInt32(Report rpt, Row row)
    //    {
    //        return Convert.ToInt32(_Value);
    //    }

    //    public DateTime EvaluateDateTime(Report rpt, Row row)
    //    {
    //        return _Value;
    //    }

    //    public bool EvaluateBoolean(Report rpt, Row row)
    //    {
    //        return Convert.ToBoolean(_Value);
    //    }
    //}
}


text:
#pragma once

#include "../../blowbox/d3d11/d3d11.h"

#include "../../blowbox/d3d11/d3d11_render_element.h"
#include "../../blowbox/lua/lua_class.h"

namespace blowbox
{
	/**
	* @class blowbox::Quad
	* @brief A Quad element with 4 vertices
	* @author Riko Ophorst
	*/
	class Quad : public D3D11RenderElement
	{
	public:
		/**
		* @brief Default Quad constructor
		*/
		Quad();

		/**
		* @brief Lua Quad constructor
		* @param[in] L (lua_State*) the lua state
		*/
		Quad(lua_State* L);

		/**
		* @brief Default Quad destructor
		*/
		~Quad();

		/**
		* @brief Creates the vertex buffer
		*/
		void Create();

		/**
		* @brief Registers all the lua functions
		* @param[in] L (lua_State*) the lua state
		*/
		static void LuaRegisterFunctions(lua_State* L);

		CLASSNAME("Quad");
	};
}


text:
<?php

namespace Dais\Services\Utility;

use Pimple\Container;
use Pimple\ServiceProviderInterface;
use Dais\Services\Providers\Utility\Length;

class LengthService implements ServiceProviderInterface {

	public function register(Container $app) {
		$app['length'] = function ($app) {
            return new Length;
        };
	}
}


text:
/**
 * @file platform/w32functions.h
 * @brief  internal functions for W32 systems
 * @author Karlson2k (Evgeny Grin)
 */

#include "w32functions.h"
#include <errno.h>
#include <winsock2.h>
#include <string.h>
#include <stdint.h>
#include <time.h>
#include <stdio.h>
#include <stdarg.h>

/**
 * Return errno equivalent of last winsock error
 * @return errno equivalent of last winsock error
 */
int MHD_W32_errno_from_winsock_(void)
{
  switch(WSAGetLastError())
  {
  case 0:                      return 0;
  case WSA_INVALID_HANDLE:     return EBADF;
  case WSA_NOT_ENOUGH_MEMORY:  return ENOMEM;
  case WSA_INVALID_PARAMETER:  return EINVAL;
  case WSAEINTR:               return EINTR;
  case WSAEWOULDBLOCK:         return EWOULDBLOCK;
  case WSAEINPROGRESS:         return EINPROGRESS;
  case WSAEALREADY:            return EALREADY;
  case WSAENOTSOCK:            return ENOTSOCK;
  case WSAEDESTADDRREQ:        return EDESTADDRREQ;
  case WSAEMSGSIZE:            return EMSGSIZE;
  case WSAEPROTOTYPE:          return EPROTOTYPE;
  case WSAENOPROTOOPT:         return ENOPROTOOPT;
  case WSAEPROTONOSUPPORT:     return EPROTONOSUPPORT;
  case WSAESOCKTNOSUPPORT:     return ESOCKTNOSUPPORT;
  case WSAEOPNOTSUPP:          return EOPNOTSUPP;
  case WSAEPFNOSUPPORT:        return EPFNOSUPPORT;
  case WSAEAFNOSUPPORT:        return EAFNOSUPPORT;
  case WSAEADDRINUSE:          return EADDRINUSE;
  case WSAEADDRNOTAVAIL:       return EADDRNOTAVAIL;
  case WSAENETDOWN:            return ENETDOWN;
  case WSAENETUNREACH:         return ENETUNREACH;
  case WSAENETRESET:           return ENETRESET;
  case WSAECONNABORTED:        return ECONNABORTED;
  case WSAECONNRESET:          return ECONNRESET;
  case WSAENOBUFS:             return ENOBUFS;
  case WSAEISCONN:             return EISCONN;
  case WSAENOTCONN:            return ENOTCONN;
  case WSAESHUTDOWN:           return ESHUTDOWN;
  case WSAETOOMANYREFS:        return ETOOMANYREFS;
  case WSAETIMEDOUT:           return ETIMEDOUT;
  case WSAECONNREFUSED:        return ECONNREFUSED;
  case WSAELOOP:               return ELOOP;
  case WSAENAMETOOLONG:        return ENAMETOOLONG;
  case WSAEHOSTDOWN:           return EHOSTDOWN;
  case WSAEHOSTUNREACH:        return EHOSTUNREACH;
  case WSAENOTEMPTY:           return ENOTEMPTY;
  case WSAEPROCLIM:            return EPROCLIM;
  case WSAEUSERS:              return EUSERS;
  case WSAEDQUOT:              return EDQUOT;
  case WSAESTALE:              return ESTALE;
  case WSAEREMOTE:             return EREMOTE;
  case WSAEINVAL:              return EINVAL;
  case WSAEFAULT:              return EFAULT;
  case WSANO_DATA:             return ENODATA;
  /* Rough equivalents */
  case WSAEDISCON:             return ECONNRESET;
  case WSAEINVALIDPROCTABLE:   return EFAULT;
  case WSASYSNOTREADY:
  case WSANOTINITIALISED:
  case WSASYSCALLFAILURE:      return ENOBUFS;
  case WSAVERNOTSUPPORTED:     return EOPNOTSUPP;
  case WSAEREFUSED:            return EIO;
  }
  return EINVAL;
}

/**
 * Return pointer to string description of errnum error
 * Works fine with both standard errno errnums
 * and errnums from MHD_W32_errno_from_winsock_
 * @param errnum the errno or value from MHD_W32_errno_from_winsock_()
 * @return pointer to string description of error
 */
const char* MHD_W32_strerror_(int errnum)
{
  switch(errnum)
  {
  case 0:
    return "No error";
  case EWOULDBLOCK:
    return "Operation would block";
  case EINPROGRESS:
    return "Connection already in progress";
  case EALREADY:
    return "Socket already connected";
  case ENOTSOCK:
    return "Socket operation on non-socket";
  case EDESTADDRREQ:
    return "Destination address required";
  case EMSGSIZE:
    return "Message too long";
  case EPROTOTYPE:
    return "Protocol wrong type for socket";
  case ENOPROTOOPT:
    return "Protocol not available";
  case EPROTONOSUPPORT:
    return "Unknown protocol";
  case ESOCKTNOSUPPORT:
    return "Socket type not supported";
  case EOPNOTSUPP:
    return "Operation not supported on socket";
  case EPFNOSUPPORT:
    return "Protocol family not supported";
  case EAFNOSUPPORT:
    return "Address family not supported by protocol family";
  case EADDRINUSE:
    return "Address already in use";
  case EADDRNOTAVAIL:
    return "Cannot assign requested address";
  case ENETDOWN:
    return "Network is down";
  case ENETUNREACH:
    return "Network is unreachable";
  case ENETRESET:
    return "Network dropped connection on reset";
  case ECONNABORTED:
    return "Software caused connection abort";
  case ECONNRESET:
    return "Connection reset by peer";
  case ENOBUFS:
    return "No system resources available";
  case EISCONN:
    return "Socket is already connected";
  case ENOTCONN:
    return "Socket is not connected";
  case ESHUTDOWN:
    return "Can't send after socket shutdown";
  case ETOOMANYREFS:
    return "Too many references: cannot splice";
  case ETIMEDOUT:
    return "Connection timed out";
  case ECONNREFUSED:
    return "Connection refused";
  case ELOOP:
    return "Cannot translate name";
  case EHOSTDOWN:
    return "Host is down";
  case EHOSTUNREACH:
    return "Host is unreachable";
  case EPROCLIM:
    return "Too many processes";
  case EUSERS:
    return "Too many users";
  case EDQUOT:
    return "Disk quota exceeded";
  case ESTALE:
    return "Stale file handle reference";
  case EREMOTE:
    return "Resource is remote";
  case ENODATA:
    return "No data available";
  }
  return strerror(errnum);
}

/**
 * Return pointer to string description of last winsock error
 * @return pointer to string description of last winsock error
 */
const char* MHD_W32_strerror_last_winsock_(void)
{
  switch (WSAGetLastError())
    {
  case 0:
    return "No error";
  case WSA_INVALID_HANDLE:
    return "Specified event object handle is invalid";
  case WSA_NOT_ENOUGH_MEMORY:
    return "Insufficient memory available";
  case WSA_INVALID_PARAMETER:
    return "One or more parameters are invalid";
  case WSA_OPERATION_ABORTED:
    return "Overlapped operation aborted";
  case WSA_IO_INCOMPLETE:
    return "Overlapped I/O event object not in signaled state";
  case WSA_IO_PENDING:
    return "Overlapped operations will complete later";
  case WSAEINTR:
    return "Interrupted function call";
  case WSAEBADF:
    return "File handle is not valid";
  case WSAEACCES:
    return "Permission denied";
  case WSAEFAULT:
    return "Bad address";
  case WSAEINVAL:
    return "Invalid argument";
  case WSAEMFILE:
    return "Too many open files";
  case WSAEWOULDBLOCK:
    return "Resource temporarily unavailable";
  case WSAEINPROGRESS:
    return "Operation now in progress";
  case WSAEALREADY:
    return "Operation already in progress";
  case WSAENOTSOCK:
    return "Socket operation on nonsocket";
  case WSAEDESTADDRREQ:
    return "Destination address required";
  case WSAEMSGSIZE:
    return "Message too long";
  case WSAEPROTOTYPE:
    return "Protocol wrong type for socket";
  case WSAENOPROTOOPT:
    return "Bad protocol option";
  case WSAEPROTONOSUPPORT:
    return "Protocol not supported";
  case WSAESOCKTNOSUPPORT:
    return "Socket type not supported";
  case WSAEOPNOTSUPP:
    return "Operation not supported";
  case WSAEPFNOSUPPORT:
    return "Protocol family not supported";
  case WSAEAFNOSUPPORT:
    return "Address family not supported by protocol family";
  case WSAEADDRINUSE:
    return "Address already in use";
  case WSAEADDRNOTAVAIL:
    return "Cannot assign requested address";
  case WSAENETDOWN:
    return "Network is down";
  case WSAENETUNREACH:
    return "Network is unreachable";
  case WSAENETRESET:
    return "Network dropped connection on reset";
  case WSAECONNABORTED:
    return "Software caused connection abort";
  case WSAECONNRESET:
    return "Connection reset by peer";
  case WSAENOBUFS:
    return "No buffer space available";
  case WSAEISCONN:
    return "Socket is already connected";
  case WSAENOTCONN:
    return "Socket is not connected";
  case WSAESHUTDOWN:
    return "Cannot send after socket shutdown";
  case WSAETOOMANYREFS:
    return "Too many references";
  case WSAETIMEDOUT:
    return "Connection timed out";
  case WSAECONNREFUSED:
    return "Connection refused";
  case WSAELOOP:
    return "Cannot translate name";
  case WSAENAMETOOLONG:
    return "Name too long";
  case WSAEHOSTDOWN:
    return "Host is down";
  case WSAEHOSTUNREACH:
    return "No route to host";
  case WSAENOTEMPTY:
    return "Directory not empty";
  case WSAEPROCLIM:
    return "Too many processes";
  case WSAEUSERS:
    return "User quota exceeded";
  case WSAEDQUOT:
    return "Disk quota exceeded";
  case WSAESTALE:
    return "Stale file handle reference";
  case WSAEREMOTE:
    return "Item is remote";
  case WSASYSNOTREADY:
    return "Network subsystem is unavailable";
  case WSAVERNOTSUPPORTED:
    return "Winsock.dll version out of range";
  case WSANOTINITIALISED:
    return "Successful WSAStartup not yet performed";
  case WSAEDISCON:
    return "Graceful shutdown in progress";
  case WSAENOMORE:
    return "No more results";
  case WSAECANCELLED:
    return "Call has been canceled";
  case WSAEINVALIDPROCTABLE:
    return "Procedure call table is invalid";
  case WSAEINVALIDPROVIDER:
    return "Service provider is invalid";
  case WSAEPROVIDERFAILEDINIT:
    return "Service provider failed to initialize";
  case WSASYSCALLFAILURE:
    return "System call failure";
  case WSASERVICE_NOT_FOUND:
    return "Service not found";
  case WSATYPE_NOT_FOUND:
    return "Class type not found";
  case WSA_E_NO_MORE:
    return "No more results";
  case WSA_E_CANCELLED:
    return "Call was canceled";
  case WSAEREFUSED:
    return "Database query was refused";
  case WSAHOST_NOT_FOUND:
    return "Host not found";
  case WSATRY_AGAIN:
    return "Nonauthoritative host not found";
  case WSANO_RECOVERY:
    return "This is a nonrecoverable error";
  case WSANO_DATA:
    return "Valid name, no data record of requested type";
  case WSA_QOS_RECEIVERS:
    return "QoS receivers";
  case WSA_QOS_SENDERS:
    return "QoS senders";
  case WSA_QOS_NO_SENDERS:
    return "No QoS senders";
  case WSA_QOS_NO_RECEIVERS:
    return "QoS no receivers";
  case WSA_QOS_REQUEST_CONFIRMED:
    return "QoS request confirmed";
  case WSA_QOS_ADMISSION_FAILURE:
    return "QoS admission error";
  case WSA_QOS_POLICY_FAILURE:
    return "QoS policy failure";
  case WSA_QOS_BAD_STYLE:
    return "QoS bad style";
  case WSA_QOS_BAD_OBJECT:
    return "QoS bad object";
  case WSA_QOS_TRAFFIC_CTRL_ERROR:
    return "QoS traffic control error";
  case WSA_QOS_GENERIC_ERROR:
    return "QoS generic error";
  case WSA_QOS_ESERVICETYPE:
    return "QoS service type error";
  case WSA_QOS_EFLOWSPEC:
    return "QoS flowspec error";
  case WSA_QOS_EPROVSPECBUF:
    return "Invalid QoS provider buffer";
  case WSA_QOS_EFILTERSTYLE:
    return "Invalid QoS filter style";
  case WSA_QOS_EFILTERTYPE:
    return "Invalid QoS filter type";
  case WSA_QOS_EFILTERCOUNT:
    return "Incorrect QoS filter count";
  case WSA_QOS_EOBJLENGTH:
    return "Invalid QoS object length";
  case WSA_QOS_EFLOWCOUNT:
    return "Incorrect QoS flow count";
  case WSA_QOS_EUNKOWNPSOBJ:
    return "Unrecognized QoS object";
  case WSA_QOS_EPOLICYOBJ:
    return "Invalid QoS policy object";
  case WSA_QOS_EFLOWDESC:
    return "Invalid QoS flow descriptor";
  case WSA_QOS_EPSFLOWSPEC:
    return "Invalid QoS provider-specific flowspec";
  case WSA_QOS_EPSFILTERSPEC:
    return "Invalid QoS provider-specific filterspec";
  case WSA_QOS_ESDMODEOBJ:
    return "Invalid QoS shape discard mode object";
  case WSA_QOS_ESHAPERATEOBJ:
    return "Invalid QoS shaping rate object";
  case WSA_QOS_RESERVED_PETYPE:
    return "Reserved policy QoS element type";
    }
  return "Unknown winsock error";
}

/**
 * Set last winsock error to equivalent of given errno value
 * @param errnum the errno value to set
 */
void MHD_W32_set_last_winsock_error_(int errnum)
{
  switch (errnum)
    {
  case 0:
    WSASetLastError(0);
    break;
  case EBADF:
    WSASetLastError(WSA_INVALID_HANDLE);
    break;
  case ENOMEM:
    WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
    break;
  case EINVAL:
    WSASetLastError(WSA_INVALID_PARAMETER);
    break;
  case EINTR:
    WSASetLastError(WSAEINTR);
    break;
  case EWOULDBLOCK:
    WSASetLastError(WSAEWOULDBLOCK);
    break;
  case EINPROGRESS:
    WSASetLastError(WSAEINPROGRESS);
    break;
  case EALREADY:
    WSASetLastError(WSAEALREADY);
    break;
  case ENOTSOCK:
    WSASetLastError(WSAENOTSOCK);
    break;
  case EDESTADDRREQ:
    WSASetLastError(WSAEDESTADDRREQ);
    break;
  case EMSGSIZE:
    WSASetLastError(WSAEMSGSIZE);
    break;
  case EPROTOTYPE:
    WSASetLastError(WSAEPROTOTYPE);
    break;
  case ENOPROTOOPT:
    WSASetLastError(WSAENOPROTOOPT);
    break;
  case EPROTONOSUPPORT:
    WSASetLastError(WSAEPROTONOSUPPORT);
    break;
  case ESOCKTNOSUPPORT:
    WSASetLastError(WSAESOCKTNOSUPPORT);
    break;
  case EOPNOTSUPP:
    WSASetLastError(WSAEOPNOTSUPP);
    break;
  case EPFNOSUPPORT:
    WSASetLastError(WSAEPFNOSUPPORT);
    break;
  case EAFNOSUPPORT:
    WSASetLastError(WSAEAFNOSUPPORT);
    break;
  case EADDRINUSE:
    WSASetLastError(WSAEADDRINUSE);
    break;
  case EADDRNOTAVAIL:
    WSASetLastError(WSAEADDRNOTAVAIL);
    break;
  case ENETDOWN:
    WSASetLastError(WSAENETDOWN);
    break;
  case ENETUNREACH:
    WSASetLastError(WSAENETUNREACH);
    break;
  case ENETRESET:
    WSASetLastError(WSAENETRESET);
    break;
  case ECONNABORTED:
    WSASetLastError(WSAECONNABORTED);
    break;
  case ECONNRESET:
    WSASetLastError(WSAECONNRESET);
    break;
  case ENOBUFS:
    WSASetLastError(WSAENOBUFS);
    break;
  case EISCONN:
    WSASetLastError(WSAEISCONN);
    break;
  case ENOTCONN:
    WSASetLastError(WSAENOTCONN);
    break;
  case ESHUTDOWN:
    WSASetLastError(WSAESHUTDOWN);
    break;
  case ETOOMANYREFS:
    WSASetLastError(WSAETOOMANYREFS);
    break;
  case ETIMEDOUT:
    WSASetLastError(WSAETIMEDOUT);
    break;
  case ECONNREFUSED:
    WSASetLastError(WSAECONNREFUSED);
    break;
  case ELOOP:
    WSASetLastError(WSAELOOP);
    break;
  case ENAMETOOLONG:
    WSASetLastError(WSAENAMETOOLONG);
    break;
  case EHOSTDOWN:
    WSASetLastError(WSAEHOSTDOWN);
    break;
  case EHOSTUNREACH:
    WSASetLastError(WSAEHOSTUNREACH);
    break;
  case ENOTEMPTY:
    WSASetLastError(WSAENOTEMPTY);
    break;
  case EPROCLIM:
    WSASetLastError(WSAEPROCLIM);
    break;
  case EUSERS:
    WSASetLastError(WSAEUSERS);
    break;
  case EDQUOT:
    WSASetLastError(WSAEDQUOT);
    break;
  case ESTALE:
    WSASetLastError(WSAESTALE);
    break;
  case EREMOTE:
    WSASetLastError(WSAEREMOTE);
    break;
  case EFAULT:
    WSASetLastError(WSAEFAULT);
    break;
  case ENODATA:
    WSASetLastError(WSANO_DATA);
    break;
#if EAGAIN != EWOULDBLOCK
  case EAGAIN:
    WSASetLastError(WSAEWOULDBLOCK);
    break;
#endif
  /* Rough equivalent */
  case EIO:
    WSASetLastError(WSAEREFUSED);
    break;

  default: /* Unmapped errors */
    WSASetLastError(WSAENOBUFS);
    break;
    }
}

/**
 * Create pair of mutually connected TCP/IP sockets on loopback address
 * @param sockets_pair array to receive resulted sockets
 * @return zero on success, -1 otherwise
 */
int MHD_W32_pair_of_sockets_(SOCKET sockets_pair[2])
{
  int i;
  if (!sockets_pair)
    {
      errno = EINVAL;
      return -1;
    }

#define PAIRMAXTRYIES 800
  for (i = 0; i < PAIRMAXTRYIES; i++)
    {
      struct sockaddr_in listen_addr;
      SOCKET listen_s;
      static const int c_addinlen = sizeof(struct sockaddr_in); /* help compiler to optimize */
      int addr_len = c_addinlen;
      int opt = 1;

      listen_s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
      if (INVALID_SOCKET == listen_s)
        break; /* can't create even single socket */

      listen_addr.sin_family = AF_INET;
      listen_addr.sin_port = htons(0);
      listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
      if (0 == bind(listen_s, (struct sockaddr*) &listen_addr, c_addinlen)
          && 0 == listen(listen_s, 1)
          && 0 == getsockname(listen_s, (struct sockaddr*) &listen_addr,
                  &addr_len))
        {
          SOCKET client_s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
          if (INVALID_SOCKET != client_s)
            {
              if (0 == ioctlsocket(client_s, FIONBIO, (u_long*) &opt)
                  && (0 == connect(client_s, (struct sockaddr*) &listen_addr, c_addinlen)
                      || WSAGetLastError() == WSAEWOULDBLOCK))
                {
                  struct sockaddr_in accepted_from_addr;
                  addr_len = c_addinlen;
                  SOCKET server_s = accept(listen_s,
                      (struct sockaddr*) &accepted_from_addr, &addr_len);
                  if (INVALID_SOCKET != server_s)
                    {
                      struct sockaddr_in client_addr;
                      addr_len = c_addinlen;
                      opt = 0;
                      if (0 == getsockname(client_s, (struct sockaddr*) &client_addr, &addr_len)
                          && accepted_from_addr.sin_family == client_addr.sin_family
                          && accepted_from_addr.sin_port == client_addr.sin_port
                          && accepted_from_addr.sin_addr.s_addr == client_addr.sin_addr.s_addr
                          && 0 == ioctlsocket(client_s, FIONBIO, (u_long*) &opt)
                          && 0 == ioctlsocket(server_s, FIONBIO, (u_long*) &opt))
                        {
                          closesocket(listen_s);
                          sockets_pair[0] = client_s;
                          sockets_pair[1] = server_s;
                          return 0;
                        }
                      closesocket(server_s);
                    }
                }
              closesocket(client_s);
            }
        }
      closesocket(listen_s);
    }

  sockets_pair[0] = INVALID_SOCKET;
  sockets_pair[1] = INVALID_SOCKET;
  return -1;
}

/**
 * Static variable used by pseudo random number generator
 */
static int32_t rnd_val = 0;
/**
 * Generate 31-bit pseudo random number.
 * Function initialize itself at first call to current time.
 * @return 31-bit pseudo random number.
 */
int MHD_W32_random_(void)
{
  if (0 == rnd_val)
    rnd_val = (int32_t)time(NULL);
  /* stolen from winsup\cygwin\random.cc */
  rnd_val = (16807 * (rnd_val % 127773) - 2836 * (rnd_val / 127773))
               & 0x7fffffff;
  return (int)rnd_val;
}

/* Emulate snprintf function on W32 */
int W32_snprintf(char *__restrict s, size_t n, const char *__restrict format, ...)
{
  int ret;
  va_list args;
  if (0 != n && NULL != s )
  {
    va_start(args, format);
    ret = _vsnprintf(s, n, format, args);
    va_end(args);
    if (n == ret)
      s[n - 1] = 0;
    if (ret >= 0)
      return ret;
  }
  va_start(args, format);
  ret = _vscprintf(format, args);
  va_end(args);
  if (0 <= ret && 0 != n && NULL == s)
    return -1;

  return ret;
}

#ifdef _MSC_FULL_VER
/**
 * Set thread name
 * @param thread_id ID of thread, -1 for current thread
 * @param thread_name name to set
 */
void W32_SetThreadName(const DWORD thread_id, const char *thread_name)
{
  static const DWORD VC_SETNAME_EXC = 0x406D1388;
#pragma pack(push,8)
  struct thread_info_struct
  {
    DWORD type;   // Must be 0x1000.
    LPCSTR name;  // Pointer to name (in user address space).
    DWORD ID;     // Thread ID (-1=caller thread).
    DWORD flags;  // Reserved for future use, must be zero.
  } thread_info;
#pragma pack(pop)

  if (NULL == thread_name)
    return;

  thread_info.type  = 0x1000;
  thread_info.name  = thread_name;
  thread_info.ID    = thread_id;
  thread_info.flags = 0;

  __try
  { /* This exception is intercepted by debugger */
    RaiseException(VC_SETNAME_EXC, 0, sizeof(thread_info) / sizeof(ULONG_PTR), (ULONG_PTR*)&thread_info);
  }
  __except (EXCEPTION_EXECUTE_HANDLER)
  {}
}
#endif /* _MSC_FULL_VER */


text:
package com.agoda.kafka.connector.jdbc.services

import java.sql._
import java.util.{GregorianCalendar, TimeZone}

import com.agoda.kafka.connector.jdbc.JdbcSourceConnectorConstants
import com.agoda.kafka.connector.jdbc.models.DatabaseProduct.{MsSQL, MySQL}
import com.agoda.kafka.connector.jdbc.models.Mode.{IncrementingMode, TimestampMode}
import com.agoda.kafka.connector.jdbc.utils.DataConverter
import org.apache.kafka.connect.data.{Field, Schema, Struct}
import org.apache.kafka.connect.source.SourceRecord
import org.mockito.Mockito._
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{Matchers, WordSpec}

import scala.collection.JavaConverters._
import scala.collection.mutable.ListBuffer
import scala.util.Success

class TimeIdBasedDataServiceTest extends WordSpec with Matchers with MockitoSugar {

  "Time ID Based Data Service" should {

    val dataConverter = mock[DataConverter]

    val UTC_CALENDAR = new GregorianCalendar(TimeZone.getTimeZone("UTC"))

    val timeIdBasedDataServiceMssql =
      TimeIdBasedDataService(
        databaseProduct = MsSQL,
        storedProcedureName = "stored-procedure",
        batchSize = 100,
        batchSizeVariableName = "batch-size-variable",
        timestampVariableName = "timestamp-variable",
        timestampOffset = 0L,
        timestampFieldName = "time",
        incrementingVariableName = "incrementing-variable",
        incrementingOffset = 0L,
        incrementingFieldName = "id",
        topic = "time-id-based-data-topic",
        keyFieldOpt = None,
        dataConverter = dataConverter,
        calendar = UTC_CALENDAR
      )

    val timeIdBasedDataServiceMysql =
      TimeIdBasedDataService(
        databaseProduct = MySQL,
        storedProcedureName = "stored-procedure",
        batchSize = 100,
        batchSizeVariableName = "batch-size-variable",
        timestampVariableName = "timestamp-variable",
        timestampOffset = 0L,
        timestampFieldName = "time",
        incrementingVariableName = "incrementing-variable",
        incrementingOffset = 0L,
        incrementingFieldName = "id",
        topic = "time-id-based-data-topic",
        keyFieldOpt = None,
        dataConverter = dataConverter,
        calendar = UTC_CALENDAR
      )

    val timestamp = new Timestamp(0L)

    "create correct prepared statement for Mssql" in {
      val connection = mock[Connection]
      val statement = mock[PreparedStatement]

      when(connection.prepareStatement("EXECUTE stored-procedure @timestamp-variable = ?, @incrementing-variable = ?, @batch-size-variable = ?")).thenReturn(statement)
      doNothing().when(statement).setTimestamp(1, timestamp, UTC_CALENDAR)
      doNothing().when(statement).setObject(2, 0L)
      doNothing().when(statement).setObject(3, 100)

      timeIdBasedDataServiceMssql.createPreparedStatement(connection)

      verify(connection).prepareStatement("EXECUTE stored-procedure @timestamp-variable = ?, @incrementing-variable = ?, @batch-size-variable = ?")
      verify(statement).setTimestamp(1, timestamp, UTC_CALENDAR)
      verify(statement).setObject(2, 0L)
      verify(statement).setObject(3, 100)
    }

    "create correct prepared statement for Mysql" in {
      val connection = mock[Connection]
      val statement = mock[PreparedStatement]

      when(connection.prepareStatement("CALL stored-procedure (@timestamp-variable := ?, @incrementing-variable := ?, @batch-size-variable := ?)")).thenReturn(statement)
      doNothing().when(statement).setTimestamp(1, timestamp, UTC_CALENDAR)
      doNothing().when(statement).setObject(2, 0L)
      doNothing().when(statement).setObject(3, 100)

      timeIdBasedDataServiceMysql.createPreparedStatement(connection)

      verify(connection).prepareStatement("CALL stored-procedure (@timestamp-variable := ?, @incrementing-variable := ?, @batch-size-variable := ?)")
      verify(statement).setTimestamp(1, timestamp, UTC_CALENDAR)
      verify(statement).setObject(2, 0L)
      verify(statement).setObject(3, 100)
    }

    "create correct string representation" in {
      timeIdBasedDataServiceMssql.toString shouldBe
        s"""
           |{
           |   "name" : "TimeIdBasedDataService"
           |   "mode" : "timestamp+incrementing"
           |   "stored-procedure.name" : "stored-procedure"
           |}
    """.stripMargin
    }

    "extract records" in {
      val resultSet = mock[ResultSet]
      val schema = mock[Schema]
      val field = mock[Field]
      val struct = mock[Struct]

      when(schema.field("id")).thenReturn(field)
      when(field.schema()).thenReturn(Schema.INT32_SCHEMA)
      when(resultSet.next()).thenReturn(true, true, false)
      when(dataConverter.convertRecord(schema, resultSet)).thenReturn(Success(struct))
      when(struct.getInt32("id")).thenReturn(1, 2)
      when(struct.get("time")).thenReturn(new Date(1L), new Date(2L))

      timeIdBasedDataServiceMssql.extractRecords(resultSet, schema).toString shouldBe
        Success(
          ListBuffer(
            new SourceRecord(
              Map(JdbcSourceConnectorConstants.STORED_PROCEDURE_NAME_KEY -> "stored-procedure").asJava,
              Map(TimestampMode.entryName -> 1L, IncrementingMode.entryName -> 1).asJava,
              "time-id-based-data-topic", schema, struct
            ),
            new SourceRecord(
              Map(JdbcSourceConnectorConstants.STORED_PROCEDURE_NAME_KEY -> "stored-procedure").asJava,
              Map(TimestampMode.entryName -> 2L, IncrementingMode.entryName -> 2).asJava,
              "time-id-based-data-topic", schema, struct
            )
          )
        ).toString
      timeIdBasedDataServiceMssql.timestampOffset shouldBe 2L
      timeIdBasedDataServiceMssql.incrementingOffset shouldBe 2
    }

    "return nothing when record ids and timestamps are smaller than offset id" in {
      val timeIdBasedDataServiceWithLargerOffsetMssql = timeIdBasedDataServiceMssql.copy(incrementingOffset = 3, timestampOffset = 3L)
      val resultSet = mock[ResultSet]
      val schema = mock[Schema]
      val field = mock[Field]
      val struct = mock[Struct]

      when(schema.field("id")).thenReturn(field)
      when(field.schema()).thenReturn(Schema.INT32_SCHEMA)
      when(resultSet.next()).thenReturn(true, true, false)
      when(dataConverter.convertRecord(schema, resultSet)).thenReturn(Success(struct))
      when(struct.getInt32("id")).thenReturn(1, 2)
      when(struct.get("time")).thenReturn(new Date(1L), new Date(2L))

      timeIdBasedDataServiceWithLargerOffsetMssql.extractRecords(resultSet, schema) shouldBe Success(ListBuffer())

      timeIdBasedDataServiceWithLargerOffsetMssql.timestampOffset shouldBe 3L
      timeIdBasedDataServiceWithLargerOffsetMssql.incrementingOffset shouldBe 3
    }

    "return record when the record timestamps are equals but record ids are than offset id" in {
      val timeIdBasedDataServiceWithLargerOffsetMssql = timeIdBasedDataServiceMssql.copy(incrementingOffset = 3, timestampOffset = 3L)
      val resultSet = mock[ResultSet]
      val schema = mock[Schema]
      val field = mock[Field]
      val struct = mock[Struct]

      when(schema.field("id")).thenReturn(field)
      when(field.schema()).thenReturn(Schema.INT32_SCHEMA)
      when(resultSet.next()).thenReturn(true, true, false)
      when(dataConverter.convertRecord(schema, resultSet)).thenReturn(Success(struct))
      when(struct.getInt32("id")).thenReturn(4, 5)
      when(struct.get("time")).thenReturn(new Date(3L), new Date(3L))

      timeIdBasedDataServiceWithLargerOffsetMssql.extractRecords(resultSet, schema).toString shouldBe
        Success(
          ListBuffer(
            new SourceRecord(
              Map(JdbcSourceConnectorConstants.STORED_PROCEDURE_NAME_KEY -> "stored-procedure").asJava,
              Map(TimestampMode.entryName -> 3L, IncrementingMode.entryName -> 4).asJava,
              "time-id-based-data-topic", schema, struct
            ),
            new SourceRecord(
              Map(JdbcSourceConnectorConstants.STORED_PROCEDURE_NAME_KEY -> "stored-procedure").asJava,
              Map(TimestampMode.entryName -> 3L, IncrementingMode.entryName -> 5).asJava,
              "time-id-based-data-topic", schema, struct
            )
          )
        ).toString

      timeIdBasedDataServiceWithLargerOffsetMssql.timestampOffset shouldBe 3L
      timeIdBasedDataServiceWithLargerOffsetMssql.incrementingOffset shouldBe 5L
    }

    "extract records with key" in {
      val timeIdBasedDataServiceWithKeyMysql = timeIdBasedDataServiceMysql.copy(keyFieldOpt = Some("key"))
      val resultSet = mock[ResultSet]
      val schema = mock[Schema]
      val field = mock[Field]
      val struct = mock[Struct]

      when(schema.field("id")).thenReturn(field)
      when(field.schema()).thenReturn(Schema.INT32_SCHEMA)
      when(resultSet.next()).thenReturn(true, true, false)
      when(dataConverter.convertRecord(schema, resultSet)).thenReturn(Success(struct))
      when(struct.getInt32("id")).thenReturn(1, 2)
      when(struct.get("time")).thenReturn(new Date(1L), new Date(2L))
      when(struct.get("key")).thenReturn("key-1", "key-2")

      timeIdBasedDataServiceWithKeyMysql.extractRecords(resultSet, schema).toString shouldBe
        Success(
          ListBuffer(
            new SourceRecord(
              Map(JdbcSourceConnectorConstants.STORED_PROCEDURE_NAME_KEY -> "stored-procedure").asJava,
              Map(TimestampMode.entryName -> 1L, IncrementingMode.entryName -> 1).asJava,
              "time-id-based-data-topic", null, schema, "key-1", schema, struct
            ),
            new SourceRecord(
              Map(JdbcSourceConnectorConstants.STORED_PROCEDURE_NAME_KEY -> "stored-procedure").asJava,
              Map(TimestampMode.entryName -> 2L, IncrementingMode.entryName -> 2).asJava,
              "time-id-based-data-topic", null, schema, "key-2", schema, struct
            )
          )
        ).toString
    }

    "returns no record when id field is not of type integer" in {
      val resultSet = mock[ResultSet]
      val schema = mock[Schema]
      val field = mock[Field]
      val struct = mock[Struct]

      when(schema.field("id")).thenReturn(field)
      when(field.schema()).thenReturn(Schema.STRING_SCHEMA)
      when(resultSet.next()).thenReturn(true, false)
      when(dataConverter.convertRecord(schema, resultSet)).thenReturn(Success(struct))
      when(struct.get("time")).thenReturn(new Date(1L), Nil)

      timeIdBasedDataServiceMysql.extractRecords(resultSet, schema) shouldBe Success(ListBuffer())
    }
  }
}


text:
/*****************************************************************************
 HandleManager.cpp

 One of the most difficult problems to track down is when stale cryptoki handles
 for e.g. keys, objects and sessions get reused by a misbehaving application.
 Especialy when handles that became invalid have since been reused.
 A simple solution to this is to never reuse a handle once it has been issued
 and subsequently invalidated.

 The handle manager tracks issued handles along with what kind of object
 is presented by the handle and an actual pointer to the object in question.

 Issued handles are unique per application run. All session and object handles
 use the same handle manager and therefore there will never be e.g. a session
 with the same handle as an object.

 *****************************************************************************/

#include "HandleManager.h"
#include "log.h"

// Constructor
HandleManager::HandleManager()
{
	handlesMutex = MutexFactory::i()->getMutex();
	handleCounter = 0;
}

// Destructor
HandleManager::~HandleManager()
{

	MutexFactory::i()->recycleMutex(handlesMutex);
}

CK_SESSION_HANDLE HandleManager::addSession(CK_SLOT_ID slotID, CK_VOID_PTR session)
{
	MutexLocker lock(handlesMutex);

	Handle h( CKH_SESSION, slotID );
	h.object = session;
	handles[++handleCounter] = h;
	return (CK_SESSION_HANDLE)handleCounter;
}

CK_VOID_PTR HandleManager::getSession(const CK_SESSION_HANDLE hSession)
{
	MutexLocker lock(handlesMutex);

	std::map< CK_ULONG, Handle>::iterator it = handles.find(hSession);
	if (it == handles.end() || CKH_SESSION != it->second.kind)
		return NULL_PTR;
	return it->second.object;
}

CK_OBJECT_HANDLE HandleManager::addSessionObject(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession, bool isPrivate, CK_VOID_PTR object)
{
	MutexLocker lock(handlesMutex);

	// Return existing handle when the object has already been registered.
	std::map< CK_VOID_PTR, CK_ULONG>::iterator oit = objects.find(object);
	if (oit != objects.end()) {
		std::map< CK_ULONG, Handle>::iterator hit = handles.find(oit->second);
		if (hit == handles.end() || CKH_OBJECT != hit->second.kind || slotID != hit->second.slotID) {
			objects.erase(oit);
			return CK_INVALID_HANDLE;
		} else
			return oit->second;
	}

	Handle h( CKH_OBJECT, slotID, hSession );
	h.isPrivate = isPrivate;
	h.object = object;
	handles[++handleCounter] = h;
	objects[object] = handleCounter;
	return (CK_OBJECT_HANDLE)handleCounter;
}

CK_OBJECT_HANDLE HandleManager::addTokenObject(CK_SLOT_ID slotID, bool isPrivate, CK_VOID_PTR object)
{
	MutexLocker lock(handlesMutex);

	// Return existing handle when the object has already been registered.
	std::map< CK_VOID_PTR, CK_ULONG>::iterator oit = objects.find(object);
	if (oit != objects.end()) {
		std::map< CK_ULONG, Handle>::iterator hit = handles.find(oit->second);
		if (hit == handles.end() || CKH_OBJECT != hit->second.kind || slotID != hit->second.slotID) {
			objects.erase(oit);
			return CK_INVALID_HANDLE;
		} else
			return oit->second;
	}

	// Token objects are not associated with a specific session.
	Handle h( CKH_OBJECT, slotID );
	h.isPrivate = isPrivate;
	h.object = object;
	handles[++handleCounter] = h;
	objects[object] = handleCounter;
	return (CK_OBJECT_HANDLE)handleCounter;
}

CK_VOID_PTR HandleManager::getObject(const CK_OBJECT_HANDLE hObject)
{
	MutexLocker lock(handlesMutex);

	std::map< CK_ULONG, Handle>::iterator it = handles.find(hObject);
	if (it == handles.end() || CKH_OBJECT != it->second.kind )
		return NULL_PTR;
	return it->second.object;
}

CK_OBJECT_HANDLE HandleManager::getObjectHandle(CK_VOID_PTR object)
{
	MutexLocker lock(handlesMutex);

	std::map< CK_VOID_PTR, CK_ULONG>::iterator it = objects.find(object);
	if (it == objects.end())
		return CK_INVALID_HANDLE;
	return it->second;
}

void HandleManager::destroyObject(const CK_OBJECT_HANDLE hObject)
{
	MutexLocker lock(handlesMutex);

	std::map< CK_ULONG, Handle>::iterator it = handles.find(hObject);
	if (it != handles.end() && CKH_OBJECT == it->second.kind) {
		objects.erase(it->second.object);
		handles.erase(it);
	}
}

void HandleManager::sessionClosed(const CK_SESSION_HANDLE hSession)
{
	CK_SLOT_ID slotID;
	{
		MutexLocker lock(handlesMutex);

		std::map< CK_ULONG, Handle>::iterator it = handles.find(hSession);
		if (it == handles.end() || CKH_SESSION != it->second.kind)
			return; // Unable to find the specified session.

		slotID = it->second.slotID;

		// session closed, so we can erase information about it.
		handles.erase(it);

		// Erase all session object handles associated with the given session handle.
		CK_ULONG openSessionCount = 0;
		for (it = handles.begin(); it != handles.end(); ) {
			Handle &h = it->second;
			if (CKH_SESSION == h.kind && slotID == h.slotID) {
				++openSessionCount; // another session is open for this slotID.
			} else {
				if (CKH_OBJECT == h.kind && hSession == h.hSession) {
					// A session object is present for the given session, so erase it.
					objects.erase(it->second.object);
					// Iterator post-incrementing (it++) will return a copy of the original it (which points to handle to be deleted).
					handles.erase(it++);
					continue;
				}
			}
			++it;
		}

		 // We are done when there are still sessions open.
		if (openSessionCount)
			return;
	}

	// No more sessions open for this token, so remove all object handles that are still valid for the given slotID.
	allSessionsClosed(slotID);
}

void HandleManager::allSessionsClosed(const CK_SLOT_ID slotID)
{
	MutexLocker lock(handlesMutex);

	// Erase all "session", "session object" and "token object" handles for a given slot id.
	std::map< CK_ULONG, Handle>::iterator it;
	for (it = handles.begin(); it != handles.end(); ) {
		Handle &h = it->second;
		if (slotID == h.slotID) {
			if (CKH_OBJECT == it->second.kind)
				objects.erase(it->second.object);
			// Iterator post-incrementing (it++) will return a copy of the original it (which points to handle to be deleted).
			handles.erase(it++);
			continue;
		}
		++it;
	}
}

void HandleManager::tokenLoggedOut(const CK_SLOT_ID slotID)
{
	MutexLocker lock(handlesMutex);

	// Erase all private "token object" or "session object" handles for a given slot id.
	std::map< CK_ULONG, Handle>::iterator it;
	for (it = handles.begin(); it != handles.end(); ) {
		Handle &h = it->second;
		if (CKH_OBJECT == h.kind && slotID == h.slotID && h.isPrivate) {
			// A private object is present for the given slotID so we need to remove it.
			objects.erase(it->second.object);
			// Iterator post-incrementing (it++) will return a copy of the original it (which points to handle to be deleted).
			handles.erase(it++);
			continue;
		}
		++it;
	}
}


text:
pthread_cond_t* getConditionPtr(org_xmlvm_runtime_Condition* me)
{
    return (pthread_cond_t*)(me->fields.org_xmlvm_runtime_Condition.pthreadCondT_);
}

void nativeConditionCleanup(void* me, void* client_data)
{
    pthread_cond_t* condPtr = getConditionPtr((org_xmlvm_runtime_Condition*)me);
    pthread_cond_destroy(condPtr);
    free(condPtr);
}

//XMLVM_END_NATIVE_IMPLEMENTATION

void org_xmlvm_runtime_Condition_initNativeConditionInstance__(JAVA_OBJECT me)
{
    //XMLVM_BEGIN_NATIVE[org_xmlvm_runtime_Condition_initNativeConditionInstance__]
    ((org_xmlvm_runtime_Condition*)me)->fields.org_xmlvm_runtime_Condition.pthreadCondT_ = malloc(sizeof(pthread_cond_t));
    pthread_cond_init(getConditionPtr(me), NULL);

    // Register a finalizer for native cleanup
    XMLVM_FINALIZE(me, nativeConditionCleanup);
    //XMLVM_END_NATIVE
}

void org_xmlvm_runtime_Condition_wait___org_xmlvm_runtime_Mutex(JAVA_OBJECT me, JAVA_OBJECT n1)
{
    //XMLVM_BEGIN_NATIVE[org_xmlvm_runtime_Condition_wait___org_xmlvm_runtime_Mutex]
    pthread_cond_t* condPtr = getConditionPtr(me);
    JAVA_OBJECT mutex = ((org_xmlvm_runtime_Mutex*)n1)->fields.org_xmlvm_runtime_Mutex.nativeMutex_;
    int result = pthread_cond_wait(condPtr, mutex);
    if (result != 0) {
        printf("ERROR: pthread_cond_wait response was %i\n", result);
    }
    //XMLVM_END_NATIVE
}

JAVA_BOOLEAN org_xmlvm_runtime_Condition_waitOrTimeout___org_xmlvm_runtime_Mutex_long(JAVA_OBJECT me, JAVA_OBJECT n1, JAVA_LONG n2)
{
    //XMLVM_BEGIN_NATIVE[org_xmlvm_runtime_Condition_waitOrTimeout___org_xmlvm_runtime_Mutex_long]
    pthread_cond_t* condPtr = getConditionPtr(me);
    JAVA_OBJECT mutex = ((org_xmlvm_runtime_Mutex*)n1)->fields.org_xmlvm_runtime_Mutex.nativeMutex_;

    struct timeval now;
    gettimeofday(&now, NULL);

    struct timespec to;
    // To avoid an overflow error, we drop precision on microseconds (usec) in favor of milliseconds.
    // The loss of precision at the microsecond level is not of concern.
    JAVA_LONG msec = (now.tv_usec / 1000) + n2;
    to.tv_sec = now.tv_sec + (msec / 1000);
    to.tv_nsec = (msec % 1000) * 1000000;

    int result = pthread_cond_timedwait(condPtr, mutex, &to);
    int timedOut = 0;
    if (result == ETIMEDOUT) {
        timedOut = 1;
    } else if (result != 0) {
        printf("ERROR: pthread_cond_timedwait response was %i\n", result);
    }
    return timedOut;
    //XMLVM_END_NATIVE
}

void org_xmlvm_runtime_Condition_signal__(JAVA_OBJECT me)
{
    //XMLVM_BEGIN_NATIVE[org_xmlvm_runtime_Condition_signal__]
    XMLVM_UNIMPLEMENTED_NATIVE_METHOD();
    //XMLVM_END_NATIVE
}

void org_xmlvm_runtime_Condition_broadcast__(JAVA_OBJECT me)
{
    //XMLVM_BEGIN_NATIVE[org_xmlvm_runtime_Condition_broadcast__]
    pthread_cond_t* condPtr = getConditionPtr(me);
    int result = pthread_cond_broadcast(condPtr);
    if (result != 0) {
        printf("ERROR: pthread_cond_broadcast response was %i\n", result);
    }
    //XMLVM_END_NATIVE
}

void xmlvm_init_native_org_xmlvm_runtime_Condition()
{
    //XMLVM_BEGIN_NATIVE_IMPLEMENTATION_INIT
    //XMLVM_END_NATIVE_IMPLEMENTATION_INIT
#ifdef XMLVM_VTABLE_IDX_org_xmlvm_runtime_Condition_wait___org_xmlvm_runtime_Mutex
    __TIB_org_xmlvm_runtime_Condition.vtable[XMLVM_VTABLE_IDX_org_xmlvm_runtime_Condition_wait___org_xmlvm_runtime_Mutex] =
        (VTABLE_PTR) org_xmlvm_runtime_Condition_wait___org_xmlvm_runtime_Mutex;
#endif
#ifdef XMLVM_VTABLE_IDX_org_xmlvm_runtime_Condition_waitOrTimeout___org_xmlvm_runtime_Mutex_long
    __TIB_org_xmlvm_runtime_Condition.vtable[XMLVM_VTABLE_IDX_org_xmlvm_runtime_Condition_waitOrTimeout___org_xmlvm_runtime_Mutex_long] =
        (VTABLE_PTR) org_xmlvm_runtime_Condition_waitOrTimeout___org_xmlvm_runtime_Mutex_long;
#endif
#ifdef XMLVM_VTABLE_IDX_org_xmlvm_runtime_Condition_signal__
    __TIB_org_xmlvm_runtime_Condition.vtable[XMLVM_VTABLE_IDX_org_xmlvm_runtime_Condition_signal__] =
        (VTABLE_PTR) org_xmlvm_runtime_Condition_signal__;
#endif
#ifdef XMLVM_VTABLE_IDX_org_xmlvm_runtime_Condition_broadcast__
    __TIB_org_xmlvm_runtime_Condition.vtable[XMLVM_VTABLE_IDX_org_xmlvm_runtime_Condition_broadcast__] =
        (VTABLE_PTR) org_xmlvm_runtime_Condition_broadcast__;
#endif
}


text:
	#define _INC_STRING_

	#include "../include/common.h"

	int k_strlen(const char* str);
	int k_strcmp(char *str1, char *str2);
	int k_strcpy(char* dest, const char* src);
	int k_strcat(char* dest, const char* src);
	void k_itoa(int n, char s[]);
	void k_reverse(char s[]);

#endif


text:
from temporaldrt import DRS, DrtLambdaExpression, DrtApplicationExpression, DrtAbstractVariableExpression, DrtNegatedExpression, DrsDrawer
from nltk.sem.logic import BinaryExpression

def _handle(self, expression, command, x=0, y=0):
    """
    @param expression: the expression to handle
    @param command: the function to apply, either _draw_command or _visit_command
    @param x: the top of the current drawing area
    @param y: the left side of the current drawing area
    @return: the bottom-rightmost point
    """
    if command == self._visit_command:
        #if we don't need to draw the item, then we can use the cached values
        try:
            #attempt to retrieve cached values
            right = expression._drawing_width + x
            bottom = expression._drawing_height + y
            return (right, bottom)
        except AttributeError:
            #the values have not been cached yet, so compute them
            pass

    if isinstance(expression, DrtAbstractVariableExpression):
        factory = self._handle_VariableExpression
    elif isinstance(expression, DRS):
        factory = self._handle_DRS
    elif isinstance(expression, DrtNegatedExpression):
        factory = self._handle_NegatedExpression
    elif isinstance(expression, DrtLambdaExpression):
        factory = self._handle_LambdaExpression
    elif isinstance(expression, BinaryExpression):
        factory = self._handle_BinaryExpression
    elif isinstance(expression, DrtApplicationExpression):
        factory = self._handle_ApplicationExpression
    else:
        raise Exception, expression.__class__.__name__

    (right, bottom) = factory(expression, command, x, y)

    #cache the values
    expression._drawing_width = right - x
    expression._drawing_height = bottom - y

    return (right, bottom)

DrsDrawer._handle = _handle


text:
using namespace cv;

void CopyImageStreamToColorMat(cv::Mat &CMat)
{
	pxcStatus sts=psm->AcquireFrame(true);
	if (sts<PXC_STATUS_NO_ERROR)
	{
		cout<<"Couldn't acquire frame ! "<<endl;
		system("pause");
		exit(1);
	}

	PXCImage *colorIm=0;
	PXCImage::ImageData first_data;
	PXCCapture::Sample *sample=psm->QuerySample();
	do
	{
		colorIm = sample->color;
		if(colorIm)
		{
			sts=colorIm->AcquireAccess(PXCImage::ACCESS_READ,PXCImage::PIXEL_FORMAT_RGB24,&first_data);
			if(PXC_STATUS_NO_ERROR == sts)
			{
				//Copy Color stream data to an openc ColorMat
				memcpy(CMat.data,first_data.planes[0],sizeof(unsigned char) * 3 * 640 * 480);
				colorIm->ReleaseAccess(&first_data);
			}
			else
				cout<<"CAN'T ACQUIRE COLOR IMAGE DATA"<<endl;
		}
	}
	while(sample==0 || colorIm==0);
}

void CopyColorStreamToColorMat(PXCImage *image,PXCImage::ImageData &data,cv::Mat &ColorMat)
{
	pxcStatus sts=image->AcquireAccess(PXCImage::ACCESS_READ,PXCImage::PIXEL_FORMAT_RGB24,&data);

	if(sts==PXC_STATUS_NO_ERROR)
	{
		//Copy Color stream data to an openc ColorMat
		memcpy(ColorMat.data,data.planes[0],sizeof(unsigned char) * 3 * 640 * 480);
		image->ReleaseAccess(&data);
	}
	else{
		cout<<"CAN'T ACQUIRE COLOR IMAGE DATA"<<endl;
		system("pause");
		exit(0);
	}
}

void CopyDepthImageMappedToColor_ToMat(PXCImage *ColorImage,PXCImage *DepthImage,PXCImage::ImageData &data,cv::Mat &MappedDepthMat)
{
	PXCImage* mapped=projection->CreateDepthImageMappedToColor(DepthImage,ColorImage);
	pxcStatus sts=mapped->AcquireAccess(PXCImage::ACCESS_READ,&data);
	if(sts==PXC_STATUS_NO_ERROR )
	{
		memcpy(MappedDepthMat.data,data.planes[0],sizeof(unsigned short) * 640 * 480);
		//MappedDepthMat=MappedDepthMat/255;

		MappedDepthMat.convertTo(normalizedMappedDepthMat,CV_32F);

		//normalizedMappedDepthMat has float depth values in mm
		normalizedMappedDepthMat=-normalizedMappedDepthMat/1000.0f;
		//normalizedMappedDepthMat has float depth values in m
		double A=(farValue*nearValue)/(farValue-nearValue);
		double B=farValue/(farValue-nearValue);
		for(int i=0;i<normalizedMappedDepthMat.rows;i++)
		{
			for(int j=0;j<normalizedMappedDepthMat.cols;j++)
			{
				normalizedMappedDepthMat.at<float>(i,j)=(A/normalizedMappedDepthMat.at<float>(i,j))+B;
			}
		}
		mapped->ReleaseAccess(&data);
	}
}

void CopyDepthStreamToDepthMatAndGetUVMap(PXCImage *image,PXCImage::ImageData &data,PXCPointF32* uvmap,cv::Mat &DepthMat)
{
	pxcStatus sts=image->AcquireAccess(PXCImage::ACCESS_READ,&data);
	if(sts==PXC_STATUS_NO_ERROR )
	{
		//Pass depth data to depthValues pointer to array
		depthValues_mm=(pxcU16*)data.planes[0];
		//memcpy(depthValues_mm,data.planes[0], sizeof(unsigned short)*640*480);
		//cout<<sizeof(unsigned short)<<endl;
		memcpy(DepthMat.data,data.planes[0],sizeof(unsigned short) * 640 * 480);
		projection->QueryUVMap(image, uvmap);
		//Range of Mat 0-255(opencv way to draw depth) instead of 0-1 initially
		DepthMat=DepthMat*255;
		image->ReleaseAccess(&data);

	}
	else
	{
		cout<<"CAN'T ACQUIRE Depth IMAGE DATA"<<endl;

	}
}

void CopyBlobToBlobMat(PXCBlobData::IBlob *pBlob, PXCImage *blobIm,PXCImage::ImageData &data)
{
	pBlob->QuerySegmentationImage(blobIm);
	pxcStatus sts=blobIm->AcquireAccess(PXCImage::ACCESS_READ,&data);
	if(PXC_STATUS_NO_ERROR == sts)
	{
		memcpy(BlobMat.data,data.planes[0], sizeof(char) * 640 * 480);
		blobIm->ReleaseAccess(&data);
	}
	else
	{
		//BlobMat.setTo(Scalar(0));
		blobIm->ReleaseAccess(&data);
	}

}


text:
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*  Chunk I/O
 *  =========
 *  Copyright 2018 Eduardo Silva <eduardo@monkey.io>
 *
 *  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.
 */

#ifndef CIO_LOG_H
#define CIO_LOG_H

#include <errno.h>

#define CIO_LOG_BUF_SIZE  256

void cio_log_print(void *ctx, int level, const char *file, int line,
                     const char *fmt, ...);
int cio_errno_print(int errnum, const char *file, int line);

#define cio_log_error(ctx, fmt, ...)                    \
    cio_log_print(ctx, CIO_LOG_ERROR, __FILENAME__,     \
                  __LINE__, fmt, ##__VA_ARGS__)

#define cio_log_warn(ctx, fmt, ...)                 \
    cio_log_print(ctx, CIO_LOG_WARN, __FILENAME__,  \
                  __LINE__, fmt, ##__VA_ARGS__)

#define cio_log_info(ctx, fmt, ...)                 \
    cio_log_print(ctx, CIO_LOG_INFO, __FILENAME__,  \
                  __LINE__, fmt, ##__VA_ARGS__)

#define cio_log_debug(ctx, fmt, ...)                \
    cio_log_print(ctx, CIO_LOG_DEBUG, __FILENAME__, \
                  __LINE__, fmt, ##__VA_ARGS__)

#define cio_log_trace(ctx, fmt, ...)                \
    cio_log_print(ctx, CIO_LOG_TRACE, __FILENAME__, \
                  __LINE__, fmt, ##__VA_ARGS__)

#ifdef __FILENAME__
#define cio_errno() cio_errno_print(errno, __FILENAME__, __LINE__)
#else
#define cio_errno() cio_errno_print(errno, __FILE__, __LINE__)
#endif

#ifdef _WIN32
void cio_winapi_error_print(const char *func, int line);
#define cio_winapi_error() cio_winapi_error_print(__func__, __LINE__)
#endif

#endif


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>fisx: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

fisx

fisx::TransmissionTable Member List

This is the complete list of members for fisx::TransmissionTable, including all inherited members.

getComment() const (defined in fisx::TransmissionTable)	fisx::TransmissionTable

getName() const (defined in fisx::TransmissionTable)	fisx::TransmissionTable

getTransmission(const double &energy) const	fisx::TransmissionTable

getTransmission(const std::vector< double > &energy) const	fisx::TransmissionTable

getTransmissionTable() const	fisx::TransmissionTable

setComment(const std::string &comment) (defined in fisx::TransmissionTable)	fisx::TransmissionTable

setName(const std::string &name) (defined in fisx::TransmissionTable)	fisx::TransmissionTable

setTransmissionTable(const std::map< double, double > &table, const std::string &name="", const std::string &comment="")	fisx::TransmissionTable

setTransmissionTable(const std::vector< double > &energy, const std::vector< double > &transmission, const std::string &name="", const std::string &comment="")	fisx::TransmissionTable

TransmissionTable()	fisx::TransmissionTable

TransmissionTable(const std::string &name, const std::string &comment="")	fisx::TransmissionTable

Generated on Wed Aug 3 2022 18:43:22 for fisx by

     1.8.12