/*
 * Copyright (c) 2006, 2007 QLogic Corporation. All rights reserved.
 * Copyright (c) 2005, 2006 PathScale, Inc. All rights reserved.
 *
 * This software is available to you under a choice of one of two
 * licenses.  You may choose to be licensed under the terms of the GNU
 * General Public License (GPL) Version 2, available from the file
 * COPYING in the main directory of this source tree, or the
 * OpenIB.org BSD license below:
 *
 *     Redistribution and use in source and binary forms, with or
 *     without modification, are permitted provided that the following
 *     conditions are met:
 *
 *      - Redistributions of source code must retain the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer.
 *
 *      - Redistributions in binary form must reproduce the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer in the documentation and/or other materials
 *        provided with the distribution.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <asm/io.h>

#include "ipath_verbs.h"
#include "ipath_kernel.h"

/**
 * ipath_alloc_lkey - allocate an lkey
 * @rkt: lkey table in which to allocate the lkey
 * @mr: memory region that this lkey protects
 *
 * Returns 1 if successful, otherwise returns 0.
 */

int ipath_alloc_lkey(struct ipath_lkey_table *rkt, struct ipath_mregion *mr)
{
	unsigned long flags;
	u32 r;
	u32 n;
	int ret;

	spin_lock_irqsave(&rkt->lock, flags);

	/* Find the next available LKEY */
	r = n = rkt->next;
	for (;;) {
		if (rkt->table[r] == NULL)
			break;
		r = (r + 1) & (rkt->max - 1);
		if (r == n) {
			spin_unlock_irqrestore(&rkt->lock, flags);
			ipath_dbg("LKEY table full\n");
			ret = 0;
			goto bail;
		}
	}
	rkt->next = (r + 1) & (rkt->max - 1);
	/*
	 * Make sure lkey is never zero which is reserved to indicate an
	 * unrestricted LKEY.
	 */
	rkt->gen++;
	mr->lkey = (r << (32 - ib_ipath_lkey_table_size)) |
		((((1 << (24 - ib_ipath_lkey_table_size)) - 1) & rkt->gen)
		 << 8);
	if (mr->lkey == 0) {
		mr->lkey |= 1 << 8;
		rkt->gen++;
	}
	rkt->table[r] = mr;
	spin_unlock_irqrestore(&rkt->lock, flags);

	ret = 1;

bail:
	return ret;
}

/**
 * ipath_free_lkey - free an lkey
 * @rkt: table from which to free the lkey
 * @lkey: lkey id to free
 */
void ipath_free_lkey(struct ipath_lkey_table *rkt, u32 lkey)
{
	unsigned long flags;
	u32 r;

	if (lkey == 0)
		return;
	r = lkey >> (32 - ib_ipath_lkey_table_size);
	spin_lock_irqsave(&rkt->lock, flags);
	rkt->table[r] = NULL;
	spin_unlock_irqrestore(&rkt->lock, flags);
}

/**
 * ipath_lkey_ok - check IB SGE for validity and initialize
 * @rkt: table containing lkey to check SGE against
 * @isge: outgoing internal SGE
 * @sge: SGE to check
 * @acc: access flags
 *
 * Return 1 if valid and successful, otherwise returns 0.
 *
 * Check the IB SGE for validity and initialize our internal version
 * of it.
 */
int ipath_lkey_ok(struct ipath_qp *qp, struct ipath_sge *isge,
		  struct ib_sge *sge, int acc)
{
	struct ipath_lkey_table *rkt = &to_idev(qp->ibqp.device)->lk_table;
	struct ipath_mregion *mr;
	unsigned n, m;
	size_t off;
	int ret;

	/*
	 * We use LKEY == zero for kernel virtual addresses
	 * (see ipath_get_dma_mr and ipath_dma.c).
	 */
	if (sge->lkey == 0) {
		/* always a kernel port, no locking needed */
		struct ipath_pd *pd = to_ipd(qp->ibqp.pd);

		if (pd->user) {
			ret = 0;
			goto bail;
		}
		isge->mr = NULL;
		isge->vaddr = (void *) sge->addr;
		isge->length = sge->length;
		isge->sge_length = sge->length;
		ret = 1;
		goto bail;
	}
	mr = rkt->table[(sge->lkey >> (32 - ib_ipath_lkey_table_size))];
	if (unlikely(mr == NULL || mr->lkey != sge->lkey ||
		     qp->ibqp.pd != mr->pd)) {
		ret = 0;
		goto bail;
	}

	off = sge->addr - mr->user_base;
	if (unlikely(sge->addr < mr->user_base ||
		     off + sge->length > mr->length ||
		     (mr->access_flags & acc) != acc)) {
		ret = 0;
		goto bail;
	}

	off += mr->offset;
	m = 0;
	n = 0;
	while (off >= mr->map[m]->segs[n].length) {
		off -= mr->map[m]->segs[n].length;
		n++;
		if (n >= IPATH_SEGSZ) {
			m++;
			n = 0;
		}
	}
	isge->mr = mr;
	isge->vaddr = mr->map[m]->segs[n].vaddr + off;
	isge->length = mr->map[m]->segs[n].length - off;
	isge->sge_length = sge->length;
	isge->m = m;
	isge->n = n;

	ret = 1;

bail:
	return ret;
}

/**
 * ipath_rkey_ok - check the IB virtual address, length, and RKEY
 * @dev: infiniband device
 * @ss: SGE state
 * @len: length of data
 * @vaddr: virtual address to place data
 * @rkey: rkey to check
 * @acc: access flags
 *
 * Return 1 if successful, otherwise 0.
 */
int ipath_rkey_ok(struct ipath_qp *qp, struct ipath_sge_state *ss,
		  u32 len, u64 vaddr, u32 rkey, int acc)
{
	struct ipath_ibdev *dev = to_idev(qp->ibqp.device);
	struct ipath_lkey_table *rkt = &dev->lk_table;
	struct ipath_sge *sge = &ss->sge;
	struct ipath_mregion *mr;
	unsigned n, m;
	size_t off;
	int ret;

	/*
	 * We use RKEY == zero for kernel virtual addresses
	 * (see ipath_get_dma_mr and ipath_dma.c).
	 */
	if (rkey == 0) {
		/* always a kernel port, no locking needed */
		struct ipath_pd *pd = to_ipd(qp->ibqp.pd);

		if (pd->user) {
			ret = 0;
			goto bail;
		}
		sge->mr = NULL;
		sge->vaddr = (void *) vaddr;
		sge->length = len;
		sge->sge_length = len;
		ss->sg_list = NULL;
		ss->num_sge = 1;
		ret = 1;
		goto bail;
	}

	mr = rkt->table[(rkey >> (32 - ib_ipath_lkey_table_size))];
	if (unlikely(mr == NULL || mr->lkey != rkey ||
		     qp->ibqp.pd != mr->pd)) {
		ret = 0;
		goto bail;
	}

	off = vaddr - mr->iova;
	if (unlikely(vaddr < mr->iova || off + len > mr->length ||
		     (mr->access_flags & acc) == 0)) {
		ret = 0;
		goto bail;
	}

	off += mr->offset;
	m = 0;
	n = 0;
	while (off >= mr->map[m]->segs[n].length) {
		off -= mr->map[m]->segs[n].length;
		n++;
		if (n >= IPATH_SEGSZ) {
			m++;
			n = 0;
		}
	}
	sge->mr = mr;
	sge->vaddr = mr->map[m]->segs[n].vaddr + off;
	sge->length = mr->map[m]->segs[n].length - off;
	sge->sge_length = len;
	sge->m = m;
	sge->n = n;
	ss->sg_list = NULL;
	ss->num_sge = 1;

	ret = 1;

bail:
	return ret;
}

{'repo_name': 'alibaba/LVS', 'stars': '1604', 'repo_language': 'C', 'file_name': 'usercopy.c', 'mime_type': 'text/x-c', 'hash': 8823620945856056649, 'source_dataset': 'data'}


<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/spacing_medium"
    android:padding="@dimen/spacing_medium">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/user_back_image"
            android:layout_width="match_parent"
            android:layout_height="180dp"
            android:scaleType="centerCrop"
            android:src="@drawable/recipe" />

        <!--<com.makeramen.roundedimageview.RoundedImageView xmlns:app="http://schemas.android.com/apk/res-auto"-->
        <!--android:id="@+id/user_image"-->
        <!--android:layout_width="48dp"-->
        <!--android:layout_height="48dp"-->
        <!--android:layout_alignParentStart="true"-->
        <!--android:layout_alignParentLeft="true"-->
        <!--android:layout_marginStart="@dimen/spacing_medium"-->
        <!--android:layout_marginLeft="@dimen/spacing_medium"-->
        <!--android:layout_marginTop="156dp"-->
        <!--android:scaleType="centerCrop"-->
        <!--app:riv_border_color="@android:color/white"-->
        <!--app:riv_border_width="2dp"-->
        <!--app:riv_oval="true" />-->

        <!--<TextView-->
        <!--android:id="@+id/restaurant_name_text"-->
        <!--android:layout_width="match_parent"-->
        <!--android:layout_height="wrap_content"-->
        <!--android:layout_below="@id/user_back_image"-->
        <!--android:layout_marginStart="@dimen/spacing_medium"-->
        <!--android:layout_marginLeft="@dimen/spacing_medium"-->
        <!--android:layout_marginTop="@dimen/spacing_small"-->
        <!--android:layout_toEndOf="@id/user_image"-->
        <!--android:layout_toRightOf="@+id/user_image"-->
        <!--android:ellipsize="end"-->
        <!--android:singleLine="true"-->
        <!--android:textSize="@dimen/text_size_xsmall" />-->

        <TextView
            android:id="@+id/title_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/user_back_image"
            android:maxLines="3"
            android:gravity="center_horizontal"
            android:maxLength="25"
            android:padding="@dimen/spacing_medium"
            android:textSize="@dimen/text_size_xxsmall"
            android:textStyle="bold" />
    </RelativeLayout>
</android.support.v7.widget.CardView>

{'repo_name': 'Sambor123/foodie-app', 'stars': '172', 'repo_language': 'Java', 'file_name': 'PrefUtils.java', 'mime_type': 'text/x-java', 'hash': -8578760589850626644, 'source_dataset': 'data'}


package com.nightonke.saver.adapter;

import android.content.Context;
import android.graphics.Color;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.balysv.materialripple.MaterialRippleLayout;
import com.nightonke.saver.R;
import com.nightonke.saver.fragment.RecordCheckDialogFragment;
import com.nightonke.saver.model.CoCoinRecord;
import com.nightonke.saver.model.RecordManager;
import com.nightonke.saver.model.SettingManager;
import com.nightonke.saver.util.CoCoinUtil;
import com.nispok.snackbar.Snackbar;
import com.nispok.snackbar.SnackbarManager;
import com.nispok.snackbar.enums.SnackbarType;
import com.nispok.snackbar.listeners.ActionClickListener;

import net.steamcrafted.materialiconlib.MaterialIconView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.Optional;
import lecho.lib.hellocharts.listener.ColumnChartOnValueSelectListener;
import lecho.lib.hellocharts.listener.PieChartOnValueSelectListener;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.PieChartData;
import lecho.lib.hellocharts.model.SelectedValue;
import lecho.lib.hellocharts.model.SliceValue;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.view.ColumnChartView;
import lecho.lib.hellocharts.view.PieChartView;

/**
 * Created by 伟平 on 2015/10/20.
 */

public class TodayViewRecyclerViewAdapter
        extends RecyclerView.Adapter<TodayViewRecyclerViewAdapter.viewHolder> {

    private OnItemClickListener onItemClickListener;

    private Context mContext;

    static final int TYPE_HEADER = 0;
    static final int TYPE_BODY = 1;

    static final int TODAY = 0;
    static final int YESTERDAY = 1;
    static final int THIS_WEEK = 2;
    static final int LAST_WEEK = 3;
    static final int THIS_MONTH = 4;
    static final int LAST_MONTH = 5;
    static final int THIS_YEAR = 6;
    static final int LAST_YEAR = 7;

    private int fragmentPosition;

    // the data of this fragment
    private ArrayList<CoCoinRecord> allData;

    // store the sum of expenses of each tag
    private Map<Integer, Double> TagExpanse;
    // store the records of each tag
    private Map<Integer, List<CoCoinRecord>> Expanse;
    // the original target value of the whole pie
    private float[] originalTargets;
    // whether the data of this fragment is empty
    private boolean IS_EMPTY;
    // the sum of the whole pie
    private double Sum;
    // the number of columns in the histogram
    private int columnNumber;
    // the axis date value of the histogram(hour, day of week and month, month)
    private int axis_date;
    // the month number
    private int month;

    // the selected position of one part of the pie
    private int pieSelectedPosition = 0;
    // the last selected position of one part of the pie
    private int lastPieSelectedPosition = -1;
    // the last selected position of one part of the histogram
    private int lastHistogramSelectedPosition = -1;

    // the date string on the footer and header
    private String dateString;
    // the date string shown in the dialog
    private String dateShownString;
    // the string shown in the dialog
    private String dialogTitle;

    // the selected tag in pie
    private int tagId = -1;
    // the selected column in histogram
    private int timeIndex;

    private MaterialDialog dialog;
    private View dialogView;

    public TodayViewRecyclerViewAdapter(int start, int end, Context context, int position) {

        mContext = context;
        fragmentPosition = position;
        Sum = 0;

        RecordManager recordManager = RecordManager.getInstance(mContext.getApplicationContext());

        allData = new ArrayList<>();
        if (start != -1)
            for (int i = start; i >= end; i--) allData.add(recordManager.RECORDS.get(i));

        IS_EMPTY = allData.isEmpty();

        setDateString();

        if (!IS_EMPTY) {
            if (fragmentPosition == TODAY || fragmentPosition == YESTERDAY) {
                columnNumber = 24;
                axis_date = Calendar.HOUR_OF_DAY;
            }
            if (fragmentPosition == THIS_WEEK || fragmentPosition == LAST_WEEK) {
                columnNumber = 7;
                axis_date = Calendar.DAY_OF_WEEK;
            }
            if (fragmentPosition == THIS_MONTH || fragmentPosition == LAST_MONTH) {
                columnNumber = allData.get(0).getCalendar().getActualMaximum(Calendar.DAY_OF_MONTH);
                axis_date = Calendar.DAY_OF_MONTH;
            }
            if (fragmentPosition == THIS_YEAR || fragmentPosition == LAST_YEAR) {
                columnNumber = 12;
                axis_date = Calendar.MONTH;
            }

            TagExpanse = new TreeMap<>();
            Expanse = new HashMap<>();
            originalTargets = new float[columnNumber];
            for (int i = 0; i < columnNumber; i++) originalTargets[i] = 0;

            int size = recordManager.TAGS.size();
            for (int j = 2; j < size; j++) {
                TagExpanse.put(recordManager.TAGS.get(j).getId(), Double.valueOf(0));
                Expanse.put(recordManager.TAGS.get(j).getId(), new ArrayList<CoCoinRecord>());
            }

            size = allData.size();
            for (int i = 0; i < size; i++) {
                CoCoinRecord coCoinRecord = allData.get(i);
                TagExpanse.put(coCoinRecord.getTag(),
                        TagExpanse.get(coCoinRecord.getTag()) + Double.valueOf(coCoinRecord.getMoney()));
                Expanse.get(coCoinRecord.getTag()).add(coCoinRecord);
                Sum += coCoinRecord.getMoney();
                if (axis_date == Calendar.DAY_OF_WEEK) {
                    if (CoCoinUtil.WEEK_START_WITH_SUNDAY)
                        originalTargets[coCoinRecord.getCalendar().get(axis_date) - 1]
                                += coCoinRecord.getMoney();
                    else originalTargets[(coCoinRecord.getCalendar().get(axis_date) + 5) % 7]
                                += coCoinRecord.getMoney();
                } else if (axis_date == Calendar.DAY_OF_MONTH) {
                    originalTargets[coCoinRecord.getCalendar().get(axis_date) - 1]
                            += coCoinRecord.getMoney();
                } else {
                    originalTargets[coCoinRecord.getCalendar().get(axis_date)]
                            += coCoinRecord.getMoney();
                }
            }

            TagExpanse = CoCoinUtil.SortTreeMapByValues(TagExpanse);
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (fragmentPosition == TODAY || fragmentPosition == YESTERDAY) {
            return position == 0 ? TYPE_HEADER : TYPE_BODY;
        }
        return TYPE_HEADER;
    }

    @Override
    public int getItemCount() {
        if (fragmentPosition == TODAY || fragmentPosition == YESTERDAY) {
            return allData.size() + 1;
        }
        return 1;
    }

    @Override
    public TodayViewRecyclerViewAdapter.viewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;

        switch (viewType) {
            case TYPE_HEADER: {
                view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_today_view_head, parent, false);
                return new viewHolder(view) {
                };
            }
            case TYPE_BODY: {
                view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_today_view_body, parent, false);
                return new viewHolder(view) {
                };
            }
        }

        return null;
    }

    @Override
    public void onBindViewHolder(final viewHolder holder, final int position) {

        switch (getItemViewType(position)) {
            case TYPE_HEADER:

                holder.date.setText(dateString);
                holder.dateBottom.setText(dateString);
                holder.expanseSum.setText(CoCoinUtil.GetInMoney((int) Sum));

                holder.date.setTypeface(CoCoinUtil.GetTypeface());
                holder.dateBottom.setTypeface(CoCoinUtil.GetTypeface());
                holder.expanseSum.setTypeface(CoCoinUtil.typefaceLatoLight);

                if (IS_EMPTY) {
                    holder.emptyTip.setVisibility(View.VISIBLE);
                    holder.emptyTip.setText(CoCoinUtil.GetTodayViewEmptyTip(fragmentPosition));
                    holder.emptyTip.setTypeface(CoCoinUtil.GetTypeface());

                    holder.reset.setVisibility(View.GONE);

                    holder.pie.setVisibility(View.GONE);
                    holder.iconLeft.setVisibility(View.GONE);
                    holder.iconRight.setVisibility(View.GONE);

                    holder.histogram.setVisibility(View.GONE);
                    holder.histogram_icon_left.setVisibility(View.GONE);
                    holder.histogram_icon_right.setVisibility(View.GONE);
                    holder.all.setVisibility(View.GONE);
                    holder.dateBottom.setVisibility(View.GONE);
                } else {
                    holder.emptyTip.setVisibility(View.GONE);

                    final ArrayList<SliceValue> sliceValues = new ArrayList<>();

                    for (Map.Entry<Integer, Double> entry : TagExpanse.entrySet()) {
                        if (entry.getValue() >= 1) {
                            SliceValue sliceValue = new SliceValue(
                                    (float)(double)entry.getValue(),
                                    mContext.getApplicationContext().getResources().
                                            getColor(CoCoinUtil.GetTagColorResource(entry.getKey())));
                            sliceValue.setLabel(String.valueOf(entry.getKey()));
                            sliceValues.add(sliceValue);
                        }
                    }

                    final PieChartData pieChartData = new PieChartData(sliceValues);

                    pieChartData.setHasLabels(false);
                    pieChartData.setHasLabelsOnlyForSelected(false);
                    pieChartData.setHasLabelsOutside(false);
                    pieChartData.setHasCenterCircle(SettingManager.getInstance().getIsHollow());

                    holder.pie.setPieChartData(pieChartData);
                    holder.pie.setChartRotationEnabled(false);

// two control button of pie////////////////////////////////////////////////////////////////////////
                    holder.iconRight.setVisibility(View.VISIBLE);
                    holder.iconRight.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (lastPieSelectedPosition != -1) {
                                pieSelectedPosition = lastPieSelectedPosition;
                            }
                            pieSelectedPosition
                                    = (pieSelectedPosition - 1 + sliceValues.size())
                                    % sliceValues.size();
                            SelectedValue selectedValue =
                                    new SelectedValue(
                                            pieSelectedPosition,
                                            0,
                                            SelectedValue.SelectedValueType.NONE);
                            holder.pie.selectValue(selectedValue);
                        }
                    });
                    holder.iconLeft.setVisibility(View.VISIBLE);
                    holder.iconLeft.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (lastPieSelectedPosition != -1) {
                                pieSelectedPosition = lastPieSelectedPosition;
                            }
                            pieSelectedPosition
                                    = (pieSelectedPosition + 1)
                                    % sliceValues.size();
                            SelectedValue selectedValue =
                                    new SelectedValue(
                                            pieSelectedPosition,
                                            0,
                                            SelectedValue.SelectedValueType.NONE);
                            holder.pie.selectValue(selectedValue);
                        }
                    });

                    final List<Column> columns = new ArrayList<>();
                    final ColumnChartData columnChartData = new ColumnChartData(columns);

                    if (!(fragmentPosition == TODAY || fragmentPosition == YESTERDAY)) {

                        for (int i = 0; i < columnNumber; i++) {
                            if (lastHistogramSelectedPosition == -1 && originalTargets[i] == 0) {
                                lastHistogramSelectedPosition = i;
                            }
                            SubcolumnValue value = new SubcolumnValue(
                                    originalTargets[i], CoCoinUtil.GetRandomColor());
                            List<SubcolumnValue> subcolumnValues = new ArrayList<>();
                            subcolumnValues.add(value);
                            Column column = new Column(subcolumnValues);
                            column.setHasLabels(false);
                            column.setHasLabelsOnlyForSelected(false);
                            columns.add(column);
                        }

                        Axis axisX = new Axis();
                        List<AxisValue> axisValueList = new ArrayList<>();

                        for (int i = 0; i < columnNumber; i++) {
                            axisValueList.add(
                                    new AxisValue(i).setLabel(CoCoinUtil.GetAxisDateName(axis_date, i)));
                        }

                        axisX.setValues(axisValueList);
                        Axis axisY = new Axis().setHasLines(true);

                        columnChartData.setAxisXBottom(axisX);
                        columnChartData.setAxisYLeft(axisY);
                        columnChartData.setStacked(true);

                        holder.histogram.setColumnChartData(columnChartData);
                        holder.histogram.setZoomEnabled(false);

                        // two control button of histogram//////////////////////////////////////////////////////////////////
                        holder.histogram_icon_left.setVisibility(View.VISIBLE);
                        holder.histogram_icon_left.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                do {
                                    lastHistogramSelectedPosition
                                            = (lastHistogramSelectedPosition - 1 + columnNumber)
                                            % columnNumber;
                                } while (columnChartData.getColumns()
                                        .get(lastHistogramSelectedPosition)
                                        .getValues().get(0).getValue() == 0);
                                SelectedValue selectedValue =
                                        new SelectedValue(
                                                lastHistogramSelectedPosition,
                                                0,
                                                SelectedValue.SelectedValueType.NONE);
                                holder.histogram.selectValue(selectedValue);
                            }
                        });
                        holder.histogram_icon_right.setVisibility(View.VISIBLE);
                        holder.histogram_icon_right.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                do {
                                    lastHistogramSelectedPosition
                                            = (lastHistogramSelectedPosition + 1)
                                            % columnNumber;
                                } while (columnChartData.getColumns()
                                        .get(lastHistogramSelectedPosition)
                                        .getValues().get(0).getValue() == 0);
                                SelectedValue selectedValue =
                                        new SelectedValue(
                                                lastHistogramSelectedPosition,
                                                0,
                                                SelectedValue.SelectedValueType.NONE);
                                holder.histogram.selectValue(selectedValue);
                            }
                        });
                    }

                    if (fragmentPosition == TODAY || fragmentPosition == YESTERDAY) {
                        holder.histogram_icon_left.setVisibility(View.INVISIBLE);
                        holder.histogram_icon_right.setVisibility(View.INVISIBLE);
                        holder.histogram.setVisibility(View.GONE);
                        holder.dateBottom.setVisibility(View.GONE);
                        holder.reset.setVisibility(View.GONE);
                    }

// set value touch listener of pie//////////////////////////////////////////////////////////////////
                    holder.pie.setOnValueTouchListener(new PieChartOnValueSelectListener() {
                        @Override
                        public void onValueSelected(int p, SliceValue sliceValue) {
                            // snack bar
                            RecordManager recordManager
                                    = RecordManager.getInstance(mContext.getApplicationContext());
                            String text;
                            tagId = Integer.valueOf(String.valueOf(sliceValue.getLabelAsChars()));
                            double percent = sliceValue.getValue() / Sum * 100;
                            if ("zh".equals(CoCoinUtil.GetLanguage())) {
                                text = CoCoinUtil.GetSpendString((int) sliceValue.getValue()) +
                                        CoCoinUtil.GetPercentString(percent) + "\n" +
                                        "于" + CoCoinUtil.GetTagName(tagId);
                            } else {
                                text = "Spend " + (int)sliceValue.getValue()
                                        + " (takes " + String.format("%.2f", percent) + "%)\n"
                                        + "in " + CoCoinUtil.GetTagName(tagId);
                            }
                            if ("zh".equals(CoCoinUtil.GetLanguage())) {
                                dialogTitle = dateShownString +
                                        CoCoinUtil.GetSpendString((int) sliceValue.getValue()) + "\n" +
                                        "于" + CoCoinUtil.GetTagName(tagId);
                            } else {
                                dialogTitle = "Spend " + (int)sliceValue.getValue()
                                        + dateShownString + "\n" +
                                        "in " + CoCoinUtil.GetTagName(tagId);
                            }
                            Snackbar snackbar =
                                    Snackbar
                                            .with(mContext)
                                            .type(SnackbarType.MULTI_LINE)
                                            .duration(Snackbar.SnackbarDuration.LENGTH_SHORT)
                                            .position(Snackbar.SnackbarPosition.BOTTOM)
                                            .margin(15, 15)
                                            .backgroundDrawable(CoCoinUtil.GetSnackBarBackground(
                                                    fragmentPosition - 2))
                                            .text(text)
                                            .textTypeface(CoCoinUtil.GetTypeface())
                                            .textColor(Color.WHITE)
                                            .actionLabelTypeface(CoCoinUtil.GetTypeface())
                                            .actionLabel(mContext.getResources()
                                                    .getString(R.string.check))
                                            .actionColor(Color.WHITE)
                                            .actionListener(new mActionClickListenerForPie());
                            SnackbarManager.show(snackbar);

                            if (p == lastPieSelectedPosition) {
                                return;
                            } else {
                                lastPieSelectedPosition = p;
                            }

                            if (!(fragmentPosition == TODAY || fragmentPosition == YESTERDAY)) {

// histogram data///////////////////////////////////////////////////////////////////////////////////
                                float[] targets = new float[columnNumber];
                                for (int i = 0; i < columnNumber; i++) targets[i] = 0;

                                for (int i = Expanse.get(tagId).size() - 1; i >= 0; i--) {
                                    CoCoinRecord coCoinRecord = Expanse.get(tagId).get(i);
                                    if (axis_date == Calendar.DAY_OF_WEEK) {
                                        if (CoCoinUtil.WEEK_START_WITH_SUNDAY) {
                                            targets[coCoinRecord.getCalendar().get(axis_date) - 1]
                                                    += coCoinRecord.getMoney();
                                        } else {
                                            targets[(coCoinRecord.getCalendar().get(axis_date) + 5) % 7]
                                                    += coCoinRecord.getMoney();
                                        }
                                    } else if (axis_date == Calendar.DAY_OF_MONTH) {
                                        targets[coCoinRecord.getCalendar().get(axis_date) - 1]
                                                += coCoinRecord.getMoney();
                                    } else {
                                        targets[coCoinRecord.getCalendar().get(axis_date)]
                                                += coCoinRecord.getMoney();
                                    }
                                }

                                lastHistogramSelectedPosition = -1;
                                for (int i = 0; i < columnNumber; i++) {
                                    if (lastHistogramSelectedPosition == -1 && targets[i] != 0) {
                                        lastHistogramSelectedPosition = i;
                                    }
                                    columnChartData.getColumns().
                                            get(i).getValues().get(0).setTarget(targets[i]);
                                }
                                holder.histogram.startDataAnimation();
                            }
                        }

                        @Override
                        public void onValueDeselected() {

                        }
                    });

                    if (!(fragmentPosition == TODAY || fragmentPosition == YESTERDAY)) {

// set value touch listener of histogram////////////////////////////////////////////////////////////
                        holder.histogram.setOnValueTouchListener(
                                new ColumnChartOnValueSelectListener() {
                            @Override
                            public void onValueSelected(int columnIndex,
                                                        int subcolumnIndex, SubcolumnValue value) {
                                lastHistogramSelectedPosition = columnIndex;
                                timeIndex = columnIndex;
                                // snack bar
                                RecordManager recordManager
                                        = RecordManager.getInstance(mContext.getApplicationContext());

                                String text = CoCoinUtil.GetSpendString((int) value.getValue());
                                if (tagId != -1)
                                    // belongs a tag
                                    if ("zh".equals(CoCoinUtil.GetLanguage()))
                                        text = getSnackBarDateString() + text + "\n" +
                                                "于" + CoCoinUtil.GetTagName(tagId);
                                    else
                                        text += getSnackBarDateString() + "\n"
                                                + "in " + CoCoinUtil.GetTagName(tagId);
                                else
                                    // don't belong to any tag
                                    if ("zh".equals(CoCoinUtil.GetLanguage()))
                                        text = getSnackBarDateString() + "\n" + text;
                                    else
                                        text += "\n" + getSnackBarDateString();

// setting the snack bar and dialog title of histogram//////////////////////////////////////////////
                                dialogTitle = text;
                                Snackbar snackbar =
                                        Snackbar
                                                .with(mContext)
                                                .type(SnackbarType.MULTI_LINE)
                                                .duration(Snackbar.SnackbarDuration.LENGTH_SHORT)
                                                .position(Snackbar.SnackbarPosition.BOTTOM)
                                                .margin(15, 15)
                                                .backgroundDrawable(CoCoinUtil.GetSnackBarBackground(
                                                        fragmentPosition - 2))
                                                .text(text)
                                                .textTypeface(CoCoinUtil.GetTypeface())
                                                .textColor(Color.WHITE)
                                                .actionLabelTypeface(CoCoinUtil.GetTypeface())
                                                .actionLabel(mContext.getResources()
                                                        .getString(R.string.check))
                                                .actionColor(Color.WHITE)
                                                .actionListener(new mActionClickListenerForHistogram());
                                SnackbarManager.show(snackbar);
                            }

                            @Override
                            public void onValueDeselected() {

                            }
                        });
                    }

// set the listener of the reset button/////////////////////////////////////////////////////////////
                    if (!(fragmentPosition == TODAY || fragmentPosition == YESTERDAY)) {
                        holder.reset.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                tagId = -1;
                                lastHistogramSelectedPosition = -1;

                                for (int i = 0; i < columnNumber; i++) {
                                    if (lastHistogramSelectedPosition == -1
                                            && originalTargets[i] != 0) {
                                        lastHistogramSelectedPosition = i;
                                    }
                                    columnChartData.getColumns().
                                            get(i).getValues().get(0).setTarget(originalTargets[i]);
                                }

                                holder.histogram.startDataAnimation();
                            }
                        });
                    }

// set the listener of the show all button//////////////////////////////////////////////////////////
                    holder.all.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ((FragmentActivity)mContext).getSupportFragmentManager()
                                    .beginTransaction()
                                    .add(new RecordCheckDialogFragment(
                                            mContext, allData, getAllDataDialogTitle()), "MyDialog")
                                    .commit();
                        }
                    });

                }

                break;

            case TYPE_BODY:

                holder.tagImage.setImageResource(
                        CoCoinUtil.GetTagIcon(allData.get(position - 1).getTag()));
                holder.money.setText((int) allData.get(position - 1).getMoney() + "");
                holder.money.setTypeface(CoCoinUtil.typefaceLatoLight);
                holder.cell_date.setText(allData.get(position - 1).getCalendarString());
                holder.cell_date.setTypeface(CoCoinUtil.typefaceLatoLight);
                holder.remark.setText(allData.get(position - 1).getRemark());
                holder.remark.setTypeface(CoCoinUtil.typefaceLatoLight);
                holder.index.setText(position + "");
                holder.index.setTypeface(CoCoinUtil.typefaceLatoLight);
                holder.layout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String subTitle;
                        double spend = allData.get(position - 1).getMoney();
                        int tagId = allData.get(position - 1).getTag();
                        if ("zh".equals(CoCoinUtil.GetLanguage())) {
                            subTitle = CoCoinUtil.GetSpendString((int)spend) +
                                    "于" + CoCoinUtil.GetTagName(tagId);
                        } else {
                            subTitle = "Spend " + (int)spend +
                                    "in " + CoCoinUtil.GetTagName(tagId);
                        }
                        dialog = new MaterialDialog.Builder(mContext)
                                .icon(CoCoinUtil.GetTagIconDrawable(allData.get(position - 1).getTag()))
                                .limitIconToDefaultSize()
                                .title(subTitle)
                                .customView(R.layout.dialog_a_record, true)
                                .positiveText(R.string.get)
                                .show();
                        dialogView = dialog.getCustomView();
                        TextView remark = (TextView)dialogView.findViewById(R.id.remark);
                        TextView date = (TextView)dialogView.findViewById(R.id.date);
                        remark.setText(allData.get(position - 1).getRemark());
                        date.setText(allData.get(position - 1).getCalendarString());
                    }
                });

                break;
        }
    }

// view holder class////////////////////////////////////////////////////////////////////////////////
    public static class viewHolder extends RecyclerView.ViewHolder {
        @Optional
        @InjectView(R.id.date)
        TextView date;
        @Optional
        @InjectView(R.id.date_bottom)
        TextView dateBottom;
        @Optional
        @InjectView(R.id.expanse)
        TextView expanseSum;
        @Optional
        @InjectView(R.id.empty_tip)
        TextView emptyTip;
        @Optional
        @InjectView(R.id.chart_pie)
        PieChartView pie;
        @Optional
        @InjectView(R.id.histogram)
        ColumnChartView histogram;
        @Optional
        @InjectView(R.id.icon_left)
        MaterialIconView iconLeft;
        @Optional
        @InjectView(R.id.icon_right)
        MaterialIconView iconRight;
        @Optional
        @InjectView(R.id.histogram_icon_left)
        MaterialIconView histogram_icon_left;
        @Optional
        @InjectView(R.id.histogram_icon_right)
        MaterialIconView histogram_icon_right;
        @Optional
        @InjectView(R.id.icon_reset)
        MaterialIconView reset;
        @Optional
        @InjectView(R.id.all)
        MaterialIconView all;
        @Optional
        @InjectView(R.id.tag_image)
        ImageView tagImage;
        @Optional
        @InjectView(R.id.money)
        TextView money;
        @Optional
        @InjectView(R.id.cell_date)
        TextView cell_date;
        @Optional
        @InjectView(R.id.remark)
        TextView remark;
        @Optional
        @InjectView(R.id.index)
        TextView index;
        @Optional
        @InjectView(R.id.material_ripple_layout)
        MaterialRippleLayout layout;

        viewHolder(View view) {
            super(view);
            ButterKnife.inject(this, view);
        }
    }

    public interface OnItemClickListener {
        void onItemClick(View view , int position);
    }

// set the listener of the check button on the snack bar of pie/////////////////////////////////////
    private class mActionClickListenerForPie implements ActionClickListener {
        @Override
        public void onActionClicked(Snackbar snackbar) {
            List<CoCoinRecord> shownCoCoinRecords = Expanse.get(tagId);
            ((FragmentActivity)mContext).getSupportFragmentManager()
                    .beginTransaction()
                    .add(new RecordCheckDialogFragment(
                            mContext, shownCoCoinRecords, dialogTitle), "MyDialog")
                    .commit();
        }
    }

// set the listener of the check button on the snack bar of histogram///////////////////////////////
    private class mActionClickListenerForHistogram implements ActionClickListener {
        @Override
        public void onActionClicked(Snackbar snackbar) {
            ArrayList<CoCoinRecord> shownCoCoinRecords = new ArrayList<>();
            int index = timeIndex;
            if (axis_date == Calendar.DAY_OF_WEEK) {
                if (CoCoinUtil.WEEK_START_WITH_SUNDAY) index++;
                else
                    if (index == 6) index = 1;
                    else index += 2;
            }
            if (fragmentPosition == THIS_MONTH || fragmentPosition == LAST_MONTH) index++;
            if (tagId != -1) {
                for (int i = 0; i < Expanse.get(tagId).size(); i++)
                    if (Expanse.get(tagId).get(i).getCalendar().get(axis_date) == index)
                        shownCoCoinRecords.add(Expanse.get(tagId).get(i));
            } else {
                for (int i = 0; i < allData.size(); i++)
                    if (allData.get(i).getCalendar().get(axis_date) == index)
                        shownCoCoinRecords.add(allData.get(i));
            }
            ((FragmentActivity)mContext).getSupportFragmentManager()
                    .beginTransaction()
                    .add(new RecordCheckDialogFragment(
                            mContext, shownCoCoinRecords, dialogTitle), "MyDialog")
                    .commit();
        }
    }

// set the dateString shown in snack bar in this fragment///////////////////////////////////////////
    private String getSnackBarDateString() {
        switch (fragmentPosition) {
            case TODAY:
                if ("zh".equals(CoCoinUtil.GetLanguage()))
                    // 在今天9点
                    return mContext.getResources().getString(R.string.at) +
                            mContext.getResources().getString(R.string.today_date_string) +
                            timeIndex +
                            mContext.getResources().getString(R.string.o_clock);
                else
                    // at 9 o'clock today
                    return mContext.getResources().getString(R.string.at) +
                            timeIndex + " " +
                            mContext.getResources().getString(R.string.o_clock) + " " +
                            mContext.getResources().getString(R.string.today_date_string);
            case YESTERDAY:
                if ("zh".equals(CoCoinUtil.GetLanguage()))
                    // 在昨天9点
                    return mContext.getResources().getString(R.string.at) +
                            mContext.getResources().getString(R.string.yesterday_date_string) +
                            timeIndex +
                            mContext.getResources().getString(R.string.o_clock);
                else
                    // at 9 o'clock yesterday
                    return mContext.getResources().getString(R.string.at) +
                            timeIndex + " " +
                            mContext.getResources().getString(R.string.o_clock) + " " +
                            mContext.getResources().getString(R.string.yesterday_date_string);
            case THIS_WEEK:
                // 在周一
                // on Monday
                return mContext.getResources().getString(R.string.on)
                        + CoCoinUtil.GetWeekDay(timeIndex);
            case LAST_WEEK:
                // 在上周一
                // on last Monday
                return mContext.getResources().getString(R.string.on)
                        + mContext.getResources().getString(R.string.last)
                        + CoCoinUtil.GetWeekDay(timeIndex);
            case THIS_MONTH:
                // 在1月1日
                // on Jan. 1
                return mContext.getResources().getString(R.string.on) +
                        CoCoinUtil.GetMonthShort(month) + CoCoinUtil.GetWhetherBlank() +
                        (timeIndex + 1) + CoCoinUtil.GetWhetherFuck();
            case LAST_MONTH:
                // 在1月1日
                // on Jan. 1
                return mContext.getResources().getString(R.string.on) +
                        CoCoinUtil.GetMonthShort(month) + CoCoinUtil.GetWhetherBlank() +
                        (timeIndex + 1) + CoCoinUtil.GetWhetherFuck();
            case THIS_YEAR:
                if ("zh".equals(CoCoinUtil.GetLanguage()))
                    // 在今年1月
                    return mContext.getResources().getString(R.string.in) +
                            mContext.getResources().getString(R.string.this_year_date_string) +
                            CoCoinUtil.GetMonthShort(timeIndex + 1);
                else
                    // in Jan. 1
                    return mContext.getResources().getString(R.string.in) +
                            CoCoinUtil.GetMonthShort(timeIndex + 1) + " " +
                            mContext.getResources().getString(R.string.this_year_date_string);
            case LAST_YEAR:
                if ("zh".equals(CoCoinUtil.GetLanguage()))
                    // 在去年1月
                    return mContext.getResources().getString(R.string.in) +
                            mContext.getResources().getString(R.string.last_year_date_string) +
                            CoCoinUtil.GetMonthShort(timeIndex + 1);
                else
                    // in Jan. 1
                    return mContext.getResources().getString(R.string.in) +
                            CoCoinUtil.GetMonthShort(timeIndex + 1) + " " +
                            mContext.getResources().getString(R.string.last_year_date_string);
            default:
                return "";
        }
    }

// set the dateString of this fragment//////////////////////////////////////////////////////////////
    private void setDateString() {
        String basicTodayDateString;
        String basicYesterdayDateString;
        Calendar today = Calendar.getInstance();
        Calendar yesterday = CoCoinUtil.GetYesterdayLeftRange(today);
        basicTodayDateString = "--:-- ";
        basicTodayDateString += CoCoinUtil.GetMonthShort(today.get(Calendar.MONTH) + 1)
                + " " + today.get(Calendar.DAY_OF_MONTH) + " " +
                today.get(Calendar.YEAR);
        basicYesterdayDateString = "--:-- ";
        basicYesterdayDateString += CoCoinUtil.GetMonthShort(today.get(Calendar.MONTH) + 1)
                + " " + yesterday.get(Calendar.DAY_OF_MONTH) + " " +
                yesterday.get(Calendar.YEAR);
        switch (fragmentPosition) {
            case TODAY:
                dateString = basicTodayDateString.substring(6, basicTodayDateString.length());
                dateShownString = mContext.getResources().getString(R.string.today_date_string);
                month = today.get(Calendar.MONTH);
                break;
            case YESTERDAY:
                dateString
                        = basicYesterdayDateString.substring(6, basicYesterdayDateString.length());
                dateShownString = mContext.getResources().getString(R.string.yesterday_date_string);
                month = yesterday.get(Calendar.MONTH);
                break;
            case THIS_WEEK:
                Calendar leftWeekRange = CoCoinUtil.GetThisWeekLeftRange(today);
                Calendar rightWeekRange = CoCoinUtil.GetThisWeekRightShownRange(today);
                dateString = CoCoinUtil.GetMonthShort(leftWeekRange.get(Calendar.MONTH) + 1)
                        + " " + leftWeekRange.get(Calendar.DAY_OF_MONTH) + " " +
                        leftWeekRange.get(Calendar.YEAR) + " - " +
                        CoCoinUtil.GetMonthShort(rightWeekRange.get(Calendar.MONTH) + 1)
                        + " " + rightWeekRange.get(Calendar.DAY_OF_MONTH) + " " +
                        rightWeekRange.get(Calendar.YEAR);
                dateShownString = mContext.getResources().getString(R.string.this_week_date_string);
                month = -1;
                break;
            case LAST_WEEK:
                Calendar leftLastWeekRange = CoCoinUtil.GetLastWeekLeftRange(today);
                Calendar rightLastWeekRange = CoCoinUtil.GetLastWeekRightShownRange(today);
                dateString
                        = CoCoinUtil.GetMonthShort(leftLastWeekRange.get(Calendar.MONTH) + 1)
                        + " " + leftLastWeekRange.get(Calendar.DAY_OF_MONTH) + " " +
                        leftLastWeekRange.get(Calendar.YEAR) + " - " +
                        CoCoinUtil.GetMonthShort(rightLastWeekRange.get(Calendar.MONTH) + 1)
                        + " " + rightLastWeekRange.get(Calendar.DAY_OF_MONTH) + " " +
                        rightLastWeekRange.get(Calendar.YEAR);
                dateShownString = mContext.getResources().getString(R.string.last_week_date_string);
                month = -1;
                break;
            case THIS_MONTH:
                dateString = CoCoinUtil.GetMonthShort(today.get(Calendar.MONTH) + 1)
                        + " " + today.get(Calendar.YEAR);
                dateShownString
                        = mContext.getResources().getString(R.string.this_month_date_string);
                month = today.get(Calendar.MONTH);
                break;
            case LAST_MONTH:
                Calendar lastMonthCalendar = CoCoinUtil.GetLastMonthLeftRange(today);
                dateString
                        = CoCoinUtil.GetMonthShort(lastMonthCalendar.get(Calendar.MONTH) + 1)
                        + " " + lastMonthCalendar.get(Calendar.YEAR);
                dateShownString
                        = mContext.getResources().getString(R.string.last_month_date_string);
                month = lastMonthCalendar.get(Calendar.MONTH);
                break;
            case THIS_YEAR:
                dateString = today.get(Calendar.YEAR) + "";
                dateShownString = mContext.getResources().getString(R.string.this_year_date_string);
                month = -1;
                break;
            case LAST_YEAR:
                Calendar lastYearCalendar = CoCoinUtil.GetLastYearLeftRange(today);
                dateString = lastYearCalendar.get(Calendar.YEAR) + "";
                dateShownString = mContext.getResources().getString(R.string.last_year_date_string);
                month = -1;
                break;
        }
    }

    private String getAllDataDialogTitle() {
        String prefix;
        String postfix;
        if ("zh".equals(CoCoinUtil.GetLanguage())) {
            prefix = mContext.getResources().getString(R.string.on);
            postfix = CoCoinUtil.GetSpendString((int)Sum);
        } else {
            prefix = CoCoinUtil.GetSpendString((int)Sum);
            postfix = "";
        }
        switch (fragmentPosition) {
            case TODAY:
                return prefix + mContext.getResources().
                        getString(R.string.today_date_string) + postfix;
            case YESTERDAY:
                return prefix + mContext.getResources().
                        getString(R.string.yesterday_date_string) + postfix;
            case THIS_WEEK:
                return prefix + mContext.getResources().
                        getString(R.string.this_week_date_string) + postfix;
            case LAST_WEEK:
                return prefix + mContext.getResources().
                        getString(R.string.last_week_date_string) + postfix;
            case THIS_MONTH:
                return prefix + mContext.getResources().
                        getString(R.string.this_month_date_string) + postfix;
            case LAST_MONTH:
                return prefix + mContext.getResources().
                        getString(R.string.last_month_date_string) + postfix;
            case THIS_YEAR:
                return prefix + mContext.getResources().
                        getString(R.string.this_year_date_string) + postfix;
            case LAST_YEAR:
                return prefix + mContext.getResources().
                        getString(R.string.last_year_date_string) + postfix;
            default:
                return "";
        }
    }

}

{'repo_name': 'Nightonke/CoCoin', 'stars': '2653', 'repo_language': 'Java', 'file_name': 'manifestMerger6273964336951648354.xml', 'mime_type': 'text/xml', 'hash': 8383161191832114283, 'source_dataset': 'data'}


/*
 *  ready.h - Information from the 'ready.dat' file.
 *
 *  Copyright (C) 2000-2013  The Exult Team
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#ifndef INCL_READY
#define INCL_READY  1

/*
 *  Internal Exult types describing how a shape may be worn.
 */
enum Ready_type_Exult {
    head = 0x00,
    backpack = 0x01,
    belt = 0x02,
    lhand = 0x03,
    lfinger = 0x04,
    legs = 0x05,
    feet = 0x06,
    rfinger = 0x07,             // Only for usecode or for alternate slot.
    rhand = 0x08,
    torso = 0x09,
    amulet = 0x0a,
    quiver = 0x0b,
    back_2h = 0x0c,             // Only for usecode or for alternate slot
    back_shield = 0x0d,         // Only for usecode or for alternate slot
    earrings = 0x0e,
    cloak = 0x0f,
    gloves = 0x10,
    ucont = 0x11,
    // The following four entries are not actual spots, but mark an object as
    // filling multiple spots of the given type.
    both_hands = 0x12,          // Uses both hands.
    lrgloves = 0x13,            // Uses gloves spot, fills ring.
    neck = 0x14,                // Uses amulet spot, fills cloak.
    // Used for alternate slot only:
    scabbard = 0x15,            // Uses belt spot, fills back_2h, back_shield.
    // Marks as firing triple crossbow bolts:
    triple_bolts = 0x16,
    // Used for paperdolling only:
    cloak_clasp = 102,
    invalid_spot = 0xff
};

// Black Gate Ready types
enum Ready_type_BG {
    backpack_bg = 0x00,
    lhand_bg = 0x01,
    rhand_bg = 0x02,            // Only for usecode or for alternate slot
    belt_bg = 0x03,             // Only for usecode or for alternate slot
    neck_bg = 0x04,
    torso_bg = 0x05,
    lfinger_bg = 0x06,
    rfinger_bg = 0x07,          // Only for usecode or for alternate slot
    quiver_bg = 0x08,
    head_bg = 0x09,
    legs_bg = 0x0a,
    feet_bg = 0x0b,
    ucont_bg = 0x0c,            // Porting from SI
    cloak_bg = 0x0d,            // Porting from SI
    gloves_bg = 0x0e,           // Porting from SI
    triple_bolts_bg = 0x0f,
    earrings_bg = 0x10,         // Porting from SI
    back_shield_bg = 0x11,      // Porting from SI
    tongs_bg = 0x12,            // Silently converted to lhand_bg
    back_2h_bg = 0x13,          // Porting from SI
    both_hands_bg = 0x14,
    lrgloves_bg = 0x15,
    amulet_bg = 0x16,
    scabbard_bg = 0x17          // Only for alternate slot
};

// Serpent Isle Ready types
enum Ready_type_SI {
    rhand_si = 0x00,
    lhand_si = 0x01,
    cloak_si = 0x02,
    amulet_si = 0x03,
    head_si = 0x04,
    gloves_si = 0x05,
    ucont_si = 0x06,
    rfinger_si = 0x07,          // Only for usecode or for alternate slot
    lfinger_si = 0x08,
    earrings_si = 0x09,
    quiver_si = 0x0a,
    belt_si = 0x0b,
    torso_si = 0x0c,
    feet_si = 0x0d,
    legs_si = 0x0e,
    backpack_si = 0x0f,
    back_shield_si = 0x10,      // Only for usecode or for alternate slot
    back_2h_si = 0x11,          // Only for usecode or for alternate slot
    triple_bolts_si = 0x12,     // Porting from BG
    both_hands_si = 0x14,
    lrgloves_si = 0x15,         // Porting from BG
    neck_si = 0x16,
    scabbard_si = 0x17          // Only for alternate slot
};

/*
 *  Convert to BG ready spot # from ours (or invalid_spot if not found).
 */

inline int Ready_spot_to_BG(int spot) {
	switch (spot) {
	case head:
		return head_bg;
	case backpack:
		return backpack_bg;
	case belt:
		return belt_bg;
	case lhand:
		return lhand_bg;
	case lfinger:
		return lfinger_bg;
	case legs:
		return legs_bg;
	case feet:
		return feet_bg;
	case rfinger:
		return rfinger_bg;
	case rhand:
		return rhand_bg;
	case torso:
		return torso_bg;
	case amulet:
		return amulet_bg;
	case quiver:
		return quiver_bg;
	case back_2h:
		return back_2h_bg;
	case back_shield:
		return back_shield_bg;
	case earrings:
		return earrings_bg;
	case cloak:
		return cloak_bg;
	case gloves:
		return gloves_bg;
	case ucont:
		return ucont_bg;
	case both_hands:
		return both_hands_bg;
	case lrgloves:
		return lrgloves_bg;
	case triple_bolts:
		return triple_bolts_bg;
	case scabbard:
		return scabbard_bg;
	case neck:
		return neck_bg;
	default:
		return invalid_spot;
	}
}

/*
 *  Convert to SI ready spot # from ours (or invalid_spot if not found).
 */

inline int Ready_spot_to_SI(int spot) {
	switch (spot) {
	case head:
		return head_si;
	case backpack:
		return backpack_si;
	case belt:
		return belt_si;
	case lhand:
		return lhand_si;
	case lfinger:
		return lfinger_si;
	case legs:
		return legs_si;
	case feet:
		return feet_si;
	case rfinger:
		return rfinger_si;
	case rhand:
		return rhand_si;
	case torso:
		return torso_si;
	case amulet:
		return amulet_si;
	case quiver:
		return quiver_si;
	case back_2h:
		return back_2h_si;
	case back_shield:
		return back_shield_si;
	case earrings:
		return earrings_si;
	case cloak:
		return cloak_si;
	case gloves:
		return gloves_si;
	case ucont:
		return ucont_si;
	case both_hands:
		return both_hands_si;
	case lrgloves:
		return lrgloves_si;
	case triple_bolts:
		return triple_bolts_si;
	case scabbard:
		return scabbard_si;
	case neck:
		return neck_si;
	default:
		return invalid_spot;
	}
}

/*
 *  Convert from BG ready spot # to ours (or invalid_spot if not found).
 */

inline int Ready_spot_from_BG(int spot) {
	switch (spot) {
	case head_bg:
		return head;
	case backpack_bg:
		return backpack;
	case belt_bg:
		return belt;
	case lhand_bg:
		return lhand;
	case lfinger_bg:
		return lfinger;
	case legs_bg:
		return legs;
	case feet_bg:
		return feet;
	case rfinger_bg:
		return rfinger;
	case rhand_bg:
		return rhand;
	case torso_bg:
		return torso;
	case amulet_bg:
		return amulet;
	case quiver_bg:
		return quiver;
	case back_2h_bg:
		return back_2h;
	case back_shield_bg:
		return back_shield;
	case earrings_bg:
		return earrings;
	case cloak_bg:
		return cloak;
	case gloves_bg:
		return gloves;
	case ucont_bg:
		return ucont;
	case both_hands_bg:
		return both_hands;
	case lrgloves_bg:
		return lrgloves;
	case triple_bolts_bg:
		return triple_bolts;
	case tongs_bg:
		return lhand;
	case scabbard_bg:
		return scabbard;
	case neck_bg:
		return neck;
	default:
		return invalid_spot;
	}
}

/*
 *  Convert from SI ready spot # to ours (or invalid_spot if not found).
 */

inline int Ready_spot_from_SI(int spot) {
	switch (spot) {
	case head_si:
		return head;
	case backpack_si:
		return backpack;
	case belt_si:
		return belt;
	case lhand_si:
		return lhand;
	case lfinger_si:
		return lfinger;
	case legs_si:
		return legs;
	case feet_si:
		return feet;
	case rfinger_si:
		return rfinger;
	case rhand_si:
		return rhand;
	case torso_si:
		return torso;
	case amulet_si:
		return amulet;
	case quiver_si:
		return quiver;
	case back_2h_si:
		return back_2h;
	case back_shield_si:
		return back_shield;
	case earrings_si:
		return earrings;
	case cloak_si:
		return cloak;
	case gloves_si:
		return gloves;
	case ucont_si:
		return ucont;
	case both_hands_si:
		return both_hands;
	case lrgloves_si:
		return lrgloves;
	case triple_bolts_si:
		return triple_bolts;
	case scabbard_si:
		return scabbard;
	case neck_si:
		return neck;
	default:
		return invalid_spot;
	}
}

#endif  /* INCL_READY   */

{'repo_name': 'exult/exult', 'stars': '280', 'repo_language': 'C++', 'file_name': 'exconfig.vcproj', 'mime_type': 'text/xml', 'hash': 8484851427867909435, 'source_dataset': 'data'}


/*
 * ******************************************************************************
 * sdrtrunk
 * Copyright (C) 2014-2019 Dennis Sheirer
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 * *****************************************************************************
 */

package io.github.dsheirer.module.decode.p25.phase1.message.tsbk.unknown.isp;

import io.github.dsheirer.bits.CorrectedBinaryMessage;
import io.github.dsheirer.identifier.Identifier;
import io.github.dsheirer.module.decode.p25.phase1.P25P1DataUnitID;
import io.github.dsheirer.module.decode.p25.phase1.message.tsbk.OSPMessage;

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

/**
 * Unknown/Unrecognized opcode message.
 */
public class UnknownVendorISPMessage extends OSPMessage
{
    /**
     * Constructs a TSBK from the binary message sequence.
     */
    public UnknownVendorISPMessage(P25P1DataUnitID dataUnitId, CorrectedBinaryMessage message, int nac, long timestamp)
    {
        super(dataUnitId, message, nac, timestamp);
    }

    public String toString()
    {
        StringBuilder sb = new StringBuilder();
        sb.append(getMessageStub());
        sb.append(" VENDOR:").append(getVendor());
        sb.append(" UNRECOGNIZED ISP OPCODE");
        sb.append(" MSG:").append(getMessage().toHexString());
        return sb.toString();
    }

    @Override
    public List<Identifier> getIdentifiers()
    {
        return Collections.EMPTY_LIST;
    }
}

{'repo_name': 'DSheirer/sdrtrunk', 'stars': '605', 'repo_language': 'Java', 'file_name': 'denny.xml', 'mime_type': 'text/plain', 'hash': -5928895726550939862, 'source_dataset': 'data'}


/* ScummVM - Graphic Adventure Engine
 *
 * ScummVM is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the COPYRIGHT
 * file distributed with this source distribution.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */

#ifndef ULTIMA8_WORLD_SNAPPROCESS_H
#define ULTIMA8_WORLD_SNAPPROCESS_H

#include "ultima/ultima8/kernel/process.h"
#include "ultima/ultima8/misc/rect.h"

namespace Ultima {
namespace Ultima8 {

class Item;

class SnapProcess : public Process {
public:
	SnapProcess();

	// p_dynamic_cast stuff
	ENABLE_RUNTIME_CLASSTYPE()

	void run() override;

	bool loadData(Common::ReadStream *rs, uint32 version);
	void saveData(Common::WriteStream *ws) override;

	void addEgg(Item *item);
	void removeEgg(Item *item);

	static SnapProcess *get_instance();

protected:
	static SnapProcess *_instance;

	void getSnapEggRange(const Item *egg, Rect &rect) const;
	void updateCurrentEgg();
	bool isNpcInRangeOfCurrentEgg() const;

	ObjId   _currentSnapEgg;
	Rect	_currentSnapEggRange;
	Std::list<ObjId> _snapEggs;
};

} // End of namespace Ultima8
} // End of namespace Ultima

#endif

{'repo_name': 'scummvm/scummvm', 'stars': '1322', 'repo_language': 'C++', 'file_name': 'coktel_decoder.cpp', 'mime_type': 'text/x-c++', 'hash': 663831487693710632, 'source_dataset': 'data'}


import sys
import numpy as np
import pytest

from numpy.testing import (assert_equal,
                           assert_almost_equal,
                           run_module_suite)
from dipy.data import get_fnames
from dipy.io.streamline import load_tractogram
from dipy.segment.bundles import RecoBundles
from dipy.tracking.distances import bundles_distances_mam
from dipy.tracking.streamline import Streamlines
from dipy.segment.clustering import qbx_and_merge

is_big_endian = 'big' in sys.byteorder.lower()

def setup_module():
    global f, f1, f2, f3, fornix

    fname = get_fnames('fornix')
    fornix = load_tractogram(fname, 'same',
                             bbox_valid_check=False).streamlines

    f = Streamlines(fornix)
    f1 = f.copy()

    f2 = f1[:20].copy()
    f2._data += np.array([50, 0, 0])

    f3 = f1[200:].copy()
    f3._data += np.array([100, 0, 0])

    f.extend(f2)
    f.extend(f3)

@pytest.mark.skipif(is_big_endian,
                    reason="Little Endian architecture required")
def test_rb_check_defaults():

    rb = RecoBundles(f, greater_than=0, clust_thr=10)

    rec_trans, rec_labels = rb.recognize(model_bundle=f2,
                                         model_clust_thr=5.,
                                         reduction_thr=10)

    D = bundles_distances_mam(f2, f[rec_labels])

    # check if the bundle is recognized correctly
    if len(f2) == len(rec_labels):
        for row in D:
            assert_equal(row.min(), 0)

    refine_trans, refine_labels = rb.refine(model_bundle=f2,
                                            pruned_streamlines=rec_trans,
                                            model_clust_thr=5.,
                                            reduction_thr=10)

    D = bundles_distances_mam(f2, f[refine_labels])

    # check if the bundle is recognized correctly
    for row in D:
        assert_equal(row.min(), 0)

@pytest.mark.skipif(is_big_endian,
                    reason="Little Endian architecture required")
def test_rb_disable_slr():

    rb = RecoBundles(f, greater_than=0, clust_thr=10)

    rec_trans, rec_labels = rb.recognize(model_bundle=f2,
                                         model_clust_thr=5.,
                                         reduction_thr=10,
                                         slr=False)

    D = bundles_distances_mam(f2, f[rec_labels])

    # check if the bundle is recognized correctly
    if len(f2) == len(rec_labels):
        for row in D:
            assert_equal(row.min(), 0)

    refine_trans, refine_labels = rb.refine(model_bundle=f2,
                                            pruned_streamlines=rec_trans,
                                            model_clust_thr=5.,
                                            reduction_thr=10)

    D = bundles_distances_mam(f2, f[refine_labels])

    # check if the bundle is recognized correctly
    for row in D:
        assert_equal(row.min(), 0)

@pytest.mark.skipif(is_big_endian,
                    reason="Little Endian architecture required")
def test_rb_slr_threads():

    rng_multi = np.random.RandomState(42)
    rb_multi = RecoBundles(f, greater_than=0, clust_thr=10,
                           rng=np.random.RandomState(42))
    rec_trans_multi_threads, _ = rb_multi.recognize(model_bundle=f2,
                                                    model_clust_thr=5.,
                                                    reduction_thr=10,
                                                    slr=True,
                                                    slr_num_threads=None)

    rb_single = RecoBundles(f, greater_than=0, clust_thr=10,
                            rng=np.random.RandomState(42))
    rec_trans_single_thread, _ = rb_single.recognize(model_bundle=f2,
                                                     model_clust_thr=5.,
                                                     reduction_thr=10,
                                                     slr=True,
                                                     slr_num_threads=1)

    D = bundles_distances_mam(rec_trans_multi_threads, rec_trans_single_thread)

    # check if the bundle is recognized correctly
    # multi-threading prevent an exact match
    for row in D:
        assert_almost_equal(row.min(), 0, decimal=4)

@pytest.mark.skipif(is_big_endian,
                    reason="Little Endian architecture required")
def test_rb_no_verbose_and_mam():

    rb = RecoBundles(f, greater_than=0, clust_thr=10, verbose=False)

    rec_trans, rec_labels = rb.recognize(model_bundle=f2,
                                         model_clust_thr=5.,
                                         reduction_thr=10,
                                         slr=True,
                                         pruning_distance='mam')

    D = bundles_distances_mam(f2, f[rec_labels])

    # check if the bundle is recognized correctly
    if len(f2) == len(rec_labels):
        for row in D:
            assert_equal(row.min(), 0)

    refine_trans, refine_labels = rb.refine(model_bundle=f2,
                                            pruned_streamlines=rec_trans,
                                            model_clust_thr=5.,
                                            reduction_thr=10)

    D = bundles_distances_mam(f2, f[refine_labels])

    # check if the bundle is recognized correctly
    for row in D:
        assert_equal(row.min(), 0)

@pytest.mark.skipif(is_big_endian,
                    reason="Little Endian architecture required")
def test_rb_clustermap():

    cluster_map = qbx_and_merge(f, thresholds=[40, 25, 20, 10])

    rb = RecoBundles(f, greater_than=0, less_than=1000000,
                     cluster_map=cluster_map, clust_thr=10)
    rec_trans, rec_labels = rb.recognize(model_bundle=f2,
                                         model_clust_thr=5.,
                                         reduction_thr=10)

    D = bundles_distances_mam(f2, f[rec_labels])

    # check if the bundle is recognized correctly
    if len(f2) == len(rec_labels):
        for row in D:
            assert_equal(row.min(), 0)

    refine_trans, refine_labels = rb.refine(model_bundle=f2,
                                            pruned_streamlines=rec_trans,
                                            model_clust_thr=5.,
                                            reduction_thr=10)

    D = bundles_distances_mam(f2, f[refine_labels])

    # check if the bundle is recognized correctly
    for row in D:
        assert_equal(row.min(), 0)

@pytest.mark.skipif(is_big_endian,
                    reason="Little Endian architecture required")
def test_rb_no_neighb():
    # what if no neighbors are found? No recognition

    b = Streamlines(fornix)
    b1 = b.copy()

    b2 = b1[:20].copy()
    b2._data += np.array([100, 0, 0])

    b3 = b1[:20].copy()
    b3._data += np.array([300, 0, 0])

    b.extend(b3)

    rb = RecoBundles(b, greater_than=0, clust_thr=10)

    rec_trans, rec_labels = rb.recognize(model_bundle=b2,
                                         model_clust_thr=5.,
                                         reduction_thr=10)

    if len(rec_trans) > 0:
        refine_trans, refine_labels = rb.refine(model_bundle=b2,
                                                pruned_streamlines=rec_trans,
                                                model_clust_thr=5.,
                                                reduction_thr=10)

        assert_equal(len(refine_labels), 0)
        assert_equal(len(refine_trans), 0)

    else:
        assert_equal(len(rec_labels), 0)
        assert_equal(len(rec_trans), 0)

@pytest.mark.skipif(is_big_endian,
                    reason="Little Endian architecture required")
def test_rb_reduction_mam():

    rb = RecoBundles(f, greater_than=0, clust_thr=10, verbose=True)

    rec_trans, rec_labels = rb.recognize(model_bundle=f2,
                                         model_clust_thr=5.,
                                         reduction_thr=10,
                                         reduction_distance='mam',
                                         slr=True,
                                         slr_metric='asymmetric',
                                         pruning_distance='mam')

    D = bundles_distances_mam(f2, f[rec_labels])

    # check if the bundle is recognized correctly
    if len(f2) == len(rec_labels):
        for row in D:
            assert_equal(row.min(), 0)

    refine_trans, refine_labels = rb.refine(model_bundle=f2,
                                            pruned_streamlines=rec_trans,
                                            model_clust_thr=5.,
                                            reduction_thr=10)

    D = bundles_distances_mam(f2, f[refine_labels])

    # check if the bundle is recognized correctly
    for row in D:
        assert_equal(row.min(), 0)

if __name__ == '__main__':

    run_module_suite()

{'repo_name': 'dipy/dipy', 'stars': '331', 'repo_language': 'Python', 'file_name': 'basic_flow.rst', 'mime_type': 'text/plain', 'hash': -8913905625808989711, 'source_dataset': 'data'}


package proxy

import (
	"github.com/TeaWeb/build/internal/teaweb/actions/default/proxy/proxyutils"
	"github.com/iwind/TeaGo/actions"
)

type StatusAction actions.Action

func (this *StatusAction) Run() {
	this.Data["changed"] = proxyutils.ProxyIsChanged()
	this.Success()
}

{'repo_name': 'TeaWeb/build', 'stars': '436', 'repo_language': 'Go', 'file_name': 'main.go', 'mime_type': 'text/x-c', 'hash': 4127198321116246696, 'source_dataset': 'data'}


// ltStringProc.c
//
// -------------------------------------------------
// Copyright 2015-2020 Dominic Ford
//
// This file is part of StarCharter.
//
// StarCharter is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// StarCharter is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with StarCharter.  If not, see <http://www.gnu.org/licenses/>.
// -------------------------------------------------

// Linked-list string processing functions

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "coreUtils/asciiDouble.h"

#include "ltList.h"

//! strSplit - Split up a string into a linked-list of words separated by whitespace
//! \param in - The string to split
//! \return - A linked list of the words within the input string

list *strSplit(char *in) {
    int pos, start, end;
    char *word;
    char *text_buffer;
    list *out;
    out = listInit();
    pos = 0;
    text_buffer = (char *) malloc((strlen(in) + 8) * sizeof(char));
    while (in[pos] != '\0') {
        // Scan along to find the next word
        while ((in[pos] <= ' ') && (in[pos] > '\0')) pos++;
        start = pos;

        // Scan along to find the end of this word
        while ((in[pos] > ' ') && (in[pos] > '\0')) pos++;
        end = pos;

        if (end > start) {
            word = str_slice(in, text_buffer, start, end);
            listAppendString(out, word);
        }
    }
    free(text_buffer);
    return out;
}

{'repo_name': 'dcf21/star-charter', 'stars': '250', 'repo_language': 'C', 'file_name': 'constellationLines.py', 'mime_type': 'text/x-python', 'hash': 8552464744460007139, 'source_dataset': 'data'}


"use strict";

var chalk = require("chalk");
var immutableDelete = require("immutable-delete");
var printTransactionStatus = require("./print-transaction-status");
var speedomatic = require("speedomatic");
var debugOptions = require("../../debug-options");

function createMarket(augur, market, designatedReporterAddress, auth, callback) {
  var createMarketOfType;
  switch (market.marketType) {
    case "categorical":
      createMarketOfType = augur.createMarket.createCategoricalMarket;
      break;
    case "scalar":
      createMarketOfType = augur.createMarket.createScalarMarket;
      break;
    case "yesNo":
    default:
      createMarketOfType = augur.createMarket.createYesNoMarket;
  }
  var createMarketParams = Object.assign({}, immutableDelete(market, ["orderBook", "marketType"]), {
    meta: auth,
    universe: augur.contracts.addresses[augur.rpc.getNetworkID()].Universe,
    _feePerEthInWei: speedomatic.fix(0.01, "hex"),
    _denominationToken: augur.contracts.addresses[augur.rpc.getNetworkID()].Cash,
    _designatedReporterAddress: designatedReporterAddress,
    onSent: function (res) {
      if (debugOptions.cannedMarkets) console.log(chalk.green.dim("createMarket sent:"), chalk.green(res.hash));
    },
    onSuccess: function (res) {
      if (debugOptions.cannedMarkets) {
        console.log(chalk.green.dim("createMarket success:"), chalk.green(res.callReturn));
        printTransactionStatus(augur.rpc, res.hash);
      }
      callback(null, res.callReturn);
    },
    onFailed: function (err) {
      if (debugOptions.cannedMarkets) {
        console.error(chalk.red.bold("createMarket failed:"), err, market);
        if (err != null) printTransactionStatus(augur.rpc, err.hash);
      }
      callback(err);
    },
  });
  if (debugOptions.cannedMarkets) console.log("createMarket params:", createMarketParams);
  createMarketOfType(createMarketParams);
}

module.exports = createMarket;

{'repo_name': 'AugurProject/augur.js', 'stars': '129', 'repo_language': 'JavaScript', 'file_name': 'genesis.json', 'mime_type': 'text/plain', 'hash': 7081384213785596809, 'source_dataset': 'data'}


/*
 * Copyright (c) 2000, 2008, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 *
 */

package com.sun.java.swing.action;

import javax.swing.ImageIcon;

class ActionUtilities
{

    ActionUtilities()
    {
    }

    public ImageIcon getIcon(String name)
    {
        String imagePath = "/toolbarButtonGraphics/" + name;
        java.net.URL url = getClass().getResource(imagePath);
        if(url != null)
            return new ImageIcon(url);
        else
            return null;
    }

    public static final String IMAGE_DIR = "/toolbarButtonGraphics/";

}

{'repo_name': 'corretto/corretto-11', 'stars': '405', 'repo_language': 'Java', 'file_name': 'zBarrierSetC1.hpp', 'mime_type': 'text/x-c++', 'hash': -4015424061558627230, 'source_dataset': 'data'}


/*
 *     Generated by class-dump 3.3.4 (64 bit).
 *
 *     class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard.
 */

#import "FBMShareAttachment.h"

@class FBMSticker;

@interface FBMStickerAttachment : FBMShareAttachment
{
    FBMSticker *_sticker;
}

@property(readonly, nonatomic) FBMSticker *sticker; // @synthesize sticker=_sticker;
//- (void).cxx_destruct;
- (id)description;
- (id)initWithSticker:(id)arg1;

@end

{'repo_name': 'Te-k/flexidie', 'stars': '808', 'repo_language': 'None', 'file_name': 'main.m', 'mime_type': 'text/x-objective-c', 'hash': -7099372558573001037, 'source_dataset': 'data'}


# Step 7: Share Code

## Video of this Lesson

<iframe width="560" height="600" src="https://www.youtube.com/embed/icyOSQ6gAm0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

Awesome! The application is working end to end! However, there is a problem. Both the backend and the frontend define the `Todo` interface. The interface is in sync now, but in a real application, over time, it will diverge, and, as a result, runtime errors will creep in. You should share this interface between the backend and the frontend. In Nx, you can do this by creating a library.

**Run the following generator to create a library:**

```bash
npx nx g @nrwl/workspace:lib data
```

The result should look like this:

```treeview
myorg/
├── apps/
│   ├── todos/
│   ├── todos-e2e/
│   └── api/
├── libs/
│   └── data/
│       ├── src/
│       │   ├── lib/
│       │   │   └── data.ts
│       │   └── index.ts
│       ├── jest.conf.js
│       ├── tsconfig.app.json
│       ├── tsconfig.json
│       ├── tsconfig.spec.json
│       └── tslint.json
├── workspace.json
├── nx.json
├── package.json
├── tools/
├── tsconfig.json
└── tslint.json
```

**Copy the interface into `libs/data/src/lib/data.ts`.**

```typescript
export interface Todo {
  title: string;
}
```

### A note about VS Code :

If you're using [VS Code](https://code.visualstudio.com/) it may be necessary at this point to restart the TS server so that the new `@myorg/data` package is recognised. This may need to be done **every time a new workspace library is added**.

## Refactor the API

**Now update `apps/api/src/app/app.service.ts` to import the interface:**

```typescript
import { Injectable } from '@nestjs/common';
import { Todo } from '@myorg/data';

@Injectable()
export class AppService {
  todos: Todo[] = [{ title: 'Todo 1' }, { title: 'Todo 2' }];

  getData(): Todo[] {
    return this.todos;
  }

  addTodo() {
    this.todos.push({
      title: `New todo ${Math.floor(Math.random() * 1000)}`,
    });
  }
}
```

## Update the Angular Application

**Next import the interface in `apps/todos/src/app/app.component.ts`:**

```typescript
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Todo } from '@myorg/data';

@Component({
  selector: 'myorg-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  todos: Todo[] = [];

  constructor(private http: HttpClient) {
    this.fetch();
  }

  fetch() {
    this.http.get<Todo[]>('/api/todos').subscribe((t) => (this.todos = t));
  }

  addTodo() {
    this.http.post('/api/addTodo', {}).subscribe(() => {
      this.fetch();
    });
  }
}
```

Every time you add a new library, you have to restart `npx nx serve`. **So restart both `npx nx serve api` and `npx nx serve todos` and you should see the application running.**

!!!!!
Nx allows you to share code...
!!!!!
Between frontend and backend apps
Between different frontend apps
Between different node apps

{'repo_name': 'nrwl/nx', 'stars': '4009', 'repo_language': 'TypeScript', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 6824181298561879376, 'source_dataset': 'data'}


/*!
 * statuses
 * Copyright(c) 2014 Jonathan Ong
 * Copyright(c) 2016 Douglas Christopher Wilson
 * MIT Licensed
 */

'use strict'

/**
 * Module dependencies.
 * @private
 */

var codes = require('./codes.json')

/**
 * Module exports.
 * @public
 */

module.exports = status

// array of status codes
status.codes = populateStatusesMap(status, codes)

// status codes for redirects
status.redirect = {
  300: true,
  301: true,
  302: true,
  303: true,
  305: true,
  307: true,
  308: true
}

// status codes for empty bodies
status.empty = {
  204: true,
  205: true,
  304: true
}

// status codes for when you should retry the request
status.retry = {
  502: true,
  503: true,
  504: true
}

/**
 * Populate the statuses map for given codes.
 * @private
 */

function populateStatusesMap (statuses, codes) {
  var arr = []

  Object.keys(codes).forEach(function forEachCode (code) {
    var message = codes[code]
    var status = Number(code)

    // Populate properties
    statuses[status] = message
    statuses[message] = status
    statuses[message.toLowerCase()] = status

    // Add to array
    arr.push(status)
  })

  return arr
}

/**
 * Get the status code.
 *
 * Given a number, this will throw if it is not a known status
 * code, otherwise the code will be returned. Given a string,
 * the string will be parsed for a number and return the code
 * if valid, otherwise will lookup the code assuming this is
 * the status message.
 *
 * @param {string|number} code
 * @returns {number}
 * @public
 */

function status (code) {
  if (typeof code === 'number') {
    if (!status[code]) throw new Error('invalid status code: ' + code)
    return code
  }

  if (typeof code !== 'string') {
    throw new TypeError('code must be a number or string')
  }

  // '403'
  var n = parseInt(code, 10)
  if (!isNaN(n)) {
    if (!status[n]) throw new Error('invalid status code: ' + n)
    return n
  }

  n = status[code.toLowerCase()]
  if (!n) throw new Error('invalid status message: "' + code + '"')
  return n
}

{'repo_name': 'liyuechun/JavaScript30-liyuechun', 'stars': '210', 'repo_language': 'HTML', 'file_name': 'README.md', 'mime_type': 'text/html', 'hash': -1421799357068555295, 'source_dataset': 'data'}


<?xml version="1.0"?>
<ZopeData>
  <record id="1" aka="AAAAAAAAAAE=">
    <pickle>
      <global name="PythonScript" module="Products.PythonScripts.PythonScript"/>
    </pickle>
    <pickle>
      <dictionary>
        <item>
            <key> <string>Script_magic</string> </key>
            <value> <int>3</int> </value>
        </item>
        <item>
            <key> <string>_bind_names</string> </key>
            <value>
              <object>
                <klass>
                  <global name="NameAssignments" module="Shared.DC.Scripts.Bindings"/>
                </klass>
                <tuple/>
                <state>
                  <dictionary>
                    <item>
                        <key> <string>_asgns</string> </key>
                        <value>
                          <dictionary>
                            <item>
                                <key> <string>name_container</string> </key>
                                <value> <string>container</string> </value>
                            </item>
                            <item>
                                <key> <string>name_context</string> </key>
                                <value> <string>context</string> </value>
                            </item>
                            <item>
                                <key> <string>name_m_self</string> </key>
                                <value> <string>script</string> </value>
                            </item>
                            <item>
                                <key> <string>name_subpath</string> </key>
                                <value> <string>traverse_subpath</string> </value>
                            </item>
                          </dictionary>
                        </value>
                    </item>
                  </dictionary>
                </state>
              </object>
            </value>
        </item>
        <item>
            <key> <string>_params</string> </key>
            <value> <string>state_change</string> </value>
        </item>
        <item>
            <key> <string>id</string> </key>
            <value> <string>deleteDocument</string> </value>
        </item>
      </dictionary>
    </pickle>
  </record>
</ZopeData>

{'repo_name': 'Nexedi/erp5', 'stars': '116', 'repo_language': 'JavaScript', 'file_name': 'base_category_list.xml', 'mime_type': 'text/plain', 'hash': 6372024232578554426, 'source_dataset': 'data'}


CAMPAIGN:Kingdoms of Kalamar
KEY:Kingdoms of Kalamar v.3.5
BOOKTYPE:Campaign Setting
GAMEMODE:Bahamut35e
SOURCELONG:Kingdoms of Kalamar Campaign
SOURCESHORT:PH
SOURCEDATE:2003-03
RANK:200303
PUBNAMELONG:Kenzer and Co
PUBNAMESHORT:Kenzer
TYPE:Kenzer and Co.Campaign.Kingdoms of Kalamar
# COVER should be cover_gameMode_pub_book.file
#COVER:../../../../_artwork/cover_35e_wotc_ph.jpg
# LOGO should be logo_pub.file
#LOGO:../../../../_artwork/logo_wotc.png
#INFOTEXT:This loads the Player's Handbook materials - it's part of the Core Set

DEITY:kokc_deities.lst

EQUIPMENT:kokc_equip.lst
KIT:kokc_kits.lst
LANGUAGE:kokc_languages.lst

ARMORPROF:kokc_profs_armor.lst

RACE:kokc_races.lst
SPELL:kokc_spells.lst

INFOTEXT:Supports 6.9.1
# ENTRY DATE: 2020-05
# LST MONKEY: Bahamut
# RELEASE REVIEW #
# BETA:
# RELEASE:
# Built for PCGen Version: 6.09.03
# Updated to work with version: -
# MINVER:6.9
# MINDEVVER:6.09.3
# COMMENTS:

{'repo_name': 'BahamutDragon/pcgen', 'stars': '240', 'repo_language': 'XSLT', 'file_name': 'k_profs_weapon.lst', 'mime_type': 'text/plain', 'hash': 7897052509254402191, 'source_dataset': 'data'}


<?php
/*
 * Copyright 2014 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

class Google_Service_Sheets_DeleteDimensionGroupRequest extends Google_Model
{
  protected $rangeType = 'Google_Service_Sheets_DimensionRange';
  protected $rangeDataType = '';

  /**
   * @param Google_Service_Sheets_DimensionRange
   */
  public function setRange(Google_Service_Sheets_DimensionRange $range)
  {
    $this->range = $range;
  }
  /**
   * @return Google_Service_Sheets_DimensionRange
   */
  public function getRange()
  {
    return $this->range;
  }
}

{'repo_name': 'WWBN/AVideo', 'stars': '1149', 'repo_language': 'PHP', 'file_name': 'design_themes.php', 'mime_type': 'text/html', 'hash': -6882772806994779712, 'source_dataset': 'data'}


/*****************************************************************************
 *                                                                           *
 * File: espi.h                                                              *
 * $Revision: 1.7 $                                                          *
 * $Date: 2005/06/21 18:29:47 $                                              *
 * Description:                                                              *
 *  part of the Chelsio 10Gb Ethernet Driver.                                *
 *                                                                           *
 * This program is free software; you can redistribute it and/or modify      *
 * it under the terms of the GNU General Public License, version 2, as       *
 * published by the Free Software Foundation.                                *
 *                                                                           *
 * You should have received a copy of the GNU General Public License along   *
 * with this program; if not, see <http://www.gnu.org/licenses/>.            *
 *                                                                           *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED    *
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF      *
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.                     *
 *                                                                           *
 * http://www.chelsio.com                                                    *
 *                                                                           *
 * Copyright (c) 2003 - 2005 Chelsio Communications, Inc.                    *
 * All rights reserved.                                                      *
 *                                                                           *
 * Maintainers: maintainers@chelsio.com                                      *
 *                                                                           *
 * Authors: Dimitrios Michailidis   <dm@chelsio.com>                         *
 *          Tina Yang               <tainay@chelsio.com>                     *
 *          Felix Marti             <felix@chelsio.com>                      *
 *          Scott Bardone           <sbardone@chelsio.com>                   *
 *          Kurt Ottaway            <kottaway@chelsio.com>                   *
 *          Frank DiMambro          <frank@chelsio.com>                      *
 *                                                                           *
 * History:                                                                  *
 *                                                                           *
 ****************************************************************************/

#ifndef _CXGB_ESPI_H_
#define _CXGB_ESPI_H_

#include "common.h"

struct espi_intr_counts {
	unsigned int DIP4_err;
	unsigned int rx_drops;
	unsigned int tx_drops;
	unsigned int rx_ovflw;
	unsigned int parity_err;
	unsigned int DIP2_parity_err;
};

struct peespi;

struct peespi *t1_espi_create(adapter_t *adapter);
void t1_espi_destroy(struct peespi *espi);
int t1_espi_init(struct peespi *espi, int mac_type, int nports);

void t1_espi_intr_enable(struct peespi *);
void t1_espi_intr_clear(struct peespi *);
void t1_espi_intr_disable(struct peespi *);
int t1_espi_intr_handler(struct peespi *);
const struct espi_intr_counts *t1_espi_get_intr_counts(struct peespi *espi);

u32 t1_espi_get_mon(adapter_t *adapter, u32 addr, u8 wait);
int t1_espi_get_mon_t204(adapter_t *, u32 *, u8);

#endif /* _CXGB_ESPI_H_ */

{'repo_name': 'seemoo-lab/bcm-rpi3', 'stars': '140', 'repo_language': 'C', 'file_name': 'spi.c', 'mime_type': 'text/x-c', 'hash': -940281585141871970, 'source_dataset': 'data'}