text:
package com.example.charmer.moving.fragment;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.example.charmer.moving.MainActivity;
import com.example.charmer.moving.R;
import com.example.charmer.moving.contantData.HttpUtils;
import com.example.charmer.moving.friendchat.PostAcyivity;
import com.example.charmer.moving.friendchat.SearchTalk;
import com.example.charmer.moving.pojo.Friend;
import com.example.charmer.moving.pojo.Qun;
import com.example.charmer.moving.pojo.TLZ;
import com.example.charmer.moving.pojo.User;
import com.example.charmer.moving.utils.CommonAdapter;
import com.example.charmer.moving.utils.Friend_titlebar;
import com.example.charmer.moving.utils.NoScrollViewPager;
import com.example.charmer.moving.utils.ViewHolder;
import com.example.charmer.moving.utils.xUtilsImageUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.UserInfo;

/**
 * Created by lenovo on 2016/10/11.
 */
public class Fragment_friend extends Fragment implements View.OnClickListener {

    @InjectView(R.id.edsearch)
    EditText edsearch;
    private NoScrollViewPager vpFriend;
    @InjectView(R.id.ll_sreach)
    LinearLayout llSreach;
    @InjectView(R.id.progressbar)
    ProgressBar progressbar;
    @InjectView(R.id.tv_jiazai)
    TextView tvJiazai;
    private ObjectAnimator mHeaderAnimator;
    private ObjectAnimator mBottomAnimator;
    private ObjectAnimator llsearch;
    private LinearLayout mBottom_bar;
    private View rl_talk;
    private ImageView iv_talk;
    private ImageView iv_goodfriend;
    private View rl_friend;
    private View rl_qun;
    private View rl_tlz;
    private ImageView iv_talk1;
    private SwipeMenuListView listView;
    private ListView qunlistView;
    private boolean isRunning = false;
    private PagerAdapter pagerAdapter;
    private List<View> views = new ArrayList<View>();
    private final List<Friend> friends = new ArrayList<Friend>();//所有好友信息
    private  List<Qun> quns=new ArrayList<Qun>();//群信息
    private  List<TLZ> tlzs=new ArrayList<TLZ>();//讨论组信息
    private List<User> usersToken = new ArrayList<User>();//所有user的Token
    CommonAdapter<Friend> goodfriendad;
    CommonAdapter<Qun> qunad;
    CommonAdapter<TLZ> tlzad;
    private Friend_titlebar fd_friend;
    private Friend_titlebar fd_talk;
    private Friend_titlebar fd_qun;
    private Friend_titlebar fd_tlz;
    private Map<String, Integer> tip = new HashMap<>();
    private List<View> ft = new ArrayList<>();
    private int pv_position;
    private RelativeLayout mHead_bar;
    private SwipeRefreshLayout re_friend;
    private boolean flag = true;
    private boolean flag1=false;
    private User user;
    private String Token;
    private RelativeLayout friendbg;
    private SwipeRefreshLayout re_qun;
    private ListView tlzlistview;
    private SwipeRefreshLayout re_tlz;
    private ProgressBar progress2;
    private ImageView userimg;
    private ImageView no_yuan;
    private ProgressBar progress4;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_friend, null);
//       Token= MainActivity.getToken();
//        Log.i("Tooooo2","kenn"+Token);
        tip.put("篮球", R.drawable.basketball);
        tip.put("游泳", R.drawable.swim);
        tip.put("乒乓球", R.drawable.pingp);
        tip.put("网球", R.drawable.vallyball);
        tip.put("足球", R.drawable.football);
        tip.put("钓鱼", R.drawable.fish);
        vpFriend = (NoScrollViewPager) view.findViewById(R.id.vp_friend);
        vpFriend.setNoScroll(true);
        mBottom_bar = (LinearLayout) getActivity().findViewById(R.id.main_bottom);
        mHead_bar = ((RelativeLayout) view.findViewById(R.id.rl_toptitle));
        initdata();
        initview(view);
        ButterKnife.inject(this, view);
        initEnt();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        getQunData();
    }

    private void initdata() {
        //所有user的token后台处理
        //已在MainActivity中注册所有Id并获得usertoken
        //尝试异步任务
        //第四次异步任务终于成功哇哈哈哈哈哈哈!!!!!时间优化4倍
        Token = MainActivity.getToken();
        /**
         * 连接
         */
        RongIM.connect(Token, new RongIMClient.ConnectCallback() {
            @Override
            public void onTokenIncorrect() {
                Log.i("Tooooo1", "kenn" + Token);
                Log.e("framgment", "tokenINcorrect");
            }

            @Override
            public void onSuccess(String s) {
                Log.e("framgment1", "onSuccess: " + s);
                RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {
                    @Override
                    public UserInfo getUserInfo(String s) {
                        for (Friend i : friends) {
                            if (i.getFriendid().equals(s)) {
                                Log.i("提供了", "用户" + s);
                                return new UserInfo(i.getFriendid() + "", i.getName(), Uri.parse(HttpUtils.hostpc+ i.getUser().getUserimg()));
                            }
                        }
                        return null;
                    }
                }, true);
                //容云用户提供头像
                Rong();
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                Log.e("framgmente", "onError: " + errorCode.getValue());
            }
        });
        Log.i("Tooooo5", "kenn" + Token);
        //对好友的信息处理
        getFriendData();
        //群
        getQunData();
        //讨论组
        getTlzData();

    }

    private void initview(View view) {
        //第三方控件侧滑
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                // create "open" item
                SwipeMenuItem openItem = new SwipeMenuItem(
                        getContext());
                // set item background
                openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
                        0xCE)));
                // set item width
                openItem.setWidth(dp2px(90));
                // set item title
                openItem.setTitle("phone");
                // set item title fontsize
                openItem.setTitleSize(18);
                // set item title font color
                openItem.setTitleColor(Color.WHITE);
                // add to menu
                menu.addMenuItem(openItem);
                // create "delete" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(
                        getContext());
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                        0x3F, 0x25)));
                // set item width
                deleteItem.setWidth(dp2px(90));
                // set a icon
                deleteItem.setIcon(R.drawable.ic_delete);
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };
        no_yuan = ((ImageView) view.findViewById(R.id.hongyuan));
        //主界面
        friendbg = ((RelativeLayout) view.findViewById(R.id.friendbg));
        //每个标题
        fd_talk = ((Friend_titlebar) view.findViewById(R.id.fd_talk));
        //自己的头像
        userimg = ((ImageView) fd_talk.findViewById(R.id.left));
        getUserimg();
        //判断是否有申请信息
        ifpost();
        fd_friend = ((Friend_titlebar) view.findViewById(R.id.fd_friend));
        fd_qun = ((Friend_titlebar) view.findViewById(R.id.fd_qun));
        fd_tlz = ((Friend_titlebar) view.findViewById(R.id.fd_tlz));
        ft.add(fd_talk);
        ft.add(fd_friend);
        ft.add(fd_qun);
        ft.add(fd_tlz);
        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
        View v1 = layoutInflater.inflate(R.layout.activity_friend_talk, null);
        View v2 = layoutInflater.inflate(R.layout.activity_friend_goodfriend, null);
        View v3 = layoutInflater.inflate(R.layout.activity_friend_qun, null);
        View v4 = layoutInflater.inflate(R.layout.activity_friend_tlzs, null);
        progress2 = ((ProgressBar) v3.findViewById(R.id.progress2));
        progress4 = ((ProgressBar) v4.findViewById(R.id.progress4));
        //讨论组listview处理
        tlzlistview = ((ListView) v4.findViewById(R.id.lv_tlzs));
        //群listview处理
        qunlistView=((ListView) v3.findViewById(R.id.lv_qun));
        //好友listview处理
        listView = ((SwipeMenuListView) v2.findViewById(R.id.lv_goodfriends));
        listView.setMenuCreator(creator);
        //好友刷新处理
        re_friend = ((SwipeRefreshLayout) v2.findViewById(R.id.re_friend));
        //设置下拉刷新加载圈的颜色
        re_friend.setColorSchemeColors(getResources().getColor(R.color.colorSkybule));
        //设置下拉加载圈出现距离顶部的位置
        re_friend.setDistanceToTriggerSync(getResources().getDimensionPixelOffset(R.dimen.activity_fragment));
        //设置下拉加载圈转动时距离顶部的位置
        re_friend.setProgressViewEndTarget(true, getResources().getDimensionPixelOffset(R.dimen.activity_fragment));
        //群刷新处理
        re_qun = ((SwipeRefreshLayout) v3.findViewById(R.id.re_qun));
        re_qun.setColorSchemeColors(getResources().getColor(R.color.colorSkybule));
        re_qun.setDistanceToTriggerSync(getResources().getDimensionPixelOffset(R.dimen.activity_fragment));
        re_qun.setProgressViewEndTarget(true, getResources().getDimensionPixelOffset(R.dimen.activity_fragment));
        //讨论组刷新
        re_tlz = ((SwipeRefreshLayout) v4.findViewById(R.id.re_tlz));
        re_tlz.setColorSchemeColors(getResources().getColor(R.color.colorSkybule));
        re_tlz.setDistanceToTriggerSync(getResources().getDimensionPixelOffset(R.dimen.activity_fragment));
        re_tlz.setProgressViewEndTarget(true, getResources().getDimensionPixelOffset(R.dimen.activity_fragment));
        //加载圈事件
        refreshData();
        views.add(v1);
        views.add(v2);
        views.add(v3);
        views.add(v4);
        //vp适配器打气
        pagerAdapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return views.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                View view = views.get(position);
                container.addView(view);
                return view;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(views.get(position));
            }
        };
        vpFriend.setAdapter(pagerAdapter);
    }

    private void initEnt() {
        //软键盘不弹出
        edsearch.setInputType(InputType.TYPE_NULL);
        //edsear点击事件
        edsearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(), SearchTalk.class);
                startActivity(intent);
            }
        });
        //好友删除按钮
        listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                      //phone
                        Intent intent = new Intent(Intent.ACTION_CALL);
                        intent.setData(Uri.parse("tel:"+friends.get(position).getUser().getUserphone()));
                        startActivity(intent);
                        break;
                    case 1:
                        //delete
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        builder.setTitle("删除");
                        builder.setMessage("抛弃他?");

                        builder.setIcon(R.drawable.qun);
                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(getActivity(),"好心人",Toast.LENGTH_SHORT).show();
                            }
                        });

                        builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Integer friendid = friends.get(position).getFriendid();
                                RequestParams requestParams = new RequestParams(HttpUtils.host4 + "friendservlet");
                                //获取用户ID
                                requestParams.addQueryStringParameter("choice", 1 + "");
                                requestParams.addQueryStringParameter("friendid", friendid + "");
                                x.http().get(requestParams, new Callback.CommonCallback<String>() {
                                    @Override
                                    public void onSuccess(String result) {
                                    }

                                    @Override
                                    public void onError(Throwable ex, boolean isOnCallback) {
                                    }

                                    @Override
                                    public void onCancelled(CancelledException cex) {
                                    }

                                    @Override
                                    public void onFinished() {
                                    }
                                });
                                friends.remove(position);
                                goodfriendad.notifyDataSetChanged();
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        while (!Thread.currentThread().isInterrupted()) {
                                            try {
                                                Thread.sleep(100);
                                            } catch (InterruptedException e) {
                                                Thread.currentThread().interrupt();
                                            }
                                            //使用postInvalidate可以直接在线程中更新界面
                                            listView.postInvalidate();
                                        }
                                    }
                                }).start();

                                Toast.makeText(getActivity(),"他已被你狠心抛弃",Toast.LENGTH_SHORT).show();
                            }
                        });

                        builder.setNeutralButton("再说", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(getActivity(),"好的",Toast.LENGTH_SHORT).show();

                            }
                        });

                        builder.show();

                        break;
                }
                // false : close the menu; true : not close the menu
                return false;
            }
        });
        //listview滑动监听隐藏
        listView.setOnTouchListener(new View.OnTouchListener() {
            private float mEndY;
            private float mStartY;
            private int direction;//0表示向上,1表示向下

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mStartY = event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        mEndY = event.getY();
                        float v1 = mEndY - mStartY;

                        if (v1 > 3 && !isRunning && direction == 1) {
                            direction = 0;
                            showBar();
                            mStartY = mEndY;
                            return false;
                        } else if (v1 < -3 && !isRunning && direction == 0) {
                            direction = 1;
                            hideBar();
                            mStartY = mEndY;
                            return false;
                        }
                        mStartY = mEndY;

                        break;
                    case MotionEvent.ACTION_UP:
                        break;
                }
                return false;
            }
        });
        //群滑动监听
        qunlistView.setOnTouchListener(new View.OnTouchListener() {
            private float mEndY;
            private float mStartY;
            private int direction;//0表示向上,1表示向下
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mStartY = event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        mEndY = event.getY();
                        float v1 = mEndY - mStartY;
                        if (v1 > 3 && !isRunning && direction == 1) {
                            direction = 0;
                            showBar();
                            mStartY = mEndY;
                            return false;
                        } else if (v1 < -3 && !isRunning && direction == 0) {
                            direction = 1;
                            hideBar();
                            mStartY = mEndY;
                            return false;
                        }
                        mStartY = mEndY;
                        break;
                    case MotionEvent.ACTION_UP:
                        break;
                }
                return false;
            }
        });
        //讨论组滑动
        tlzlistview.setOnTouchListener(new View.OnTouchListener() {
            private float mEndY;
            private float mStartY;
            private int direction;//0表示向上,1表示向下
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mStartY = event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        mEndY = event.getY();
                        float v1 = mEndY - mStartY;
                        if (v1 > 3 && !isRunning && direction == 1) {
                            direction = 0;
                            showBar();
                            mStartY = mEndY;
                            return false;
                        } else if (v1 < -3 && !isRunning && direction == 0) {
                            direction = 1;
                            hideBar();
                            mStartY = mEndY;
                            return false;
                        }
                        mStartY = mEndY;
                        break;
                    case MotionEvent.ACTION_UP:
                        break;
                }
                return false;
            }
        });
        //容云点击聊天按钮单聊
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (RongIM.getInstance() != null) {
                    RongIM.getInstance().startPrivateChat(getActivity(), friends.get(position - 1).getFriendid() + "", friends.get(position - 1).getName());
                }
            }
        });

        //群聊
        qunlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(RongIM.getInstance()!=null){
                    RongIM.getInstance().startGroupChat(getActivity(),quns.get(position).getQunid()+"", quns.get(position).getQunname());
                }
            }
        });
        //讨论组聊天
        tlzlistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(RongIM.getInstance()!=null){
                    RongIM.getInstance().startDiscussionChat(getActivity(), tlzs.get(position).getTlzid(),tlzs.get(position).getTlzname());
                }
            }
        });
        //会话标题按钮

        fd_talk.setImgLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                no_yuan.setVisibility(View.GONE);
                Intent intent=new Intent(getActivity(), PostAcyivity.class);
                startActivity(intent);

            }
        });
        rightclick(fd_talk, 1);
        rightclick(fd_friend, 2);
        rightclick(fd_qun, 3);
        rightclick(fd_tlz, 0);
        leftclick(fd_friend, 0);
        leftclick(fd_qun, 1);
        leftclick(fd_tlz, 2);
        //vp滑动事件
        vpFriend.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            String str[] = new String[]{"会话", "好友", "群", "讨论组"};

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Toast.makeText(getActivity(), str[position], Toast.LENGTH_SHORT).show();
                ft.get(position).setVisibility(View.VISIBLE);
                ft.get(pv_position).setVisibility(View.GONE);
                pv_position = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }
    //各种控件的点击事件
    @Override
    public void onClick(View v) {
      switch (v.getId()){

      }
    }
    //好友列表的填充
    class FriendAdapter extends CommonAdapter<Friend> {

        public FriendAdapter(Context context, List<Friend> lists, int layoutId) {
            super(context, lists, layoutId);
        }

        @Override
        public void convert(ViewHolder viewHolder, Friend friend, int position) {

            final String str = friend.getUser().getUserimg();

            Log.i("daqi", "打气了");
            TextView tv_username = ((TextView) viewHolder.getViewById(R.id.tv_username));
            tv_username.setText(friend.getUser().getUsername());
            TextView tv_nowact = ((TextView) viewHolder.getViewById(R.id.tv_nowact));
            if(friend.getContent()==null){
                tv_nowact.setText("暂无");
            }else{
            tv_nowact.setText(friend.getContent());}
            ImageView iv_toux = ((ImageView) viewHolder.getViewById(R.id.iv_toux));
            xUtilsImageUtils.display(iv_toux, HttpUtils.host4+"upload/" + str, true);
            ImageView i_tip = ((ImageView) viewHolder.getViewById(R.id.i_tip));
            System.out.println();
            if (friend.getTitle()!=null){
                if (friend.getTitle().isEmpty()){
                    i_tip.setImageResource(R.drawable.wu);
                }
                else {
                    i_tip.setImageResource(tip.get(friend.getTitle()));
                }
            }
            if (friend.getTitle()==null){
                i_tip.setImageResource(R.drawable.wu);
            }
        }
    }
    //群列表的填充
  class QunAdapter extends CommonAdapter<Qun> {
        public QunAdapter(Context context, List<Qun> lists, int layoutId) {
            super(context, lists, layoutId);
        }

        @Override
        public void convert(ViewHolder viewHolder, Qun qun, int position) {
            ImageView qunimg=((ImageView) viewHolder.getViewById(R.id.qunimg));
            xUtilsImageUtils.display(qunimg, qun.getQunimg(),false);
            TextView qun_name=((TextView) viewHolder.getViewById(R.id.qun_name));
            qun_name.setText(qun.getQunname());
        }
    }
    //讨论组列表的填充
    class TlzAdapter extends CommonAdapter<TLZ>{

        public TlzAdapter(Context context, List<TLZ> lists, int layoutId) {
            super(context, lists, layoutId);
        }

        @Override
        public void convert(ViewHolder viewHolder, TLZ tlz, int position) {
           TextView tv_tlzname= ((TextView) viewHolder.getViewById(R.id.tv_tlzname));
            tv_tlzname.setText(tlz.getTlzname());
            String userid=tlz.getTlzusers();
            String[] userids=userid.split(",");
            for(int i=0;i<userids.length;i++){
                Log.i("convertids",userids[i]);
            }
        }
    }
    //对好友的信息处理
    public void getFriendData() {
        RequestParams requestParams = new RequestParams(HttpUtils.host4 + "friendservlet");
        requestParams.addQueryStringParameter("choice", 6+ "");
        //获取用户ID
        requestParams.addQueryStringParameter("userid", MainActivity.getUser().getUserid() + "");
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if(result.equals("[]")){
                    Toast.makeText(getActivity(),"没有朋友呢(╯^╰〉",Toast.LENGTH_SHORT).show();
                }
                friends.clear();
                progressbar.setVisibility(View.GONE);
                tvJiazai.setVisibility(View.GONE);
                Gson gson = new Gson();
                Type type = new TypeToken<List<Friend>>() {
                }.getType();
                Log.i("getFrienddata", result);
                List<Friend> newfds = gson.fromJson(result, type);
                friends.addAll(newfds);
                goodfriendad = new FriendAdapter(getActivity(), friends, R.layout.activity_friend_goodfriend_layout);
                listView.setAdapter(goodfriendad);
                if (flag) {
                    View view1 = View.inflate(getContext(), R.layout.friendnumber, null);
                    TextView fdnum = ((TextView) view1.findViewById(R.id.friendnumber));
                    fdnum.setText(friends.size() + "");
                    listView.addFooterView(view1);
                    View view2 = View.inflate(getContext(), R.layout.friend_bugdeal, null);
                    listView.addHeaderView(view2);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                System.out.println("===================================");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    //对群组信息的处理
     public void getQunData(){
     RequestParams params=new RequestParams(HttpUtils.host4+"getqun");
         params.addQueryStringParameter("choice",0+"");//改动
         params.addQueryStringParameter("userid",MainActivity.getUser().getUserid() + "");
         x.http().get(params, new Callback.CommonCallback<String>() {
             @Override
             public void onSuccess(String result) {
                 if(result.equals("[]")){
                     Toast.makeText(getActivity(),"暂时没有组织-____-\"",Toast.LENGTH_SHORT).show();
                 }
                 quns.clear();
                 Log.i("qunData",result);
                 progress2.setVisibility(View.GONE);
                 Gson gson = new Gson();
                 Type type = new TypeToken<List<Qun>>() {
                 }.getType();
                 List<Qun> newquns=gson.fromJson(result,type);
                 quns.addAll(newquns);
                 qunad=new QunAdapter(getActivity(),quns,R.layout.activity_friend_qun_layout);
                 qunlistView.setAdapter(qunad);
             }

             @Override
             public void onError(Throwable ex, boolean isOnCallback) {

             }

             @Override
             public void onCancelled(CancelledException cex) {

             }

             @Override
             public void onFinished() {

             }
         });

     }
    //讨论组数据处理
    public void getTlzData(){
        RequestParams params=new RequestParams(HttpUtils.host4+"getqun");
        params.addQueryStringParameter("choice","4");
        params.addQueryStringParameter("userid",MainActivity.getUser().getUserid()+"");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if(result.equals("[]")){
                    Toast.makeText(getActivity(),"暂时没有讨论组-____-\"",Toast.LENGTH_SHORT).show();
                }
                Log.i("onError:succ",result);
                tlzs.clear();
                Log.i("tlzsData",result);
                progress4.setVisibility(View.GONE);
                Gson gson = new Gson();
                Type type = new TypeToken<List<TLZ>>() {
                }.getType();
                List<TLZ> newtlzs=gson.fromJson(result,type);
                tlzs.addAll(newtlzs);
                tlzad=new TlzAdapter(getActivity(),tlzs,R.layout.activity_friend_tlzs_layout);
                tlzlistview.setAdapter(tlzad);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i("onError:",ex+"");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }
    //左右图片点击方法
    public void leftclick(Friend_titlebar ft, final Integer i) {
        ft.setImgLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                vpFriend.setCurrentItem(i);
            }
        });
    }

    public void rightclick(Friend_titlebar ft, final Integer i) {
        ft.setImgRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                vpFriend.setCurrentItem(i);
            }
        });
    }

    //dp2xp
    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    //lisiview拖动隐藏bar
    public void hideBar() {
        mHeaderAnimator = ObjectAnimator.ofFloat(mHead_bar, "translationY", -mHead_bar.getHeight());
        mBottomAnimator = ObjectAnimator.ofFloat(mBottom_bar, "translationY", mBottom_bar.getHeight());
        llsearch = ObjectAnimator.ofFloat(llSreach, "translationY", -llSreach.getHeight());
        mHeaderAnimator.setDuration(500).start();
        mBottomAnimator.setDuration(400).start();
        llsearch.setDuration(500).start();
        mHeaderAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                isRunning = true;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                isRunning = false;
            }
        });
    }
    //list拖动显示bottom
    public void showBar() {
        mHeaderAnimator = ObjectAnimator.ofFloat(mHead_bar, "translationY", 0);
        mBottomAnimator = ObjectAnimator.ofFloat(mBottom_bar, "translationY", 0);
        llsearch = ObjectAnimator.ofFloat(llSreach, "translationY", 0);
        mHeaderAnimator.setDuration(300).start();
        mBottomAnimator.setDuration(400).start();
        llsearch.setDuration(300).start();

    }

    //加载圈的处理
    private void refreshData() {
        re_friend.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                flag = false;
                re_friend.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getFriendData();
                        re_friend.setRefreshing(false);
                    }
                }, 1000);
            }
        });
        re_qun.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                re_qun.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        getQunData();
                        re_qun.setRefreshing(false);
                    }
                }, 1000);
            }
        });
        re_tlz.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                re_tlz.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        getTlzData();
                        re_tlz.setRefreshing(false);
                    }
                }, 1000);
            }
        });
    }

    //会话列表链接容云
    private void Rong() {
        //        //异步回调刷新数据??有用??3天后:有用 >_<
        RequestParams requestParams1 = new RequestParams(HttpUtils.host4 + "getuser");
        requestParams1.addQueryStringParameter("choice",0+"");
        requestParams1.addQueryStringParameter("userid", +MainActivity.getUser().getUserid() + "");
        x.http().get(requestParams1, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.i("UUUSSSSIIIMMMGG", result);
                Gson gson = new Gson();
                Type type = new TypeToken<User>() {
                }.getType();
                user = gson.fromJson(result, type);
                RongIM.getInstance().refreshUserInfoCache(new UserInfo(MainActivity.getUser().getUserid() + "", user.getUsername(), Uri.parse(HttpUtils.hostpc + user.getUserimg())));
                //刷新所有好友的头像
                refreshImg();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }
    //刷新用户头像
    private void refreshImg() {
        for (Friend i : friends) {
            Log.i("fffffrrrrree", i.getFriendid() + "");
            RongIM.getInstance().refreshUserInfoCache(new UserInfo(i.getFriendid() + "", i.getName(), Uri.parse(HttpUtils.hostpc + i.getUser().getUserimg())));
        }
    }
    private  void getUserimg(){
        RequestParams params=new RequestParams(HttpUtils.host4+"getuser");
        params.addQueryStringParameter("choice",0+"");
        params.addQueryStringParameter("userid",MainActivity.getUser().getUserid()+"");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson=new Gson();
                Type type=new TypeToken<User>(){}.getType();
                User user=gson.fromJson(result,type);
                xUtilsImageUtils.display(userimg, HttpUtils.host4+"upload/"+user.getUserimg(),true);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    //是否有申请
    private  void ifpost(){
        RequestParams requestParams =new RequestParams(HttpUtils.host4+"friendservlet");
        requestParams.addQueryStringParameter("choice",3+"");
        requestParams.addQueryStringParameter("userid",MainActivity.getUser().getUserid()+"");
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (result.equals("[]")){
                    no_yuan.setVisibility(View.GONE);
                }else {
                    no_yuan.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    //url转bitmap
    public Bitmap getBitmap(String url) {
        Bitmap bm = null;
        try {
            URL iconUrl = new URL(url);
            URLConnection conn = iconUrl.openConnection();
            HttpURLConnection http = (HttpURLConnection) conn;

            int length = http.getContentLength();

            conn.connect();
            // 获得图像的字符流
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is, length);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();// 关闭流
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return bm;
    }
}


text:
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf
import org.apache.hadoop.conf.Configuration
import org.apache.spark.{ SparkContext, SparkConf }
import org.apache.spark.rdd.RDD
import org.bson.BSONObject
import com.mongodb.hadoop.{
  MongoInputFormat,
  MongoOutputFormat,
  BSONFileInputFormat,
  BSONFileOutputFormat
}
import com.mongodb.hadoop.util.MongoConfigUtil
import org.bson.types.ObjectId
import org.bson.{ BSONObject, BasicBSONObject }
import com.mongodb.hadoop.io.MongoUpdateWritable
import com.mongodb.BasicDBList

import scala.io.Source
import spray.json._
import DefaultJsonProtocol._

//val sc = SparkContext.getOrCreate

// val inputURI = "mongodb://localhost:27018/weather_db.historical"
// val outputURI = "mongodb://localhost:27018/weather_db.forecast"

object SysDist {
  var sc : SparkContext = null

  var hosts : List[String] = List(
    "localhost:27018",
    "localhost:27019",
    "localhost:27020"
  )

  var inputDB : String = "weather_db"
  var inputColl : String = "historical"

  var outputDB : String = "weather_db"
  var outputColl : String = "forecast"

  val baseURLFormat : String = "mongodb://%s/%s.%s?replicaSet=%s"

  var replicaSetName : String = "sysdist"
  var readPref : String = ""

  val inputConfig = new Configuration()
  val outputConfig = new Configuration()

  def readConfig() {
    val configsStr = Source.fromFile("config.json").getLines.mkString
    val jsonAst = configsStr.parseJson
    //println(jsonAst.prettyPrint)
    jsonAst.asJsObject.getFields("hosts", "database", "histColl", "foreColl", "replicaSet", "readPreference") match {
      case Seq(JsArray(_hosts), JsString(_db), JsString(_histColl), JsString(_foreColl), JsString(_replSet), JsString(_readPref)) => {
        hosts = _hosts.toList.map(_.convertTo[String])
        inputDB = _db
        outputDB = _db
        inputColl = _histColl
        outputColl = _foreColl
        replicaSetName = _replSet
        readPref = _readPref
      }
    }
  }

  def getURL(hostList: List[String], db: String, collection: String, replicaSet: String, readPref: String) : String = {
    var baseURLFormat = "mongodb://%s/%s.%s?replicaSet=%s"
    if (readPref != "") {
      baseURLFormat += "&readPreference=%s"
      println(">>>>> Using readPreference \"" + readPref + "\"")
      baseURLFormat.format(hostList.reduce(_+","+_), db, collection, replicaSet, readPref)
    }
    else {
      baseURLFormat.format(hostList.reduce(_+","+_), db, collection, replicaSet)
    }
  }

  def kelvinToCelsius(numberAsObj : Object) : Double = {
    val temp_kelvin =
      (if (numberAsObj.isInstanceOf[Double])
         Double.unbox(numberAsObj)
       else
         numberAsObj.asInstanceOf[Integer].toDouble)
    temp_kelvin - 273.15
  }

  def saveToMongo(rdd: RDD[(Null, MongoUpdateWritable)], config: Configuration) {
    rdd.saveAsNewAPIHadoopFile("", classOf[Any], classOf[Any], classOf[MongoOutputFormat[Any,Any]], config)
  }
  // Fix the foreign keys in the database. That means, add a hist_id field
  // to entries in 'forecast' with the id from 'historical'
  def fixFK() {
    val fixFKInputFore = new Configuration()

    fixFKInputFore.set("mongo.input.uri", getURL(hosts, "weather_db", "forecast", replicaSetName, readPref))
    val name_fore = sc.newAPIHadoopRDD(fixFKInputFore, classOf[MongoInputFormat], classOf[Object], classOf[BSONObject])
    val name_fore_sorted = name_fore.map(
      {
        case (id, obj) =>
          (obj.get("city").asInstanceOf[BSONObject].get("name").toString,
            // If this object already contains the foreign key, we will discard it later
            // (this should happen either for every single document or for none of them)
            if (obj.containsField("hist_id")) None else id.toString)
      }).sortByKey(true, 1)

    val fixFKInputHist = new Configuration()
    fixFKInputHist.set("mongo.input.uri", getURL(hosts, "weather_db", "historical", replicaSetName, readPref))
    val name_hist = sc.newAPIHadoopRDD(fixFKInputHist, classOf[MongoInputFormat], classOf[Object], classOf[BSONObject])
    val name_hist_sorted =
      name_hist.
        map(
          {
            case (id, obj) =>
              (obj.get("city").asInstanceOf[BSONObject].get("name").toString, id.toString)
          }).
          sortByKey(true, 1)
    // This gives us pairs in the form ( (city1, idHistorical), (city1, idForecast) )
    val zipped = name_hist_sorted.zip(name_fore_sorted)
    saveToMongo(
    zipped.
      filter({ case ((n1, id_h), (n2, id_f)) => id_f != None }).
      map(
        {
          case ((n1, id_h), (n2, id_f)) =>
            val query = new BasicBSONObject().append("_id", new ObjectId(id_f.toString))
            val update = new BasicBSONObject().append("$set", new BasicBSONObject("hist_id", new ObjectId(id_h)))
            val muw = new MongoUpdateWritable(query, update, false, false)
            (null, muw)
        })
    , outputConfig)
  }

  def calc_avg_temp_last5d() {
    val docs = sc.newAPIHadoopRDD(inputConfig, classOf[MongoInputFormat], classOf[Object], classOf[BSONObject])

    val update_avgtemp = docs.
      map(x =>
      (x._1.toString,
       x._2.get("list").asInstanceOf[BasicDBList].toArray().takeRight(5 * 8).
         map(y => {
           val temp = y.asInstanceOf[BSONObject].get("main").asInstanceOf[BSONObject].get("temp")
           kelvinToCelsius(temp)
         }))).
      map(x => (x._1, x._2.reduce(_+_)/x._2.length)).
      map(x => {
        val newProps = new BasicBSONObject().append("stats.avg_temp_last5d", x._2)
        val query = new BasicBSONObject().append("hist_id", new ObjectId(x._1))
        val update = new BasicBSONObject().append("$set", newProps)
        (null, new MongoUpdateWritable(query, update, false, false))
      })
      saveToMongo(update_avgtemp, outputConfig)
  }

  def calc_minmax_temp() {
    val docs = sc.newAPIHadoopRDD(inputConfig, classOf[MongoInputFormat], classOf[Object], classOf[BSONObject])

    val update_minmaxtemp = docs.
      map(x =>
        (x._1.toString,
         x._2.get("list").asInstanceOf[BasicDBList].toArray().
          map(y => {
            val temp = y.asInstanceOf[BSONObject].get("main").asInstanceOf[BSONObject].get("temp")
            kelvinToCelsius(temp)
          }))).
      map(x => (x._1, (x._2.max, x._2.min))).
      map(x => {
        val newProps = new BasicBSONObject()
        newProps.append("stats.max_temp", x._2._1)
        newProps.append("stats.min_temp", x._2._2)
        val query = new BasicBSONObject().append("hist_id", new ObjectId(x._1))
        val update = new BasicBSONObject().append("$set", newProps)
        (null, new MongoUpdateWritable(query, update, false, false))
      })

    saveToMongo(update_minmaxtemp, outputConfig)
  }

  def calc_minmax_rain() {
    val docs = sc.newAPIHadoopRDD(inputConfig, classOf[MongoInputFormat], classOf[Object], classOf[BSONObject])

    val update_minmaxrain = docs.
      map(x =>
        (x._1.toString,
         x._2.get("list").asInstanceOf[BasicDBList].toArray().
         map(y => {
          val rain = Option(y.asInstanceOf[BSONObject].get("rain").asInstanceOf[BSONObject])
          val rain_3h = Option(if (rain.isDefined) rain.get.get("3h") else null)
          val rain_db : Double = (
            if (!rain_3h.isDefined)
              0.0 : Double
            else if (rain_3h.get.isInstanceOf[Double])
              Double.unbox(rain_3h.get)
            else
              rain_3h.get.asInstanceOf[Integer].toDouble)
          val dt_txt = y.asInstanceOf[BSONObject].get("dt_txt").toString
          (dt_txt, rain_db)
        }).filter(x => x._2 > 0.0).groupBy(y => {
          val date = y._1
          date.substring(0, date.indexOf(' '))
        }).toList.map(x => {
          val date = x._1
          val list = x._2.asInstanceOf[Array[(String,Double)]].map(_._2)
          (date, list.sum)})
        )).filter(x => x._2.length > 0 ).map(x => {
        val _max = x._2.map(_._2).max
        val _min = x._2.map(_._2).min
        (x._1, (_max, _min)) } ).
      map(x => {
        val newProps = new BasicBSONObject()
        newProps.append("stats.max_rain", x._2._1)
        newProps.append("stats.min_rain", x._2._2)
        val query = new BasicBSONObject().append("hist_id", new ObjectId(x._1))
        val update = new BasicBSONObject().append("$set", newProps)
        (null, new MongoUpdateWritable(query, update, false, false))
      })

    saveToMongo(update_minmaxrain, outputConfig)

  }

  def calc_avg_wind_5d() {
    val docs = sc.newAPIHadoopRDD(inputConfig, classOf[MongoInputFormat], classOf[Object], classOf[BSONObject])

    val update_avgwind = docs.
      map(x =>
        (x._1.toString,
         x._2.get("list").asInstanceOf[BasicDBList].toArray().takeRight(8 * 5).
         map(y => {
          val wind = Option(y.asInstanceOf[BSONObject].get("wind").asInstanceOf[BSONObject])
          val wind_speed = Option(if (wind.isDefined) wind.get.get("speed") else null)
          val wind_db : Double = (
            if (!wind_speed.isDefined)
              0.0 : Double
            else if (wind_speed.get.isInstanceOf[Double])
              Double.unbox(wind_speed.get)
            else
              wind_speed.get.asInstanceOf[Integer].toDouble)
          wind_db
          }))).
      map(x =>
        (x._1, x._2.reduce(_ + _)/x._2.length)).
      map(x => {
        val newProp = new BasicBSONObject().append("stats.avg_rain_last5d", x._2)
        val query = new BasicBSONObject().append("hist_id", new ObjectId(x._1))
        val update = new BasicBSONObject().append("$set", newProp)
        (null, new MongoUpdateWritable(query, update, false, false))
      })

    saveToMongo(update_avgwind, outputConfig)
  }

  def calc_minmax_wind() {
    val docs = sc.newAPIHadoopRDD(inputConfig, classOf[MongoInputFormat], classOf[Object], classOf[BSONObject])

    val update_minmaxwind = docs.
      map(x =>
        (x._1.toString,
         x._2.get("list").asInstanceOf[BasicDBList].toArray().
         map(y => {
          val wind = Option(y.asInstanceOf[BSONObject].get("wind").asInstanceOf[BSONObject])
          val wind_speed = Option(if (wind.isDefined) wind.get.get("speed") else null)
          val wind_db : Double = (
            if (!wind_speed.isDefined)
              0.0 : Double
            else if (wind_speed.get.isInstanceOf[Double])
              Double.unbox(wind_speed.get)
            else
              wind_speed.get.asInstanceOf[Integer].toDouble)
          val dt_txt = y.asInstanceOf[BSONObject].get("dt_txt").toString
          (dt_txt, wind_db)
        }).filter(x => x._2 > 0.0).groupBy(y => {
          val date = y._1
          date.substring(0, date.indexOf(' '))
        }).toList.map(x => {
          val date = x._1
          val list = x._2.asInstanceOf[Array[(String,Double)]].map(_._2)
          (date, (if (list.length == 0) None else Some(list.max)) : Option[Double])})
        )).map(x => (x._1, x._2.filter(_._2.isDefined))).map(x => {
        val _max = x._2.map(_._2.get).max
        val _min = x._2.map(_._2.get).min
        (x._1, (_max, _min)) } ).
      map(x => {
        val newProps = new BasicBSONObject()
        newProps.append("stats.max_wind", x._2._1)
        newProps.append("stats.min_wind", x._2._2)
        val query = new BasicBSONObject().append("hist_id", new ObjectId(x._1))
        val update = new BasicBSONObject().append("$set", newProps)
        (null, new MongoUpdateWritable(query, update, false, false))
      })

    saveToMongo(update_minmaxwind, outputConfig)

  }

  def main(args : Array[String]) {
    println(">>>>> Starting...")
    readConfig
    val conf = new SparkConf().setAppName("SysDist")
    sc = new SparkContext(conf)

    var inputURI = String.format(baseURLFormat, hosts.reduce(_ +","+ _), inputDB, inputColl, replicaSetName)
    var outputURI = String.format(baseURLFormat, hosts.reduce(_ +","+ _), outputDB, outputColl, replicaSetName)

    if (args.length > 0) {
      readPref = args(0)
    }

    MongoConfigUtil.setOutputURI(outputConfig, outputURI)
    MongoConfigUtil.setInputURI(inputConfig, getURL(hosts, inputDB, inputColl, replicaSetName, readPref))

    val docs = sc.newAPIHadoopRDD(
      inputConfig,
      classOf[MongoInputFormat],
      classOf[Object],
      classOf[BSONObject]
    )

    println(">>>>> There are " + docs.count.toString + " documents in the base")

    println(">>>>> Fixing database's FKs...")
    fixFK
    println(">>>>> Fixed :)")

    println("Calculating temperature records...")
    calc_minmax_temp
    println("Finished...")

    println(">>>>> Calculating avg temp last 5 days")
    calc_avg_temp_last5d
    println(">>>>> Calculations finished")

        println(">>>>> Calculate rain records...")
    calc_minmax_rain
    println(">>>>> Finished...")

    println(">>>>> Calculate wind records...")
    calc_minmax_wind
    println(">>>>> Finished...")

    println(">>>>> Calculate wind avgs...")
    calc_avg_wind_5d
    println(">>>>> Finished...")

    //println(">>>>> Result : " + (sc.parallelize(List.range(1,10000)).sum).toString)

  }
}

redpajama_set_name: RedPajamaGithub


text:
import nltk.classify.util
import csv
from nltk.classify import NaiveBayesClassifier
import collections
import nltk.metrics
from nltk.tokenize import RegexpTokenizer
from nltk.corpus import movie_reviews
import random

def word_feats(words):
    return dict([(word, True) for word in words])

class PipeDialect(csv.Dialect):
    delimiter = "|"
    quotechar = None
    escapechar = None
    doublequote = None
    lineterminator = "\r\n"
    quoting = csv.QUOTE_NONE
    skipinitialspace = False

fneg = "data.neg.txt"
fpos = "data.pos.txt"
f = "data.txt"
fileNeg = open(fneg, "rb")
filePos = open(fpos, "rb")
file = open(f, "rb")

reader = csv.reader(file, PipeDialect())
readerNeg = csv.reader(fileNeg, PipeDialect())
readerPos = csv.reader(filePos, PipeDialect())

sentencesNeg = []
sentencesPos = []
wordsNeg = []
wordsPos = []

for row in readerNeg:
   sentencesNeg.append(row[2].lower())
for row in readerPos:
   sentencesPos.append(row[2].lower())

tokenizer = RegexpTokenizer(r'\w+')

for i in range(0, len(sentencesNeg)-1):
    wordsNeg.append(tokenizer.tokenize(sentencesNeg[i]))

for i in range(0, len(sentencesPos)-1):
    wordsPos.append(tokenizer.tokenize(sentencesPos[i]))

negfeats = [(word_feats(wordsNeg[i]), 'neg') for i in range(0, len(wordsNeg)-1)]
posfeats = [(word_feats(wordsPos[i]), 'pos') for i in range(0, len(wordsPos)-1)]

random.shuffle(negfeats)
random.shuffle(posfeats)

negcutoff = len(negfeats)*3/4
poscutoff = len(posfeats)*3/4

trainfeats = negfeats[:negcutoff] + posfeats[:poscutoff]
testfeats = negfeats[negcutoff:] + posfeats[poscutoff:]

print 'train on %d instances, test on %d instances' % (len(trainfeats), len(testfeats))

classifier = NaiveBayesClassifier.train(trainfeats)
refsets = collections.defaultdict(set)
testsets = collections.defaultdict(set)

for i, (feats, label) in enumerate(testfeats):
    refsets[label].add(i)
    observed = classifier.classify(feats)
    testsets[observed].add(i)

print 'accuracy:', nltk.classify.util.accuracy(classifier, testfeats)
print 'pos precision:', nltk.metrics.precision(refsets['pos'], testsets['pos'])
print 'pos recall:', nltk.metrics.recall(refsets['pos'], testsets['pos'])
print 'neg precision:', nltk.metrics.precision(refsets['neg'], testsets['neg'])
print 'neg recall:', nltk.metrics.recall(refsets['neg'], testsets['neg'])

classifier.show_most_informative_features()

file.close()
filePos.close()
fileNeg.close()


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">ButterKnifeSample</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="title_activity_list_view">ListViewActivity</string>

</resources>


text:
package com.fasterxml.jackson.databind.deser.jdk;

import java.util.*;

import com.fasterxml.jackson.annotation.JsonTypeInfo;

import com.fasterxml.jackson.core.type.TypeReference;

import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.testutil.NoCheckSubTypeValidator;

/**
 * Tests for special collection/map types via `java.util.Collections`
 */
public class JDKCollectionsDeserTest extends BaseMapTest
{
    static class XBean {
        public int x;

        public XBean() { }
        public XBean(int x) { this.x = x; }
    }

    /*
    /**********************************************************************
    /* Test methods
    /**********************************************************************
     */

    private final static ObjectMapper MAPPER = new ObjectMapper();

    // And then a round-trip test for singleton collections
    public void testSingletonCollections() throws Exception
    {
        final TypeReference<List<XBean>> xbeanListType = new TypeReference<List<XBean>>() { };

        String json = MAPPER.writeValueAsString(Collections.singleton(new XBean(3)));
        Collection<XBean> result = MAPPER.readValue(json, xbeanListType);
        assertNotNull(result);
        assertEquals(1, result.size());
        assertEquals(3, result.iterator().next().x);

        json = MAPPER.writeValueAsString(Collections.singletonList(new XBean(28)));
        result = MAPPER.readValue(json, xbeanListType);
        assertNotNull(result);
        assertEquals(1, result.size());
        assertEquals(28, result.iterator().next().x);
    }

    // [databind#1868]: Verify class name serialized as is
    public void testUnmodifiableSet() throws Exception
    {
        ObjectMapper mapper = jsonMapperBuilder()
                .activateDefaultTyping(NoCheckSubTypeValidator.instance,
                        ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY)
                .build();

        Set<String> theSet = Collections.unmodifiableSet(Collections.singleton("a"));
        String json = mapper.writeValueAsString(theSet);

        assertEquals("[\"java.util.Collections$UnmodifiableSet\",[\"a\"]]", json);

        // 04-Jan-2018, tatu: Alas, no way to make this actually work well, at this point.
         //   In theory could jiggle things back on deser, using one of two ways:
         //
         //   1) Do mapping to regular Set/List types (abstract type mapping): would work, but get rid of immutability
         //   2) Have actually separate deserializer OR ValueInstantiator
        /*
        Set<String> result = mapper.readValue(json, Set.class);
        assertNotNull(result);
        assertEquals(1, result.size());
        */
    }
}


text:
#include "cuncomp_profile.h"
#include <rohc/compressor.h>
#include <iterator>

namespace ROHC
{
    /**************************************************************************
     * Compression Profile
     **************************************************************************/

    CUncompressedProfile::CUncompressedProfile(Compressor* comp, unsigned int cid, const iphdr* ip)
    : CProfile(comp, cid, ip)
    , IRRequested(true)
    {

    }

    void
    CUncompressedProfile::Compress(const data_t &data, data_t &output)
    {
        size_t outputStart = output.size();

        bool largeCID = compressor->LargeCID();

        if (!largeCID && cid > 0)
        {
            output.push_back(CreateShortCID(cid));
        }

        if (IRRequested)
        {
            output.push_back(CreateIR(0));

            if (largeCID)
            {
                SDVLEncode(back_inserter(output), cid);
            }

            uint8_t lsbProfile = CUncompressedProfile::ProfileID() & 0xff;

            output.push_back(lsbProfile);

            uint8_t crc = CRC8(output.begin() + outputStart, output.end());
            output.push_back(crc);

            output.insert(output.end(), data.begin(), data.end());
            IRRequested = false;
        }
        else
        {
            const_data_iterator pos = data.begin();
            output.push_back(*pos++);
            if (largeCID)
            {
                SDVLEncode(back_inserter(output), cid);
            }
            output.insert(output.end(), pos, data.end());
        }
    }

} // ns ROHC


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#452446" >

    <ImageView
        android:id="@+id/imgLogo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/splash" />

</RelativeLayout>


text:
/**
 * @file   timer.c
 * @author Marti Bolivar <mbolivar@leaflabs.com>
 * @brief  New-style timer interface
 */

#include "timer.h"

/* Just like the corresponding DIER bits:
 * [0] = Update handler;
 * [1,2,3,4] = capture/compare 1,2,3,4 handlers, respectively;
 * [5] = COM;
 * [6] = TRG;
 * [7] = BRK. */
#define NR_ADV_HANDLERS                 8
/* Update, capture/compare 1,2,3,4; <junk>; trigger. */
#define NR_GEN_HANDLERS                 7
/* Update only. */
#define NR_BAS_HANDLERS                 1

static timer_dev timer1 = {
    .regs         = { .adv = TIMER1_BASE },
    .clk_id       = RCC_TIMER1,
    .type         = TIMER_ADVANCED,
    .handlers     = { [NR_ADV_HANDLERS - 1] = 0 },
};
/** Timer 1 device (advanced) */
timer_dev *TIMER1 = &timer1;

static timer_dev timer2 = {
    .regs         = { .gen = TIMER2_BASE },
    .clk_id       = RCC_TIMER2,
    .type         = TIMER_GENERAL,
    .handlers     = { [NR_GEN_HANDLERS - 1] = 0 },
};
/** Timer 2 device (general-purpose) */
timer_dev *TIMER2 = &timer2;

static timer_dev timer3 = {
    .regs         = { .gen = TIMER3_BASE },
    .clk_id       = RCC_TIMER3,
    .type         = TIMER_GENERAL,
    .handlers     = { [NR_GEN_HANDLERS - 1] = 0 },
};
/** Timer 3 device (general-purpose) */
timer_dev *TIMER3 = &timer3;

static timer_dev timer4 = {
    .regs         = { .gen = TIMER4_BASE },
    .clk_id       = RCC_TIMER4,
    .type         = TIMER_GENERAL,
    .handlers     = { [NR_GEN_HANDLERS - 1] = 0 },
};
/** Timer 4 device (general-purpose) */
timer_dev *TIMER4 = &timer4;

#ifdef STM32_HIGH_DENSITY
static timer_dev timer5 = {
    .regs         = { .gen = TIMER5_BASE },
    .clk_id       = RCC_TIMER5,
    .type         = TIMER_GENERAL,
    .handlers     = { [NR_GEN_HANDLERS - 1] = 0 },
};
/** Timer 5 device (general-purpose) */
timer_dev *TIMER5 = &timer5;

static timer_dev timer6 = {
    .regs         = { .bas = TIMER6_BASE },
    .clk_id       = RCC_TIMER6,
    .type         = TIMER_BASIC,
    .handlers     = { [NR_BAS_HANDLERS - 1] = 0 },
};
/** Timer 6 device (basic) */
timer_dev *TIMER6 = &timer6;

static timer_dev timer7 = {
    .regs         = { .bas = TIMER7_BASE },
    .clk_id       = RCC_TIMER7,
    .type         = TIMER_BASIC,
    .handlers     = { [NR_BAS_HANDLERS - 1] = 0 },
};
/** Timer 7 device (basic) */
timer_dev *TIMER7 = &timer7;

static timer_dev timer8 = {
    .regs         = { .adv = TIMER8_BASE },
    .clk_id       = RCC_TIMER8,
    .type         = TIMER_ADVANCED,
    .handlers     = { [NR_ADV_HANDLERS - 1] = 0 },
};
/** Timer 8 device (advanced) */
timer_dev *TIMER8 = &timer8;
#endif

/*
 * Convenience routines
 */

static void disable_channel(timer_dev *dev, uint8 channel);
static void pwm_mode(timer_dev *dev, uint8 channel);
static void output_compare_mode(timer_dev *dev, uint8 channel);

static inline void enable_irq(timer_dev *dev, uint8 interrupt);

/**
 * Initialize a timer, and reset its register map.
 * @param dev Timer to initialize
 */
void timer_init(timer_dev *dev) {
    rcc_clk_enable(dev->clk_id);
    rcc_reset_dev(dev->clk_id);
}

/**
 * @brief Disable a timer.
 *
 * The timer will stop counting, all DMA requests and interrupts will
 * be disabled, and no state changes will be output.
 *
 * @param dev Timer to disable.
 */
void timer_disable(timer_dev *dev) {
    (dev->regs).bas->CR1 = 0;
    (dev->regs).bas->DIER = 0;
    switch (dev->type) {
    case TIMER_ADVANCED:        /* fall-through */
    case TIMER_GENERAL:
        (dev->regs).gen->CCER = 0;
        break;
    case TIMER_BASIC:
        break;
    }
}

/**
 * Sets the mode of an individual timer channel.
 *
 * Note that not all timers can be configured in every mode.  For
 * example, basic timers cannot be configured to output compare mode.
 * Be sure to use a timer which is appropriate for the mode you want.
 *
 * @param dev Timer whose channel mode to set
 * @param channel Relevant channel
 * @param mode New timer mode for channel
 */
void timer_set_mode(timer_dev *dev, uint8 channel, timer_mode mode) {
    ASSERT_FAULT(channel > 0 && channel <= 4);

    /* TODO decide about the basic timers */
    ASSERT(dev->type != TIMER_BASIC);
    if (dev->type == TIMER_BASIC)
        return;

    switch (mode) {
    case TIMER_DISABLED:
        disable_channel(dev, channel);
        break;
    case TIMER_PWM:
        pwm_mode(dev, channel);
        break;
    case TIMER_OUTPUT_COMPARE:
        output_compare_mode(dev, channel);
        break;
    }
}

/**
 * @brief Call a function on timer devices.
 * @param fn Function to call on each timer device.
 */
void timer_foreach(void (*fn)(timer_dev*)) {
    fn(TIMER1);
    fn(TIMER2);
    fn(TIMER3);
    fn(TIMER4);
#ifdef STM32_HIGH_DENSITY
    fn(TIMER5);
    fn(TIMER6);
    fn(TIMER7);
    fn(TIMER8);
#endif
}

/**
 * @brief Attach a timer interrupt.
 * @param dev Timer device
 * @param interrupt Interrupt number to attach to; this may be any
 *                  timer_interrupt_id or timer_channel value appropriate
 *                  for the timer.
 * @param handler Handler to attach to the given interrupt.
 * @see timer_interrupt_id
 * @see timer_channel
 */
void timer_attach_interrupt(timer_dev *dev,
                            uint8 interrupt,
                            voidFuncPtr handler) {
    dev->handlers[interrupt] = handler;
    timer_enable_irq(dev, interrupt);
    enable_irq(dev, interrupt);
}

/**
 * @brief Detach a timer interrupt.
 * @param dev Timer device
 * @param interrupt Interrupt number to detach; this may be any
 *                  timer_interrupt_id or timer_channel value appropriate
 *                  for the timer.
 * @see timer_interrupt_id
 * @see timer_channel
 */
void timer_detach_interrupt(timer_dev *dev, uint8 interrupt) {
    timer_disable_irq(dev, interrupt);
    dev->handlers[interrupt] = NULL;
}

/*
 * IRQ handlers
 */

static inline void dispatch_adv_brk(timer_dev *dev);
static inline void dispatch_adv_up(timer_dev *dev);
static inline void dispatch_adv_trg_com(timer_dev *dev);
static inline void dispatch_adv_cc(timer_dev *dev);
static inline void dispatch_general(timer_dev *dev);
static inline void dispatch_basic(timer_dev *dev);

void __irq_tim1_brk(void) {
    dispatch_adv_brk(TIMER1);
}

void __irq_tim1_up(void) {
    dispatch_adv_up(TIMER1);
}

void __irq_tim1_trg_com(void) {
    dispatch_adv_trg_com(TIMER1);
}

void __irq_tim1_cc(void) {
    dispatch_adv_cc(TIMER1);
}

void __irq_tim2(void) {
    dispatch_general(TIMER2);
}

void __irq_tim3(void) {
    dispatch_general(TIMER3);
}

void __irq_tim4(void) {
    dispatch_general(TIMER4);
}

#if defined(STM32_HIGH_DENSITY) || defined(STM32_XL_DENSITY)

void __irq_tim5(void) {
    dispatch_general(TIMER5);
}

void __irq_tim6(void) {
    dispatch_basic(TIMER6);
}

void __irq_tim7(void) {
    dispatch_basic(TIMER7);
}

void __irq_tim8_brk(void) {
    dispatch_adv_brk(TIMER8);
}

void __irq_tim8_up(void) {
    dispatch_adv_up(TIMER8);
}

void __irq_tim8_trg_com(void) {
    dispatch_adv_trg_com(TIMER8);
}

void __irq_tim8_cc(void) {
    dispatch_adv_cc(TIMER8);
}
#endif

/* Note: the following dispatch routines make use of the fact that
 * DIER interrupt enable bits and SR interrupt flags have common bit
 * positions.  Thus, ANDing DIER and SR lets us check if an interrupt
 * is enabled and if it has occurred simultaneously.
 */

/* A special-case dispatch routine for single-interrupt NVIC lines.
 * This function assumes that the interrupt corresponding to `iid' has
 * in fact occurred (i.e., it doesn't check DIER & SR). */
static inline void dispatch_single_irq(timer_dev *dev,
                                       timer_interrupt_id iid,
                                       uint32 irq_mask) {
    timer_bas_reg_map *regs = (dev->regs).bas;
    void (*handler)(void) = dev->handlers[iid];
    if (handler) {
        handler();
        regs->SR &= ~irq_mask;
    }
}

/* For dispatch routines which service multiple interrupts. */
#define handle_irq(dier_sr, irq_mask, handlers, iid, handled_irq) do {  \
        if ((dier_sr) & (irq_mask)) {                                   \
            void (*__handler)(void) = (handlers)[iid];                  \
            if (__handler) {                                            \
                __handler();                                            \
                handled_irq |= (irq_mask);                              \
            }                                                           \
        }                                                               \
    } while (0)

static inline void dispatch_adv_brk(timer_dev *dev) {
    dispatch_single_irq(dev, TIMER_BREAK_INTERRUPT, TIMER_SR_BIF);
}

static inline void dispatch_adv_up(timer_dev *dev) {
    dispatch_single_irq(dev, TIMER_UPDATE_INTERRUPT, TIMER_SR_UIF);
}

static inline void dispatch_adv_trg_com(timer_dev *dev) {
    timer_adv_reg_map *regs = (dev->regs).adv;
    uint32 dsr = regs->DIER & regs->SR;
    void (**hs)(void) = dev->handlers;
    uint32 handled = 0; /* Logical OR of SR interrupt flags we end up
                         * handling.  We clear these.  User handlers
                         * must clear overcapture flags, to avoid
                         * wasting time in output mode. */

    handle_irq(dsr, TIMER_SR_TIF,   hs, TIMER_TRG_INTERRUPT, handled);
    handle_irq(dsr, TIMER_SR_COMIF, hs, TIMER_COM_INTERRUPT, handled);

    regs->SR &= ~handled;
}

static inline void dispatch_adv_cc(timer_dev *dev) {
    timer_adv_reg_map *regs = (dev->regs).adv;
    uint32 dsr = regs->DIER & regs->SR;
    void (**hs)(void) = dev->handlers;
    uint32 handled = 0;

    handle_irq(dsr, TIMER_SR_CC4IF, hs, TIMER_CC4_INTERRUPT, handled);
    handle_irq(dsr, TIMER_SR_CC3IF, hs, TIMER_CC3_INTERRUPT, handled);
    handle_irq(dsr, TIMER_SR_CC2IF, hs, TIMER_CC2_INTERRUPT, handled);
    handle_irq(dsr, TIMER_SR_CC1IF, hs, TIMER_CC1_INTERRUPT, handled);

    regs->SR &= ~handled;
}

static inline void dispatch_general(timer_dev *dev) {
    timer_gen_reg_map *regs = (dev->regs).gen;
    uint32 dsr = regs->DIER & regs->SR;
    void (**hs)(void) = dev->handlers;
    uint32 handled = 0;

    handle_irq(dsr, TIMER_SR_TIF,   hs, TIMER_TRG_INTERRUPT,    handled);
    handle_irq(dsr, TIMER_SR_CC4IF, hs, TIMER_CC4_INTERRUPT,    handled);
    handle_irq(dsr, TIMER_SR_CC3IF, hs, TIMER_CC3_INTERRUPT,    handled);
    handle_irq(dsr, TIMER_SR_CC2IF, hs, TIMER_CC2_INTERRUPT,    handled);
    handle_irq(dsr, TIMER_SR_CC1IF, hs, TIMER_CC1_INTERRUPT,    handled);
    handle_irq(dsr, TIMER_SR_UIF,   hs, TIMER_UPDATE_INTERRUPT, handled);

    regs->SR &= ~handled;
}

static inline void dispatch_basic(timer_dev *dev) {
    dispatch_single_irq(dev, TIMER_UPDATE_INTERRUPT, TIMER_SR_UIF);
}

/*
 * Utilities
 */

static void disable_channel(timer_dev *dev, uint8 channel) {
    timer_detach_interrupt(dev, channel);
    timer_cc_disable(dev, channel);
}

static void pwm_mode(timer_dev *dev, uint8 channel) {
    timer_disable_irq(dev, channel);
    timer_oc_set_mode(dev, channel, TIMER_OC_MODE_PWM_1, TIMER_OC_PE);
    timer_cc_enable(dev, channel);
}

static void output_compare_mode(timer_dev *dev, uint8 channel) {
    timer_oc_set_mode(dev, channel, TIMER_OC_MODE_ACTIVE_ON_MATCH, 0);
    timer_cc_enable(dev, channel);
}

static void enable_advanced_irq(timer_dev *dev, timer_interrupt_id id);
static void enable_nonmuxed_irq(timer_dev *dev);

static inline void enable_irq(timer_dev *dev, timer_interrupt_id iid) {
    if (dev->type == TIMER_ADVANCED) {
        enable_advanced_irq(dev, iid);
    } else {
        enable_nonmuxed_irq(dev);
    }
}

static void enable_advanced_irq(timer_dev *dev, timer_interrupt_id id) {
    uint8 is_timer1 = dev->clk_id == RCC_TIMER1;

    switch (id) {
    case TIMER_UPDATE_INTERRUPT:
        nvic_irq_enable(is_timer1 ? NVIC_TIMER1_UP : NVIC_TIMER8_UP);
        break;
    case TIMER_CC1_INTERRUPT:
    case TIMER_CC2_INTERRUPT:
    case TIMER_CC3_INTERRUPT:
    case TIMER_CC4_INTERRUPT:
        nvic_irq_enable(is_timer1 ? NVIC_TIMER1_CC : NVIC_TIMER8_CC);
        break;
    case TIMER_COM_INTERRUPT:
    case TIMER_TRG_INTERRUPT:
        nvic_irq_enable(is_timer1 ? NVIC_TIMER1_TRG_COM : NVIC_TIMER8_TRG_COM);
        break;
    case TIMER_BREAK_INTERRUPT:
        nvic_irq_enable(is_timer1 ? NVIC_TIMER1_BRK : NVIC_TIMER8_BRK);
        break;
    }
}

static void enable_nonmuxed_irq(timer_dev *dev) {
    switch (dev->clk_id) {
    case RCC_TIMER2:
        nvic_irq_enable(NVIC_TIMER2);
        break;
    case RCC_TIMER3:
        nvic_irq_enable(NVIC_TIMER3);
        break;
    case RCC_TIMER4:
        nvic_irq_enable(NVIC_TIMER4);
        break;
#ifdef STM32_HIGH_DENSITY
    case RCC_TIMER5:
        nvic_irq_enable(NVIC_TIMER5);
        break;
    case RCC_TIMER6:
        nvic_irq_enable(NVIC_TIMER6);
        break;
    case RCC_TIMER7:
        nvic_irq_enable(NVIC_TIMER7);
        break;
#endif
    default:
        ASSERT_FAULT(0);
        break;
    }
}


text:
class IPymlCache
{
public:
	virtual const IPymlFile* get(std::string filename) = 0;
};


text:
using System;
using System.Collections.Generic;
using System.Text;
using wojilu.Web.Mvc;
using wojilu.Apps.Content.Interface;
using wojilu.Apps.Content.Domain;
using System.Collections;
using wojilu.Members.Users.Domain;
using wojilu.Apps.Content.Service;
using wojilu.Web.Controller.Content.Utils;

namespace wojilu.Web.Controller.Content.Binder {

    public class UserFacesBinderController : ControllerBase, ISectionBinder {

        public IContentCustomTemplateService ctService { get; set; }

        public UserFacesBinderController() {
            ctService = new ContentCustomTemplateService();
        }

        public void Bind( ContentSection section, IList serviceData ) {

            TemplateUtil.loadTemplate( this, section, ctService );

            IBlock block = base.getBlock( "list" );

            foreach (User user in serviceData) {

                block.Set( "user.Name", user.Name );
                block.Set( "user.Face", user.PicSmall );
                block.Set( "user.Link", Link.ToMember( user ) );

                block.Bind( "user", user );

                block.Next();
            }

        }

    }

}


text:
package com.ciq.qless.java.test.lua;

import static org.junit.Assert.assertEquals;

import org.junit.Ignore;
import org.junit.Test;

public class LuaScriptTest extends LuaScriptBaseTest {
	private final String unpauseScript = "-- This script takes the name of the queue(s) and removes it"
			+ "-- from the ql:paused_queues set."
			+ "--"
			+ "-- Args: The list of queues to pause."
			+ "if #KEYS > 0 then error('Pause(): No Keys should be provided') end"
			+ "if #ARGV < 1 then error('Pause(): Must provide at least one queue to pause') end"
			+ "local key = 'ql:paused_queues'"
			+ "redis.call('srem', key, unpack(ARGV));";

	@Test
	@Ignore
	public void luaScriptLoad() {
		String contents = _luaScript.getScript(this.scriptName());
		assertEquals(contents, unpauseScript);
	}

	@Override
	protected String scriptName() {
		return "unpause.lua";
	}

	@Override
	protected String scriptErrorName() {
		return "Unpause";
	}
}


text:
import {
  inject,
  addProviders
} from '@angular/core/testing';

import {HeroesService} from './heroes.service';
import { HEROES } from './heroes.mock';

describe('HeroService', () => {

  beforeEach(function() {
    addProviders([HeroesService]);
  });

  it('should have name property set', inject( [HeroesService], (api: HeroesService) => {
    api.getHeroes().then((hs) => {
      expect(hs).toBe(HEROES);
    });
  }))
});


text:
void sdl::DispatchEvent(const SDL_Event &event, IInputEventAcceptor &acceptor)
{
    switch (event.type)
    {
    case SDL_KEYDOWN:
        acceptor.OnKeyDown(event.key);
        break;
    case SDL_KEYUP:
        acceptor.OnKeyUp(event.key);
        break;
    case SDL_MOUSEBUTTONDOWN:
        acceptor.OnMouseDown(event.button);
        break;
    case SDL_MOUSEBUTTONUP:
        acceptor.OnMouseUp(event.button);
        break;
    case SDL_MOUSEMOTION:
        acceptor.OnMouseMotion(event.motion);
        break;
    case SDL_MOUSEWHEEL:
        acceptor.OnMouseWheel(event.wheel);
        break;
    }
}


text:
class ConfigurationOption
  include DataMapper::Resource

  property :configuration_id,  Integer, :key => true
  property :configurable_id,   Integer, :key => true
  property :value,             DataMapper::Types::Option, :required => true

  belongs_to :configuration

  def name
    self.configuration.name
  end
end


text:
#ifndef OCFS2_ALLOC_H
#define OCFS2_ALLOC_H

/*
 * For xattr tree leaf, we limit the leaf byte size to be 64K.
 */
#define OCFS2_MAX_XATTR_TREE_LEAF_SIZE 65536

/*
 * ocfs2_extent_tree and ocfs2_extent_tree_operations are used to abstract
 * the b-tree operations in ocfs2. Now all the b-tree operations are not
 * limited to ocfs2_dinode only. Any data which need to allocate clusters
 * to store can use b-tree. And it only needs to implement its ocfs2_extent_tree
 * and operation.
 *
 * ocfs2_extent_tree becomes the first-class object for extent tree
 * manipulation.  Callers of the alloc.c code need to fill it via one of
 * the ocfs2_init_*_extent_tree() operations below.
 *
 * ocfs2_extent_tree contains info for the root of the b-tree, it must have a
 * root ocfs2_extent_list and a root_bh so that they can be used in the b-tree
 * functions.  It needs the ocfs2_caching_info structure associated with
 * I/O on the tree.  With metadata ecc, we now call different journal_access
 * functions for each type of metadata, so it must have the
 * root_journal_access function.
 * ocfs2_extent_tree_operations abstract the normal operations we do for
 * the root of extent b-tree.
 */
struct ocfs2_extent_tree_operations;
struct ocfs2_extent_tree {
	struct ocfs2_extent_tree_operations	*et_ops;
	struct buffer_head			*et_root_bh;
	struct ocfs2_extent_list		*et_root_el;
	struct ocfs2_caching_info		*et_ci;
	ocfs2_journal_access_func		et_root_journal_access;
	void					*et_object;
	unsigned int				et_max_leaf_clusters;
};

/*
 * ocfs2_init_*_extent_tree() will fill an ocfs2_extent_tree from the
 * specified object buffer.
 */
void ocfs2_init_dinode_extent_tree(struct ocfs2_extent_tree *et,
				   struct ocfs2_caching_info *ci,
				   struct buffer_head *bh);
void ocfs2_init_xattr_tree_extent_tree(struct ocfs2_extent_tree *et,
				       struct ocfs2_caching_info *ci,
				       struct buffer_head *bh);
struct ocfs2_xattr_value_buf;
void ocfs2_init_xattr_value_extent_tree(struct ocfs2_extent_tree *et,
					struct ocfs2_caching_info *ci,
					struct ocfs2_xattr_value_buf *vb);
void ocfs2_init_dx_root_extent_tree(struct ocfs2_extent_tree *et,
				    struct ocfs2_caching_info *ci,
				    struct buffer_head *bh);
void ocfs2_init_refcount_extent_tree(struct ocfs2_extent_tree *et,
				     struct ocfs2_caching_info *ci,
				     struct buffer_head *bh);

/*
 * Read an extent block into *bh.  If *bh is NULL, a bh will be
 * allocated.  This is a cached read.  The extent block will be validated
 * with ocfs2_validate_extent_block().
 */
int ocfs2_read_extent_block(struct ocfs2_caching_info *ci, u64 eb_blkno,
			    struct buffer_head **bh);

struct ocfs2_alloc_context;
int ocfs2_insert_extent(handle_t *handle,
			struct ocfs2_extent_tree *et,
			u32 cpos,
			u64 start_blk,
			u32 new_clusters,
			u8 flags,
			struct ocfs2_alloc_context *meta_ac);

enum ocfs2_alloc_restarted {
	RESTART_NONE = 0,
	RESTART_TRANS,
	RESTART_META
};
int ocfs2_add_clusters_in_btree(handle_t *handle,
				struct ocfs2_extent_tree *et,
				u32 *logical_offset,
				u32 clusters_to_add,
				int mark_unwritten,
				struct ocfs2_alloc_context *data_ac,
				struct ocfs2_alloc_context *meta_ac,
				enum ocfs2_alloc_restarted *reason_ret);
struct ocfs2_cached_dealloc_ctxt;
struct ocfs2_path;
int ocfs2_split_extent(handle_t *handle,
		       struct ocfs2_extent_tree *et,
		       struct ocfs2_path *path,
		       int split_index,
		       struct ocfs2_extent_rec *split_rec,
		       struct ocfs2_alloc_context *meta_ac,
		       struct ocfs2_cached_dealloc_ctxt *dealloc);
int ocfs2_mark_extent_written(struct inode *inode,
			      struct ocfs2_extent_tree *et,
			      handle_t *handle, u32 cpos, u32 len, u32 phys,
			      struct ocfs2_alloc_context *meta_ac,
			      struct ocfs2_cached_dealloc_ctxt *dealloc);
int ocfs2_change_extent_flag(handle_t *handle,
			     struct ocfs2_extent_tree *et,
			     u32 cpos, u32 len, u32 phys,
			     struct ocfs2_alloc_context *meta_ac,
			     struct ocfs2_cached_dealloc_ctxt *dealloc,
			     int new_flags, int clear_flags);
int ocfs2_remove_extent(handle_t *handle, struct ocfs2_extent_tree *et,
			u32 cpos, u32 len,
			struct ocfs2_alloc_context *meta_ac,
			struct ocfs2_cached_dealloc_ctxt *dealloc);
int ocfs2_remove_btree_range(struct inode *inode,
			     struct ocfs2_extent_tree *et,
			     u32 cpos, u32 phys_cpos, u32 len, int flags,
			     struct ocfs2_cached_dealloc_ctxt *dealloc,
			     u64 refcount_loc, bool refcount_tree_locked);

int ocfs2_num_free_extents(struct ocfs2_super *osb,
			   struct ocfs2_extent_tree *et);

/*
 * how many new metadata chunks would an allocation need at maximum?
 *
 * Please note that the caller must make sure that root_el is the root
 * of extent tree. So for an inode, it should be &fe->id2.i_list. Otherwise
 * the result may be wrong.
 */
static inline int ocfs2_extend_meta_needed(struct ocfs2_extent_list *root_el)
{
	/*
	 * Rather than do all the work of determining how much we need
	 * (involves a ton of reads and locks), just ask for the
	 * maximal limit.  That's a tree depth shift.  So, one block for
	 * level of the tree (current l_tree_depth), one block for the
	 * new tree_depth==0 extent_block, and one block at the new
	 * top-of-the tree.
	 */
	return le16_to_cpu(root_el->l_tree_depth) + 2;
}

void ocfs2_dinode_new_extent_list(struct inode *inode, struct ocfs2_dinode *di);
void ocfs2_set_inode_data_inline(struct inode *inode, struct ocfs2_dinode *di);
int ocfs2_convert_inline_data_to_extents(struct inode *inode,
					 struct buffer_head *di_bh);

int ocfs2_truncate_log_init(struct ocfs2_super *osb);
void ocfs2_truncate_log_shutdown(struct ocfs2_super *osb);
void ocfs2_schedule_truncate_log_flush(struct ocfs2_super *osb,
				       int cancel);
int ocfs2_flush_truncate_log(struct ocfs2_super *osb);
int ocfs2_begin_truncate_log_recovery(struct ocfs2_super *osb,
				      int slot_num,
				      struct ocfs2_dinode **tl_copy);
int ocfs2_complete_truncate_log_recovery(struct ocfs2_super *osb,
					 struct ocfs2_dinode *tl_copy);
int ocfs2_truncate_log_needs_flush(struct ocfs2_super *osb);
int ocfs2_truncate_log_append(struct ocfs2_super *osb,
			      handle_t *handle,
			      u64 start_blk,
			      unsigned int num_clusters);
int __ocfs2_flush_truncate_log(struct ocfs2_super *osb);

/*
 * Process local structure which describes the block unlinks done
 * during an operation. This is populated via
 * ocfs2_cache_block_dealloc().
 *
 * ocfs2_run_deallocs() should be called after the potentially
 * de-allocating routines. No journal handles should be open, and most
 * locks should have been dropped.
 */
struct ocfs2_cached_dealloc_ctxt {
	struct ocfs2_per_slot_free_list		*c_first_suballocator;
	struct ocfs2_cached_block_free 		*c_global_allocator;
};
static inline void ocfs2_init_dealloc_ctxt(struct ocfs2_cached_dealloc_ctxt *c)
{
	c->c_first_suballocator = NULL;
	c->c_global_allocator = NULL;
}
int ocfs2_cache_cluster_dealloc(struct ocfs2_cached_dealloc_ctxt *ctxt,
				u64 blkno, unsigned int bit);
int ocfs2_cache_block_dealloc(struct ocfs2_cached_dealloc_ctxt *ctxt,
			      int type, int slot, u64 suballoc, u64 blkno,
			      unsigned int bit);
static inline int ocfs2_dealloc_has_cluster(struct ocfs2_cached_dealloc_ctxt *c)
{
	return c->c_global_allocator != NULL;
}
int ocfs2_run_deallocs(struct ocfs2_super *osb,
		       struct ocfs2_cached_dealloc_ctxt *ctxt);

struct ocfs2_truncate_context {
	struct ocfs2_cached_dealloc_ctxt tc_dealloc;
	int tc_ext_alloc_locked; /* is it cluster locked? */
	/* these get destroyed once it's passed to ocfs2_commit_truncate. */
	struct buffer_head *tc_last_eb_bh;
};

int ocfs2_zero_range_for_truncate(struct inode *inode, handle_t *handle,
				  u64 range_start, u64 range_end);
int ocfs2_commit_truncate(struct ocfs2_super *osb,
			  struct inode *inode,
			  struct buffer_head *di_bh);
int ocfs2_truncate_inline(struct inode *inode, struct buffer_head *di_bh,
			  unsigned int start, unsigned int end, int trunc);

int ocfs2_find_leaf(struct ocfs2_caching_info *ci,
		    struct ocfs2_extent_list *root_el, u32 cpos,
		    struct buffer_head **leaf_bh);
int ocfs2_search_extent_list(struct ocfs2_extent_list *el, u32 v_cluster);

int ocfs2_trim_fs(struct super_block *sb, struct fstrim_range *range);
/*
 * Helper function to look at the # of clusters in an extent record.
 */
static inline unsigned int ocfs2_rec_clusters(struct ocfs2_extent_list *el,
					      struct ocfs2_extent_rec *rec)
{
	/*
	 * Cluster count in extent records is slightly different
	 * between interior nodes and leaf nodes. This is to support
	 * unwritten extents which need a flags field in leaf node
	 * records, thus shrinking the available space for a clusters
	 * field.
	 */
	if (el->l_tree_depth)
		return le32_to_cpu(rec->e_int_clusters);
	else
		return le16_to_cpu(rec->e_leaf_clusters);
}

/*
 * This is only valid for leaf nodes, which are the only ones that can
 * have empty extents anyway.
 */
static inline int ocfs2_is_empty_extent(struct ocfs2_extent_rec *rec)
{
	return !rec->e_leaf_clusters;
}

int ocfs2_grab_pages(struct inode *inode, loff_t start, loff_t end,
		     struct page **pages, int *num);
void ocfs2_map_and_dirty_page(struct inode *inode, handle_t *handle,
			      unsigned int from, unsigned int to,
			      struct page *page, int zero, u64 *phys);
/*
 * Structures which describe a path through a btree, and functions to
 * manipulate them.
 *
 * The idea here is to be as generic as possible with the tree
 * manipulation code.
 */
struct ocfs2_path_item {
	struct buffer_head		*bh;
	struct ocfs2_extent_list	*el;
};

#define OCFS2_MAX_PATH_DEPTH	5

struct ocfs2_path {
	int				p_tree_depth;
	ocfs2_journal_access_func	p_root_access;
	struct ocfs2_path_item		p_node[OCFS2_MAX_PATH_DEPTH];
};

#define path_root_bh(_path) ((_path)->p_node[0].bh)
#define path_root_el(_path) ((_path)->p_node[0].el)
#define path_root_access(_path)((_path)->p_root_access)
#define path_leaf_bh(_path) ((_path)->p_node[(_path)->p_tree_depth].bh)
#define path_leaf_el(_path) ((_path)->p_node[(_path)->p_tree_depth].el)
#define path_num_items(_path) ((_path)->p_tree_depth + 1)

void ocfs2_reinit_path(struct ocfs2_path *path, int keep_root);
void ocfs2_free_path(struct ocfs2_path *path);
int ocfs2_find_path(struct ocfs2_caching_info *ci,
		    struct ocfs2_path *path,
		    u32 cpos);
struct ocfs2_path *ocfs2_new_path_from_path(struct ocfs2_path *path);
struct ocfs2_path *ocfs2_new_path_from_et(struct ocfs2_extent_tree *et);
int ocfs2_path_bh_journal_access(handle_t *handle,
				 struct ocfs2_caching_info *ci,
				 struct ocfs2_path *path,
				 int idx);
int ocfs2_journal_access_path(struct ocfs2_caching_info *ci,
			      handle_t *handle,
			      struct ocfs2_path *path);
int ocfs2_find_cpos_for_right_leaf(struct super_block *sb,
				   struct ocfs2_path *path, u32 *cpos);
int ocfs2_find_cpos_for_left_leaf(struct super_block *sb,
				  struct ocfs2_path *path, u32 *cpos);
int ocfs2_find_subtree_root(struct ocfs2_extent_tree *et,
			    struct ocfs2_path *left,
			    struct ocfs2_path *right);
#endif /* OCFS2_ALLOC_H */


text:
local table                     = require "hp/lang/table"
local class                     = require "hp/lang/class"
local DisplayObject             = require "hp/display/DisplayObject"
local TextureDrawable           = require "hp/display/TextureDrawable"

-- class
local M                         = class(DisplayObject, TextureDrawable)

----------------------------------------------------------------
-- The constructor.
-- @param params (option)Parameter is set to Object.<br>
----------------------------------------------------------------
function M:init(params)
    DisplayObject.init(self)

    params = params or {}
    params = type(params) == "string" and {texture = params} or params

    local deck = MOAIGfxQuadDeck2D.new()
    local grid = MOAIGrid.new ()

    self:setDeck(deck)
    self:setGrid(grid)
    self.deck = deck
    self.grid = grid

    self:copyParams(params)
end

--------------------------------------------------------------------------------
-- Sets the data to generate a sheet of tile form.
-- @param tileWidth Width of the tile.
-- @param tileHeight Height of the tile.
-- @param tileX number of tiles in the x-direction.
-- @param tileY number of tiles in the y-direction.
-- @param spacing (option)Space size of each tile.
-- @param margin (option)Margin of tile.
--------------------------------------------------------------------------------
function M:setMapSheets(tileWidth, tileHeight, tileX, tileY, spacing, margin)
    spacing = spacing or 0
    margin = margin or 0
    local sheets = {}
    for y = 1, tileY do
        for x = 1, tileX do
            local sx = (x - 1) * (tileWidth + spacing) + margin
            local sy = (y - 1) * (tileHeight + spacing) + margin
            table.insert(sheets, {x = sx, y = sy, width = tileWidth, height = tileHeight})
        end
    end
    self:setSheets(sheets)
end

--------------------------------------------------------------------------------
-- Sets the data sheet.
-- @param sheets Data sheet.
--------------------------------------------------------------------------------
function M:setSheets(sheets)
    assert(self.texture)

    local tw, th = self.texture:getSize()
    self.deck:reserve(#sheets)
    for i, sheet in ipairs(sheets) do
        local xMin, yMin = sheet.x, sheet.y
        local xMax = sheet.x + sheet.width
        local yMax = sheet.y + sheet.height
        self.deck:setUVRect(i, xMin / tw, yMin / th, xMax / tw, yMax / th)
    end
end

--------------------------------------------------------------------------------
-- Set the map size.
-- @param mapWidth Height of the map.
-- @param mapHeight Height of the map.
-- @param tileWidth Width of the tile.
-- @param tileHeight Height of the tile.
--------------------------------------------------------------------------------
function M:setMapSize(mapWidth, mapHeight, tileWidth, tileHeight)
    self.grid:setSize(mapWidth, mapHeight, tileWidth, tileHeight)
end

--------------------------------------------------------------------------------
-- Set the map data.
-- @param rows Multiple rows of data.
--------------------------------------------------------------------------------
function M:setRows(rows)
    for i, row in ipairs(rows) do
        self:setRow(i, table.unpack(row))
    end
end

--------------------------------------------------------------------------------
-- Set the map data.
-- @param ... rows of data.
--------------------------------------------------------------------------------
function M:setRow(...)
    self.grid:setRow(...)
end

--------------------------------------------------------------------------------
-- Set the map value.
-- @param x x.
-- @param y y.
-- @param value value.
--------------------------------------------------------------------------------
function M:setTile(x, y, value)
    self.grid:setTile(x, y, value)
end

--------------------------------------------------------------------------------
-- Set the repeat flag.
-- @param repeatX
-- @param repeatY
--------------------------------------------------------------------------------
function M:setRepeat(repeatX, repeatY)
    self.grid:setRepeat(repeatX, repeatY)
end

return M


text:
@extends($theme_layout)

@section('content')

					 {{$title}}

				<form action="/admin/{{$active}}/{{$item->id}}" method="POST" id="admin_form" class="form-horizontal">
					<input name="_method" type="hidden" value="PUT">
					<input type="hidden" name="_token" value="{{ csrf_token() }}">

 {{Lang::get('admin.content')}}

						@foreach($errors->all() as $error)

							<button class="close" data-close="alert"></button>
							{{$error}}

						@endforeach

							<button class="close" data-close="alert"></button>
							{{Lang::get('admin.form_errors')}}

							<button class="close" data-close="alert"></button>
							{{Lang::get('admin.form_success')}}

							{{Lang::get('admin.type')}}
							*

									<select class="form-control" name="type" id="selectType" required data-required="1">
										<option value="category">{{ucwords(Lang::get('admin.normal'))}}</option>
										<option value="portfolio">{{ucwords(Lang::get('admin.portfolio'))}}</option>
										<option value="about_us">{{ucwords(Lang::get('admin.about_us'))}}</option>
										<option value="services">{{ucwords(Lang::get('admin.services'))}}</option>
										<option value="faq">{{ucwords(Lang::get('admin.faq'))}}</option>
										<option value="gallery">{{ucwords(Lang::get('admin.gallery'))}}</option>
										<option value="careers">{{ucwords(Lang::get('admin.careers'))}}</option>
									</select>

							{{Lang::get('admin.title')}}
							*

								<input type="text" name="title" value="{{$item->title}}" data-required="1" class="form-control" required/>

							{{Lang::get('admin.subtitle')}}

								<input type="text" name="subtitle" value="{{$item->subtitle}}" class="form-control"/>

							{{Lang::get('admin.intro')}}

								<textarea name="intro" class="form-control">{{$item->intro}}</textarea>

							{{Lang::get('admin.quote')}}

								<textarea name="quote" class="form-control">{{$item->quote}}</textarea>

							{{Lang::get('admin.quote_author')}}

								<input type="text" name="quote_author" value="{{$item->quote_author}}" class="form-control"/>

							{{Lang::get('admin.staff')}}

								<input type="hidden" id="staff" name="staff" class="form-control select2" value="">

							{{Lang::get('admin.testimonials')}}

								<input type="hidden" id="testimonials" name="testimonials" class="form-control select2" value="">

							{{Lang::get('admin.description')}}

								<textarea class="wysihtml5 form-control" rows="10" name="description" data-error-container="#editor1_error">
									{{$item->description}}
								</textarea>

 {{Lang::get('admin.media')}}

							{{Lang::get('admin.main')}} {{Lang::get('admin.image')}}

								<input type="hidden" id="main_image" name="image_id" class="form-control select2" value="">

							{{Lang::get('admin.gallery')}} {{Lang::get('admin.images')}}

								<input type="hidden" id="gallery" name="gallery" class="form-control select2" value="">

 {{Lang::get('admin.settings')}}

							{{Lang::get('admin.parent')}} {{Lang::get('admin.category')}}

								<select class="form-control select2me" name="parent_id" id="selectParent">
									<option value="">{{Lang::get('admin.none')}}</option>
									@foreach($categories as $category)
									<option value="{{$category->id}}">{{$category->title}}</option>
									@endforeach
								</select>

							{{Lang::get('admin.slug')}}
							*

								<input type="text" name="slug" value="{{$item->slug}}" data-required="1" class="form-control" required/>

							{{Lang::get('admin.language')}}
							*

								<select class="form-control select2me" name="language" id="selectLanguage" required data-required="1">
									@foreach($languages as $language)
									<option value="{{$language->language}}">{{$language->name}}</option>
									@endforeach
								</select>

							{{Lang::get('admin.order')}}
							*

									<input type="text" name="order" value="{{$item->order}}" data-required="1" class="form-control" required/>

							{{Lang::get('admin.status')}}
							*

									<select class="form-control" name="status" id="selectStatus" required data-required="1">
										<option value="1">{{ucwords(Lang::get('admin.activated'))}}</option>
										<option value="0">{{ucwords(Lang::get('admin.deactivated'))}}</option>
									</select>

								<button type="submit" class="btn green">Submit</button>
								<button type="button" onclick="history.go(-1);" class="btn default">Cancel</button>

				</form>

@endsection

@section('headerPlugins')
@endsection

@section('header')
<link rel="stylesheet" type="text/css" href="/themes/bootstrap/assets/global/plugins/select2/select2.css"/>
<link rel="stylesheet" type="text/css" href="/themes/bootstrap/assets/global/plugins/bootstrap-wysihtml5/bootstrap-wysihtml5.css"/>
<link rel="stylesheet" type="text/css" href="/themes/bootstrap/assets/global/plugins/bootstrap-datepicker/css/datepicker.css"/>
@endsection

@section('footerPlugins')

@endsection

@section('footer')

@if($item->image_id)

@endif

@endsection

@section('inits')
FormValidation.init();
@endsection