text:
package pasta.music.adapters;

import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.async.Action;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.BitmapImageViewTarget;

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

import pasta.music.Pasta;
import pasta.music.R;
import pasta.music.activities.PlayerActivity;
import pasta.music.data.AlbumListData;
import pasta.music.data.ArtistListData;
import pasta.music.data.PlaylistListData;
import pasta.music.data.TrackListData;
import pasta.music.dialogs.AddToPlaylistDialog;
import pasta.music.dialogs.NewPlaylistDialog;
import pasta.music.fragments.AlbumFragment;
import pasta.music.fragments.ArtistFragment;
import pasta.music.fragments.PlaylistFragment;
import pasta.music.utils.ImageUtils;
import pasta.music.utils.PreferenceUtils;
import pasta.music.utils.StaticUtils;
import pasta.music.views.CustomImageView;

public class OmniAdapter extends RecyclerView.Adapter<OmniAdapter.ViewHolder> {

    private List original;
    private List list;
    private AppCompatActivity activity;
    private Pasta pasta;
    private boolean thumbnails, cards, trackList, palette, dark;
    private boolean isFavoriteBehavior;

    public OmniAdapter(AppCompatActivity activity, List list, boolean isFavoriteBehavior) {
        original = list;
        if (list != null) {
            this.list = new ArrayList();
            try {
                this.list.addAll(original);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        this.activity = activity;
        pasta = (Pasta) activity.getApplicationContext();

        thumbnails = PreferenceUtils.isThumbnails(activity);
        cards = PreferenceUtils.isCards(activity);
        trackList = PreferenceUtils.isListTracks(activity);
        palette = PreferenceUtils.isPalette(activity);
        dark = PreferenceUtils.isDarkTheme(activity);

        this.isFavoriteBehavior = isFavoriteBehavior;
    }

    public void addData(Parcelable data) {
        if (data == null) return;
        original.add(data);
        int pos = list.size();
        list.add(pos, data);
        notifyItemInserted(pos);
    }

    public void addData(List data) {
        if (data == null) return;
        original.addAll(data);
        list.addAll(data);
        notifyDataSetChanged();
    }

    public void swapData(List list) {
        original = list;
        this.list = new ArrayList();
        this.list.addAll(list);
        notifyDataSetChanged();
    }

    public void removeData(int position) {
        if (position < 0 || position > original.size()) return;
        original.remove(original.indexOf(list.get(position)));
        list.remove(position);
        notifyItemRemoved(position);
    }

    public void removeData(Parcelable data) {
        original.remove(original.indexOf(data));
        int pos = list.indexOf(data);
        list.remove(pos);
        notifyItemRemoved(pos);
    }

    @Override
    public int getItemViewType(int position) {
        if (position >= list.size() || position < 0) return -1;
        Object o = list.get(position);
        if (o instanceof TrackListData) return 0;
        else if (o instanceof AlbumListData) return 1;
        else if (o instanceof PlaylistListData) return 2;
        else if (o instanceof ArtistListData) return 3;
        else return -1;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        switch (viewType) {
            case 0:
                return new TrackViewHolder(inflater.inflate(trackList ? R.layout.track_item : (cards ? R.layout.track_item_card : R.layout.track_item_tile), null));
            case 1:
                return new AlbumViewHolder(inflater.inflate(cards ? R.layout.album_item_card : R.layout.album_item_tile, null));
            case 2:
                return new PlaylistViewHolder(inflater.inflate(cards ? R.layout.playlist_item_card : R.layout.playlist_item_tile, null));
            case 3:
                return new ArtistViewHolder(inflater.inflate(cards ? R.layout.artist_item_card : R.layout.artist_item_tile, null));
            default:
                return null;
        }
    }

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

        String image;

        switch (getItemViewType(position)) {
            case 0:
                View trackMenu = holder.v.findViewById(R.id.menu);
                if (trackMenu.getVisibility() == View.GONE) trackMenu.setVisibility(View.VISIBLE);

                trackMenu.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PopupMenu popup = new PopupMenu(v.getContext(), v);
                        MenuInflater inflater = popup.getMenuInflater();
                        inflater.inflate(R.menu.menu_track, popup.getMenu());

                        final MenuItem fav = popup.getMenu().findItem(R.id.action_fav);
                        if (isFavoriteBehavior) fav.setTitle(R.string.unfav);
                        else new Action<Boolean>() {
                            @NonNull
                            @Override
                            public String id() {
                                return "isTrackFav";
                            }

                            @Nullable
                            @Override
                            protected Boolean run() throws InterruptedException {
                                return pasta.isFavorite((TrackListData) list.get(holder.getAdapterPosition()));
                            }

                            @Override
                            protected void done(@Nullable Boolean result) {
                                if (result == null) return;
                                if (result) {
                                    fav.setTitle(R.string.unfav);
                                } else {
                                    fav.setTitle(R.string.fav);
                                }
                            }

                        }.execute();

                        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                            @Override
                            public boolean onMenuItemClick(final MenuItem item) {
                                switch (item.getItemId()) {
                                    case R.id.action_fav:
                                        new Action<Boolean>() {
                                            @NonNull
                                            @Override
                                            public String id() {
                                                return "favTrack";
                                            }

                                            @Nullable
                                            @Override
                                            protected Boolean run() throws InterruptedException {
                                                if (!pasta.toggleFavorite((TrackListData) list.get(holder.getAdapterPosition()))) {
                                                    return null;
                                                } else return pasta.isFavorite((TrackListData) list.get(holder.getAdapterPosition()));
                                            }

                                            @Override
                                            protected void done(@Nullable Boolean result) {
                                                if (result == null) {
                                                    pasta.onError(activity, "favorite track action");
                                                    return;
                                                }
                                                if (result) item.setTitle(R.string.unfav);
                                                else {
                                                    item.setTitle(R.string.fav);
                                                    if (isFavoriteBehavior) removeData(holder.getAdapterPosition());
                                                }
                                            }

                                        }.execute();
                                        break;
                                    case R.id.action_add:
                                        new AddToPlaylistDialog(activity, ((TrackListData) list.get(holder.getAdapterPosition()))).show();
                                        break;
                                    case R.id.action_album:
                                        new Action<AlbumListData>() {
                                            @NonNull
                                            @Override
                                            public String id() {
                                                return "gotoAlbum";
                                            }

                                            @Nullable
                                            @Override
                                            protected AlbumListData run() throws InterruptedException {
                                                return pasta.getAlbum(((TrackListData) list.get(holder.getAdapterPosition())).albumId);
                                            }

                                            @Override
                                            protected void done(@Nullable AlbumListData result) {
                                                if (result == null) {
                                                    pasta.onError(activity, "album menu action");
                                                    return;
                                                }

                                                Bundle args = new Bundle();
                                                args.putParcelable("album", result);

                                                Fragment f = new AlbumFragment();
                                                f.setArguments(args);

                                                activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment, f).addToBackStack(null).commit();
                                            }
                                        }.execute();
                                        break;
                                    case R.id.action_artist:
                                        TrackListData track = (TrackListData) list.get(holder.getAdapterPosition());
                                        if (track.artists.size() > 0) {
                                            new Action<ArtistListData>() {
                                                @NonNull
                                                @Override
                                                public String id() {
                                                    return "gotoArtist";
                                                }

                                                @Nullable
                                                @Override
                                                protected ArtistListData run() throws InterruptedException {
                                                    return pasta.getArtist(((TrackListData) list.get(holder.getAdapterPosition())).artists.get(0).artistId);
                                                }

                                                @Override
                                                protected void done(@Nullable ArtistListData result) {
                                                    if (result == null) {
                                                        pasta.onError(activity, "artist menu action");
                                                        return;
                                                    }

                                                    Bundle args = new Bundle();
                                                    args.putParcelable("artist", result);

                                                    Fragment f = new ArtistFragment();
                                                    f.setArguments(args);

                                                    activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment, f).addToBackStack(null).commit();
                                                }
                                            }.execute();
                                        }
                                        break;
                                }
                                return false;
                            }
                        });
                        popup.show();
                    }
                });

                TrackListData trackData = (TrackListData) list.get(position);

                image = trackData.trackImage;

                ((TextView) holder.v.findViewById(R.id.name)).setText(trackData.trackName);
                TextView extra = (TextView) holder.v.findViewById(R.id.extra);
                if (trackData.artists.size() > 0)
                    extra.setText(trackData.artists.get(0).artistName);
                else extra.setText("");

                holder.v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int position = 0;
                        List<TrackListData> trackList = new ArrayList<>();
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i) instanceof TrackListData) {
                                if (i == holder.getAdapterPosition()) position = trackList.size();
                                trackList.add((TrackListData) list.get(i));
                            }
                        }
                        StaticUtils.play(position, trackList, activity);

                        ActivityOptionsCompat options = ActivityOptionsCompat.makeCustomAnimation(activity, R.anim.slide_up, R.anim.blank);
                        activity.startActivity(new Intent(activity, PlayerActivity.class), options.toBundle());
                    }
                });
                break;
            case 1:
                holder.v.findViewById(R.id.menu).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PopupMenu popup = new PopupMenu(v.getContext(), v);
                        MenuInflater inflater = popup.getMenuInflater();
                        inflater.inflate(R.menu.menu_basic, popup.getMenu());

                        final MenuItem fav = popup.getMenu().findItem(R.id.action_fav);
                        if (isFavoriteBehavior) fav.setTitle(R.string.unfav);
                        else new Action<Boolean>() {
                            @NonNull
                            @Override
                            public String id() {
                                return "isAlbumFav";
                            }

                            @Nullable
                            @Override
                            protected Boolean run() throws InterruptedException {
                                return pasta.isFavorite((AlbumListData) list.get(holder.getAdapterPosition()));
                            }

                            @Override
                            protected void done(@Nullable Boolean result) {
                                if (result == null) return;
                                if (result) {
                                    fav.setTitle(R.string.unfav);
                                } else {
                                    fav.setTitle(R.string.fav);
                                }
                            }

                        }.execute();

                        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                            @Override
                            public boolean onMenuItemClick(final MenuItem item) {
                                switch (item.getItemId()) {
                                    case R.id.action_fav:
                                        new Action<Boolean>() {
                                            @NonNull
                                            @Override
                                            public String id() {
                                                return "favAlbum";
                                            }

                                            @Nullable
                                            @Override
                                            protected Boolean run() throws InterruptedException {
                                                if (!pasta.toggleFavorite((AlbumListData) list.get(holder.getAdapterPosition()))) {
                                                    return null;
                                                } else return pasta.isFavorite((AlbumListData) list.get(holder.getAdapterPosition()));
                                            }

                                            @Override
                                            protected void done(@Nullable Boolean result) {
                                                if (result == null) {
                                                    pasta.onError(activity, "favorite album menu action");
                                                    return;
                                                }
                                                if (result) {
                                                    item.setTitle(R.string.unfav);
                                                } else {
                                                    item.setTitle(R.string.fav);

                                                    if (isFavoriteBehavior) removeData(holder.getAdapterPosition());
                                                }
                                            }

                                        }.execute();
                                        break;
                                    case R.id.action_web:
                                        activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(StaticUtils.getAlbumUrl(((AlbumListData) list.get(holder.getAdapterPosition())).albumId))));
                                        break;
                                    case R.id.action_share:
                                        AlbumListData data = (AlbumListData) list.get(holder.getAdapterPosition());

                                        Intent s = new Intent(android.content.Intent.ACTION_SEND);
                                        s.setType("text/plain");
                                        s.putExtra(Intent.EXTRA_SUBJECT, data.albumName);
                                        s.putExtra(Intent.EXTRA_TEXT, StaticUtils.getAlbumUrl(data.albumId));
                                        activity.startActivity(Intent.createChooser(s, data.albumName));
                                        break;
                                }
                                return false;
                            }
                        });
                        popup.show();
                    }
                });

                AlbumListData albumData = (AlbumListData) list.get(position);

                image = albumData.albumImage;

                View artist = holder.v.findViewById(R.id.artist);
                if (artist != null) {
                    if (albumData.artists != null && albumData.artists.size() > 0) {
                        ((TextView) holder.v.findViewById(R.id.artist_name)).setText(albumData.artists.get(0).artistName);
                        ((TextView) holder.v.findViewById(R.id.artist_extra)).setText(albumData.albumDate);

                        new Action<ArtistListData>() {
                            @NonNull
                            @Override
                            public String id() {
                                return "gotoArtist";
                            }

                            @Nullable
                            @Override
                            protected ArtistListData run() throws InterruptedException {
                                return pasta.getArtist(((AlbumListData) list.get(holder.getAdapterPosition())).artists.get(0).artistId);
                            }

                            @Override
                            protected void done(@Nullable ArtistListData result) {
                                if (result == null) {
                                    pasta.onError(activity, "artist action");
                                    return;
                                }

                                holder.v.findViewById(R.id.artist).setTag(result);

                                ImageView artistImage = (ImageView) holder.v.findViewById(R.id.artist_image);
                                if (artistImage != null)
                                    Glide.with(activity).load(result.artistImage).into((ImageView) holder.v.findViewById(R.id.artist_image));
                            }
                        }.execute();

                        artist.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                ArtistListData artist = (ArtistListData) v.getTag();
                                if (artist != null) {
                                    Bundle args = new Bundle();
                                    args.putParcelable("artist", artist);

                                    Fragment f = new ArtistFragment();
                                    f.setArguments(args);

                                    activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment, f).addToBackStack(null).commit();
                                } else {
                                    new Action<ArtistListData>() {
                                        @NonNull
                                        @Override
                                        public String id() {
                                            return "gotoArtist";
                                        }

                                        @Nullable
                                        @Override
                                        protected ArtistListData run() throws InterruptedException {
                                            return pasta.getArtist(((AlbumListData) list.get(holder.getAdapterPosition())).artists.get(0).artistId);
                                        }

                                        @Override
                                        protected void done(@Nullable ArtistListData result) {
                                            if (result == null) {
                                                pasta.onError(activity, "artist action");
                                                return;
                                            }

                                            Bundle args = new Bundle();
                                            args.putParcelable("artist", result);

                                            Fragment f = new ArtistFragment();
                                            f.setArguments(args);

                                            activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment, f).addToBackStack(null).commit();
                                        }
                                    }.execute();
                                }
                            }
                        });
                    } else artist.setVisibility(View.GONE);
                }

                ((TextView) holder.v.findViewById(R.id.name)).setText(albumData.albumName);
                ((TextView) holder.v.findViewById(R.id.extra)).setText(String.valueOf(albumData.tracks) + (albumData.tracks == 1 ? " track" : " tracks"));

                holder.v.findViewById(R.id.album).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle args = new Bundle();
                        args.putParcelable("album", (AlbumListData) list.get(holder.getAdapterPosition()));

                        Fragment f = new AlbumFragment();
                        f.setArguments(args);

                        activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment, f).addToBackStack(null).commit();
                    }
                });
                break;
            case 2:
                holder.v.findViewById(R.id.menu).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PopupMenu popup = new PopupMenu(v.getContext(), v);
                        MenuInflater inflater = popup.getMenuInflater();
                        inflater.inflate(R.menu.menu_playlist, popup.getMenu());

                        final MenuItem fav = popup.getMenu().findItem(R.id.action_fav);
                        if (isFavoriteBehavior) fav.setTitle(R.string.unfav);
                        else new Action<Boolean>() {
                            @NonNull
                            @Override
                            public String id() {
                                return "isPlaylistFav";
                            }

                            @Nullable
                            @Override
                            protected Boolean run() throws InterruptedException {
                                return pasta.isFavorite((PlaylistListData) list.get(holder.getAdapterPosition()));
                            }

                            @Override
                            protected void done(@Nullable Boolean result) {
                                if (result == null) return;
                                if (result) {
                                    fav.setTitle(R.string.unfav);
                                } else {
                                    fav.setTitle(R.string.fav);
                                }
                            }

                        }.execute();

                        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                            @Override
                            public boolean onMenuItemClick(final MenuItem item) {
                                switch (item.getItemId()) {
                                    case R.id.action_fav:
                                        new Action<Boolean>() {
                                            @NonNull
                                            @Override
                                            public String id() {
                                                return "favPlaylist";
                                            }

                                            @Nullable
                                            @Override
                                            protected Boolean run() throws InterruptedException {
                                                if (!pasta.toggleFavorite((PlaylistListData) list.get(holder.getAdapterPosition()))) {
                                                    return null;
                                                } else return pasta.isFavorite((PlaylistListData) list.get(holder.getAdapterPosition()));
                                            }

                                            @Override
                                            protected void done(@Nullable Boolean result) {
                                                if (result == null) {
                                                    pasta.onError(activity, "favorite playlist menu action");
                                                    return;
                                                }
                                                if (result) {
                                                    item.setTitle(R.string.unfav);
                                                } else {
                                                    item.setTitle(R.string.fav);
                                                    if (isFavoriteBehavior) removeData(holder.getAdapterPosition());
                                                }
                                            }

                                        }.execute();
                                        break;
                                    case R.id.action_edit:
                                        new NewPlaylistDialog(activity).setPlaylist((PlaylistListData) list.get(holder.getAdapterPosition())).setOnCreateListener(new NewPlaylistDialog.OnCreateListener() {
                                            @Override
                                            public void onCreate() {
                                                notifyItemChanged(holder.getAdapterPosition());
                                            }
                                        }).show();
                                        break;
                                    case R.id.action_web:
                                        PlaylistListData data = (PlaylistListData) list.get(holder.getAdapterPosition());
                                        activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(StaticUtils.getPlaylistUrl(data.playlistOwnerId, data.playlistId))));
                                        break;
                                    case R.id.action_share:
                                        PlaylistListData data2 = (PlaylistListData) list.get(holder.getAdapterPosition());

                                        Intent s = new Intent(android.content.Intent.ACTION_SEND);
                                        s.setType("text/plain");
                                        s.putExtra(Intent.EXTRA_SUBJECT, data2.playlistName);
                                        s.putExtra(Intent.EXTRA_TEXT, StaticUtils.getPlaylistUrl(data2.playlistOwnerId, data2.playlistId));
                                        activity.startActivity(Intent.createChooser(s, data2.playlistName));
                                        break;
                                }
                                return false;
                            }
                        });

                        popup.getMenu().findItem(R.id.action_edit).setVisible(true);
                        popup.show();
                    }
                });

                PlaylistListData playlistData = (PlaylistListData) list.get(position);

                image = playlistData.playlistImage;

                ((TextView) holder.v.findViewById(R.id.name)).setText(playlistData.playlistName);
                ((TextView) holder.v.findViewById(R.id.extra)).setText(playlistData.tracks + (playlistData.tracks == 1 ? " track" : " tracks"));

                holder.v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle args = new Bundle();
                        args.putParcelable("playlist", (PlaylistListData) list.get(holder.getAdapterPosition()));

                        Fragment f = new PlaylistFragment();
                        f.setArguments(args);

                        activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment, f).addToBackStack(null).commit();
                    }
                });
                break;
            case 3:
                holder.v.findViewById(R.id.menu).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PopupMenu popup = new PopupMenu(v.getContext(), v);
                        MenuInflater inflater = popup.getMenuInflater();
                        inflater.inflate(R.menu.menu_basic, popup.getMenu());

                        final MenuItem fav = popup.getMenu().findItem(R.id.action_fav);
                        if (isFavoriteBehavior) fav.setTitle(R.string.unfav);
                        else new Action<Boolean>() {
                            @NonNull
                            @Override
                            public String id() {
                                return "isTrackFav";
                            }

                            @Nullable
                            @Override
                            protected Boolean run() throws InterruptedException {
                                return pasta.isFavorite((ArtistListData) list.get(holder.getAdapterPosition()));
                            }

                            @Override
                            protected void done(@Nullable Boolean result) {
                                if (result == null) return;
                                if (result) {
                                    fav.setTitle(R.string.unfav);
                                } else {
                                    fav.setTitle(R.string.fav);
                                }
                            }

                        }.execute();

                        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                            @Override
                            public boolean onMenuItemClick(final MenuItem item) {
                                switch (item.getItemId()) {
                                    case R.id.action_fav:
                                        new Action<Boolean>() {
                                            @NonNull
                                            @Override
                                            public String id() {
                                                return "favArtist";
                                            }

                                            @Nullable
                                            @Override
                                            protected Boolean run() throws InterruptedException {
                                                if (!pasta.toggleFavorite((ArtistListData) list.get(holder.getAdapterPosition()))) {
                                                    return null;
                                                } else
                                                    return pasta.isFavorite((ArtistListData) list.get(holder.getAdapterPosition()));
                                            }

                                            @Override
                                            protected void done(@Nullable Boolean result) {
                                                if (result == null) {
                                                    pasta.onError(activity, "favorite artist menu action");
                                                    return;
                                                }
                                                if (result) {
                                                    item.setTitle(R.string.unfav);
                                                } else {
                                                    item.setTitle(R.string.fav);
                                                    if (isFavoriteBehavior) removeData(holder.getAdapterPosition());
                                                }
                                            }

                                        }.execute();
                                        break;
                                    case R.id.action_web:
                                        activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(StaticUtils.getArtistUrl(((ArtistListData) list.get(holder.getAdapterPosition())).artistId))));
                                        break;
                                    case R.id.action_share:
                                        ArtistListData data = (ArtistListData) list.get(holder.getAdapterPosition());

                                        Intent s = new Intent(android.content.Intent.ACTION_SEND);
                                        s.setType("text/plain");
                                        s.putExtra(Intent.EXTRA_SUBJECT, data.artistName);
                                        s.putExtra(Intent.EXTRA_TEXT, StaticUtils.getArtistUrl(data.artistId));
                                        activity.startActivity(Intent.createChooser(s, data.artistName));
                                        break;
                                }
                                return false;
                            }
                        });
                        popup.show();
                    }
                });

                ArtistListData artistData = (ArtistListData) list.get(position);

                image = artistData.artistImage;

                ((TextView) holder.v.findViewById(R.id.name)).setText(artistData.artistName);
                ((TextView) holder.v.findViewById(R.id.extra)).setText(String.valueOf(artistData.followers) + (artistData.followers == 1 ? " follower" : " followers"));

                holder.v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle args = new Bundle();
                        args.putParcelable("artist", (ArtistListData) list.get(holder.getAdapterPosition()));

                        Fragment f = new ArtistFragment();
                        f.setArguments(args);

                        activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment, f).addToBackStack(null).commit();
                    }
                });
                break;
            default:
                return;
        }

        ImageView imageView = (ImageView) holder.v.findViewById(R.id.image);

        if (!thumbnails) imageView.setVisibility(View.GONE);
        else {
            Glide.with(activity).load(image).asBitmap().placeholder(ImageUtils.getVectorDrawable(activity, R.drawable.preload)).into(new BitmapImageViewTarget(imageView) {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                    ((CustomImageView) getView()).transition(resource);
                    if (!thumbnails) getView().setVisibility(View.GONE);

                    View bg = holder.v.findViewById(R.id.bg);
                    if (!thumbnails || !palette || bg == null) return;
                    Palette.from(resource).generate(new Palette.PaletteAsyncListener() {
                        @Override
                        public void onGenerated(Palette palette) {
                            int defaultColor = dark ? Color.DKGRAY : Color.WHITE;
                            int color = palette.getLightVibrantColor(defaultColor);
                            if (dark) color = palette.getDarkVibrantColor(defaultColor);

                            ValueAnimator animator = ValueAnimator.ofObject(new ArgbEvaluator(), defaultColor, color);
                            animator.setDuration(250);
                            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                                @Override
                                public void onAnimationUpdate(ValueAnimator animation) {
                                    int color = (int) animation.getAnimatedValue();
                                    holder.v.findViewById(R.id.bg).setBackgroundColor(color);

                                    View artist = holder.v.findViewById(R.id.artist);
                                    if (artist != null) artist.setBackgroundColor(Color.argb(255, Math.max(Color.red(color) - 10, 0), Math.max(Color.green(color) - 10, 0), Math.max(Color.blue(color) - 10, 0)));
                                }
                            });
                            animator.start();
                        }
                    });
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    public static class TrackViewHolder extends ViewHolder {
        public View v;

        public TrackViewHolder(View v) {
            super(v);
            this.v = v;
        }
    }

    public static class AlbumViewHolder extends ViewHolder {
        public View v;

        public AlbumViewHolder(View v) {
            super(v);
            this.v = v;
        }
    }

    public static class PlaylistViewHolder extends ViewHolder {
        public View v;

        public PlaylistViewHolder(View v) {
            super(v);
            this.v = v;
        }
    }

    public static class ArtistViewHolder extends ViewHolder {
        public View v;

        public ArtistViewHolder(View v) {
            super(v);
            this.v = v;
        }
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public View v;

        public ViewHolder(View v) {
            super(v);
            this.v = v;
        }
    }
}


text:
void compile_and_link_test()
{
   check_result<float>(boost::math::sinc_pi<float>(f));
   check_result<double>(boost::math::sinc_pi<double>(d));
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
   check_result<long double>(boost::math::sinc_pi<long double>(l));
#endif
}

redpajama_set_name: RedPajamaGithub


text:
<?php

class Drupal_Sniffs_Commenting_InlineCommentUnitTest extends CoderSniffUnitTest
{

    /**
     * Returns the lines where errors should occur.
     *
     * The key of the array should represent the line number and the value
     * should represent the number of errors that should occur on that line.
     *
     * @return array(int => int)
     */
    public function getErrorList($testFile)
    {
        return array(
                8 => 1,
                10 => 1,
                13 => 1,
                15 => 1,
                20 => 1,
                24 => 1,
                44 => 1,
                47 => 1,
                59 => 2,
               );

    }//end getErrorList()

    /**
     * Returns the lines where warnings should occur.
     *
     * The key of the array should represent the line number and the value
     * should represent the number of warnings that should occur on that line.
     *
     * @return array(int => int)
     */
    public function getWarningList($testFile)
    {
        return array(
                16 => 1,
               );

    }//end getWarningList()

}//end class


text:
package com.navercorp.pinpoint.web.vo.stat;

import com.navercorp.pinpoint.web.vo.chart.Point;
import com.navercorp.pinpoint.web.vo.chart.UncollectedPointCreatorFactory;
import com.navercorp.pinpoint.web.vo.stat.chart.agent.AgentStatPoint;

import java.util.Objects;

/**
 * @author Roy Kim
 */
public class SampledDirectBuffer implements SampledAgentStatDataPoint {

    public static final Long UNCOLLECTED_VALUE = -1L;
    public static final Point.UncollectedPointCreator<AgentStatPoint<Long>> UNCOLLECTED_POINT_CREATOR = UncollectedPointCreatorFactory.createLongPointCreator(UNCOLLECTED_VALUE);

    private final AgentStatPoint<Long> directCount;
    private final AgentStatPoint<Long> directMemoryUsed;
    private final AgentStatPoint<Long> mappedCount;
    private final AgentStatPoint<Long> mappedMemoryUsed;

    public SampledDirectBuffer(AgentStatPoint<Long> directCount, AgentStatPoint<Long> directMemoryUsed, AgentStatPoint<Long> mappedCount, AgentStatPoint<Long> mappedMemoryUsed) {
        this.directCount = Objects.requireNonNull(directCount, "directCount");
        this.directMemoryUsed = Objects.requireNonNull(directMemoryUsed, "directMemoryUsed");
        this.mappedCount = Objects.requireNonNull(mappedCount, "mappedCount");
        this.mappedMemoryUsed = Objects.requireNonNull(mappedMemoryUsed, "mappedMemoryUsed");
    }
    public AgentStatPoint<Long> getDirectCount() {
        return directCount;
    }

    public AgentStatPoint<Long> getDirectMemoryUsed() {
        return directMemoryUsed;
    }

    public AgentStatPoint<Long> getMappedCount() {
        return mappedCount;
    }

    public AgentStatPoint<Long> getMappedMemoryUsed() {
        return mappedMemoryUsed;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("SampledDirectBuffer{");
        sb.append("directCount=").append(directCount);
        sb.append("directMemoryUsed=").append(directMemoryUsed);
        sb.append("mappedCount=").append(mappedCount);
        sb.append("mappedMemoryUsed=").append(mappedMemoryUsed);
        sb.append('}');
        return sb.toString();
    }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.0
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Resources {
    using System;
    using System.Reflection;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Strings {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Strings() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Resources.Strings", typeof(Strings).GetTypeInfo().Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Alternation conditions do not capture and cannot be named..
        /// </summary>
        internal static string AlternationCantCapture {
            get {
                return ResourceManager.GetString("AlternationCantCapture", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Alternation conditions cannot be comments..
        /// </summary>
        internal static string AlternationCantHaveComment {
            get {
                return ResourceManager.GetString("AlternationCantHaveComment", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Target array type is not compatible with the type of items in the collection..
        /// </summary>
        internal static string Arg_InvalidArrayType {
            get {
                return ResourceManager.GetString("Arg_InvalidArrayType", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Only single dimensional arrays are supported for the requested action..
        /// </summary>
        internal static string Arg_RankMultiDimNotSupported {
            get {
                return ResourceManager.GetString("Arg_RankMultiDimNotSupported", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Cannot include class \{0} in character range..
        /// </summary>
        internal static string BadClassInCharRange {
            get {
                return ResourceManager.GetString("BadClassInCharRange", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Start index cannot be less than 0 or greater than input length..
        /// </summary>
        internal static string BeginIndexNotNegative {
            get {
                return ResourceManager.GetString("BeginIndexNotNegative", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Capture number cannot be zero..
        /// </summary>
        internal static string CapnumNotZero {
            get {
                return ResourceManager.GetString("CapnumNotZero", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Capture group numbers must be less than or equal to Int32.MaxValue..
        /// </summary>
        internal static string CaptureGroupOutOfRange {
            get {
                return ResourceManager.GetString("CaptureGroupOutOfRange", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Count cannot be less than -1..
        /// </summary>
        internal static string CountTooSmall {
            get {
                return ResourceManager.GetString("CountTooSmall", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Enumeration has either not started or has already finished..
        /// </summary>
        internal static string EnumNotStarted {
            get {
                return ResourceManager.GetString("EnumNotStarted", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Illegal conditional (?(...)) expression..
        /// </summary>
        internal static string IllegalCondition {
            get {
                return ResourceManager.GetString("IllegalCondition", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Illegal \ at end of pattern..
        /// </summary>
        internal static string IllegalEndEscape {
            get {
                return ResourceManager.GetString("IllegalEndEscape", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Illegal {x,y} with x > y..
        /// </summary>
        internal static string IllegalRange {
            get {
                return ResourceManager.GetString("IllegalRange", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Incomplete \p{X} character escape..
        /// </summary>
        internal static string IncompleteSlashP {
            get {
                return ResourceManager.GetString("IncompleteSlashP", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Internal error in ScanRegex..
        /// </summary>
        internal static string InternalError {
            get {
                return ResourceManager.GetString("InternalError", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Invalid group name: Group names must begin with a word character..
        /// </summary>
        internal static string InvalidGroupName {
            get {
                return ResourceManager.GetString("InvalidGroupName", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Length cannot be less than 0 or exceed input length..
        /// </summary>
        internal static string LengthNotNegative {
            get {
                return ResourceManager.GetString("LengthNotNegative", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to parsing '{0}' - {1}.
        /// </summary>
        internal static string MakeException {
            get {
                return ResourceManager.GetString("MakeException", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Malformed \k<...> named back reference..
        /// </summary>
        internal static string MalformedNameRef {
            get {
                return ResourceManager.GetString("MalformedNameRef", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to (?({0}) ) malformed..
        /// </summary>
        internal static string MalformedReference {
            get {
                return ResourceManager.GetString("MalformedReference", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Malformed \p{X} character escape..
        /// </summary>
        internal static string MalformedSlashP {
            get {
                return ResourceManager.GetString("MalformedSlashP", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Missing control character..
        /// </summary>
        internal static string MissingControl {
            get {
                return ResourceManager.GetString("MissingControl", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Nested quantifier {0}..
        /// </summary>
        internal static string NestedQuantify {
            get {
                return ResourceManager.GetString("NestedQuantify", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Result cannot be called on a failed Match..
        /// </summary>
        internal static string NoResultOnFailed {
            get {
                return ResourceManager.GetString("NoResultOnFailed", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Not enough )'s..
        /// </summary>
        internal static string NotEnoughParens {
            get {
                return ResourceManager.GetString("NotEnoughParens", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to This operation is only allowed once per object..
        /// </summary>
        internal static string OnlyAllowedOnce {
            get {
                return ResourceManager.GetString("OnlyAllowedOnce", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Quantifier {x,y} following nothing..
        /// </summary>
        internal static string QuantifyAfterNothing {
            get {
                return ResourceManager.GetString("QuantifyAfterNothing", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The RegEx engine has timed out while trying to match a pattern to an input string. This can occur for many reasons, including very large inputs or excessive backtracking caused by nested quantifiers, back-references and other factors..
        /// </summary>
        internal static string RegexMatchTimeoutException_Occurred {
            get {
                return ResourceManager.GetString("RegexMatchTimeoutException_Occurred", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Replacement pattern error..
        /// </summary>
        internal static string ReplacementError {
            get {
                return ResourceManager.GetString("ReplacementError", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to [x-y] range in reverse order..
        /// </summary>
        internal static string ReversedCharRange {
            get {
                return ResourceManager.GetString("ReversedCharRange", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to A subtraction must be the last element in a character class..
        /// </summary>
        internal static string SubtractionMustBeLast {
            get {
                return ResourceManager.GetString("SubtractionMustBeLast", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Insufficient hexadecimal digits..
        /// </summary>
        internal static string TooFewHex {
            get {
                return ResourceManager.GetString("TooFewHex", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Too many | in (?()|)..
        /// </summary>
        internal static string TooManyAlternates {
            get {
                return ResourceManager.GetString("TooManyAlternates", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Too many )'s..
        /// </summary>
        internal static string TooManyParens {
            get {
                return ResourceManager.GetString("TooManyParens", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Reference to undefined group number {0}..
        /// </summary>
        internal static string UndefinedBackref {
            get {
                return ResourceManager.GetString("UndefinedBackref", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Reference to undefined group name {0}..
        /// </summary>
        internal static string UndefinedNameRef {
            get {
                return ResourceManager.GetString("UndefinedNameRef", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to (?({0}) ) reference to undefined group..
        /// </summary>
        internal static string UndefinedReference {
            get {
                return ResourceManager.GetString("UndefinedReference", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Unexpected opcode in regular expression generation: {0}..
        /// </summary>
        internal static string UnexpectedOpcode {
            get {
                return ResourceManager.GetString("UnexpectedOpcode", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Unimplemented state..
        /// </summary>
        internal static string UnimplementedState {
            get {
                return ResourceManager.GetString("UnimplementedState", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Unknown property '{0}'..
        /// </summary>
        internal static string UnknownProperty {
            get {
                return ResourceManager.GetString("UnknownProperty", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Unrecognized control character..
        /// </summary>
        internal static string UnrecognizedControl {
            get {
                return ResourceManager.GetString("UnrecognizedControl", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Unrecognized escape sequence \{0}..
        /// </summary>
        internal static string UnrecognizedEscape {
            get {
                return ResourceManager.GetString("UnrecognizedEscape", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Unrecognized grouping construct..
        /// </summary>
        internal static string UnrecognizedGrouping {
            get {
                return ResourceManager.GetString("UnrecognizedGrouping", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Unterminated [] set..
        /// </summary>
        internal static string UnterminatedBracket {
            get {
                return ResourceManager.GetString("UnterminatedBracket", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Unterminated (?#...) comment..
        /// </summary>
        internal static string UnterminatedComment {
            get {
                return ResourceManager.GetString("UnterminatedComment", resourceCulture);
            }
        }
    }
}


text:
namespace ProbabilityDistributions {
  template <unsigned int K, class D, class W = D, class T = W>
  class Discrete: public Distribution<D,W,T> {
    public:
      static_assert(K > 0, "Can't create distribution without classes.");

      static constexpr unsigned int sample_size = K;

      Discrete();
      explicit Discrete(std::vector<T> const& p);

      void anneal(T temp = 1);

      void set_p(std::vector<T> const& p) { assert(p.size() == K); p_ = p; normalize(); }
      std::vector<T> const& get_p() const { return p_; }
      unsigned int get_number_of_classes() const { return K; }
      Discrete<K,D,W,T> const&
        operator=(Discrete<K,D,W,T> const& other) {
          set_p(other.get_p());
          return *this;
        }

      template <class RNG>
      void sample(MA::Array<D>& samples, size_t n_samples, RNG& rng) const;

      using Distribution<D,W,T>::log_likelihood;
      T log_likelihood(MA::ConstArray<D> const& data,
          MA::ConstArray<W> const& weight) const;

      using Distribution<D,W,T>::MLE;
      void MLE(MA::ConstArray<D> const& data, MA::ConstArray<W> const& weight,
          std::vector<size_t> const& indexes = std::vector<size_t>());

      void sample_to_index(MA::Array<unsigned int>& indexes,
          MA::ConstArray<D> const& samples) const;

      void index_to_sample(MA::Array<D>& samples,
          MA::ConstArray<unsigned int> const& indexes) const;

    private:
      void check_data_and_weight(MA::ConstArray<D> const& data,
          MA::ConstArray<W> const& weight) const;
      void normalize();

      std::vector<T> p_;
  };
};

#include "discrete_impl.hpp"

#endif


text:
<?php

class Translation extends \Vortaro\Storage\Translations\EloquentTranslation {

}


text:
package com.udojava.jmx.wrapper;

import static org.junit.Assert.assertEquals;

import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.IntrospectionException;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanException;
import javax.management.ReflectionException;

import org.junit.Test;

public class BeanAttributeTest {
	@JMXBean
	public class TestBean1 {
		private String stringAttribute;
		private boolean booleanAttribute;

		@JMXBeanAttribute
		public boolean isBooleanAttribute() {
			return booleanAttribute;
		}

		@JMXBeanAttribute
		public void setBooleanAttribute(boolean booleanAttribute) {
			this.booleanAttribute = booleanAttribute;
		}

		@JMXBeanAttribute
		public String getStringAttribute() {
			return stringAttribute;
		}

		@JMXBeanAttribute
		public void setStringAttribute(String stringAttribute) {
			this.stringAttribute = stringAttribute;
		}
	}

	@Test(expected=AttributeNotFoundException.class)
	public void testStringSetUnknown() throws IntrospectionException,
			SecurityException, InvalidAttributeValueException, MBeanException,
			ReflectionException, AttributeNotFoundException {
		JMXBeanWrapper bean = new JMXBeanWrapper(new TestBean1());

		bean.setAttribute(new Attribute("unknownAttribute", "test value"));
	}

	@Test
	public void testStringSetGet() throws IntrospectionException,
			SecurityException, AttributeNotFoundException,
			InvalidAttributeValueException, MBeanException, ReflectionException {
		JMXBeanWrapper bean = new JMXBeanWrapper(new TestBean1());

		bean.setAttribute(new Attribute("stringAttribute", "test value"));
		assertEquals("test value", bean.getAttribute("stringAttribute"));

		bean.setAttribute(new Attribute("booleanAttribute", true));
		assertEquals(true, bean.getAttribute("booleanAttribute"));
	}

	@Test
	public void testGetAttributes() throws IntrospectionException,
			SecurityException, AttributeNotFoundException,
			InvalidAttributeValueException, MBeanException, ReflectionException {
		JMXBeanWrapper bean = new JMXBeanWrapper(new TestBean1());

		bean.setAttribute(new Attribute("stringAttribute", "test value"));
		bean.setAttribute(new Attribute("booleanAttribute", true));

		AttributeList attributes = bean
				.getAttributes(new String[] { "stringAttribute" });

		assertEquals("test value", ((Attribute) attributes.get(0)).getValue());
		assertEquals(1, attributes.size());

		attributes = bean.getAttributes(new String[] { "stringAttribute",
				"booleanAttribute" });

		assertEquals("test value", ((Attribute) attributes.get(0)).getValue());
		assertEquals(true, ((Attribute) attributes.get(1)).getValue());
		assertEquals(2, attributes.size());
	}

	@Test
	public void testSetAttributes() throws IntrospectionException,
			SecurityException, AttributeNotFoundException, MBeanException,
			ReflectionException {
		JMXBeanWrapper bean = new JMXBeanWrapper(new TestBean1());

		AttributeList aList = new AttributeList();

		aList.add(new Attribute("stringAttribute", "a string value"));
		aList.add(new Attribute("booleanAttribute", true));

		bean.setAttributes(aList);

		assertEquals("a string value", bean.getAttribute("stringAttribute"));
		assertEquals(true, bean.getAttribute("booleanAttribute"));

	}

}


text:
package helpers

import (
	"fmt"
	"strings"
)

// PerfTest represents a type of test to run when running `netperf`.
type PerfTest string

const (
	// TCP_RR represents a netperf test for TCP Request/Response performance.
	// For more information, consult : http://www.cs.kent.edu/~farrell/dist/ref/Netperf.html
	TCP_RR = PerfTest("TCP_RR")

	// TCP_STREAM represents a netperf test for TCP throughput performance.
	// For more information, consult : http://www.cs.kent.edu/~farrell/dist/ref/Netperf.html
	TCP_STREAM = PerfTest("TCP_STREAM")

	// TCP_MAERTS represents a netperf test for TCP throughput performance (reverse direction of TCP_STREAM).
	// For more information, consult : http://www.cs.kent.edu/~farrell/dist/ref/Netperf.html
	TCP_MAERTS = PerfTest("TCP_MAERTS")

	// TCP_CRR represents a netperf test that connects and sends single request/response
	// For more information, consult : http://www.cs.kent.edu/~farrell/dist/ref/Netperf.html
	TCP_CRR = PerfTest("TCP_CRR")

	// UDP_RR represents a netperf test for UDP Request/Response performance.
	// For more information, consult : http://www.cs.kent.edu/~farrell/dist/ref/Netperf.html
	UDP_RR = PerfTest("UDP_RR")
)

// PingWithCount returns the string representing the ping command to ping the
// specified endpoint, and takes a custom number of requests to send.
func PingWithCount(endpoint string, count uint) string {
	return fmt.Sprintf("ping -W %d -c %d %s", PingTimeout, count, endpoint)
}

// Ping returns the string representing the ping command to ping the specified
// endpoint.
func Ping(endpoint string) string {
	return PingWithCount(endpoint, PingCount)
}

// Ping6 returns the string representing the ping6 command to ping6 the
// specified endpoint.
func Ping6(endpoint string) string {
	return fmt.Sprintf("ping6 -c %d %s", PingCount, endpoint)
}

// Wrk runs a standard wrk test for http
func Wrk(endpoint string) string {
	return fmt.Sprintf("wrk -t2 -c100 -d30s -R2000 http://%s", endpoint)
}

// CurlFail returns the string representing the curl command with `-s` and
// `--fail` options enabled to curl the specified endpoint.  It takes a
// variadic optionalValues argument. This is passed on to fmt.Sprintf() and
// used into the curl message.
func CurlFail(endpoint string, optionalValues ...interface{}) string {
	statsInfo := `time-> DNS: '%{time_namelookup}(%{remote_ip})', Connect: '%{time_connect}',` +
		`Transfer '%{time_starttransfer}', total '%{time_total}'`

	if len(optionalValues) > 0 {
		endpoint = fmt.Sprintf(endpoint, optionalValues...)
	}
	return fmt.Sprintf(
		`curl --path-as-is -s -D /dev/stderr --fail --connect-timeout %d --max-time %d %s -w "%s"`,
		CurlConnectTimeout, CurlMaxTimeout, endpoint, statsInfo)
}

// CurlFailNoStats does the same as CurlFail() except that it does not print
// the stats info.
func CurlFailNoStats(endpoint string, optionalValues ...interface{}) string {
	if len(optionalValues) > 0 {
		endpoint = fmt.Sprintf(endpoint, optionalValues...)
	}
	return fmt.Sprintf(
		`curl --path-as-is -s -D /dev/stderr --fail --connect-timeout %[1]d --max-time %[2]d %[3]s`,
		CurlConnectTimeout, CurlMaxTimeout, endpoint)
}

// CurlWithHTTPCode retunrs the string representation of the curl command which
// only outputs the HTTP code returned by its execution against the specified
// endpoint. It takes a variadic optinalValues argument. This is passed on to
// fmt.Sprintf() and uses into the curl message
func CurlWithHTTPCode(endpoint string, optionalValues ...interface{}) string {
	if len(optionalValues) > 0 {
		endpoint = fmt.Sprintf(endpoint, optionalValues...)
	}

	return fmt.Sprintf(
		`curl --path-as-is -s  -D /dev/stderr --output /dev/stderr -w '%%{http_code}' --connect-timeout %d %s`,
		CurlConnectTimeout, endpoint)
}

// CurlWithRetries returns the string representation of the curl command that
// retries the request if transient problems occur. The parameter "retries"
// indicates the maximum number of attempts.  If flag "fail" is true, the
// function will call CurlFail() and add --retry flag at the end of the command
// and return.  If flag "fail" is false, the function will generate the command
// with --retry flag and return.
func CurlWithRetries(endpoint string, retries int, fail bool, optionalValues ...interface{}) string {
	if fail {
		return fmt.Sprintf(
			`%s --retry %d`,
			CurlFail(endpoint, optionalValues...), retries)
	}
	if len(optionalValues) > 0 {
		endpoint = fmt.Sprintf(endpoint, optionalValues...)
	}
	return fmt.Sprintf(
		`curl --path-as-is -s  -D /dev/stderr --output /dev/stderr --retry %d %s`,
		retries, endpoint)
}

// Netperf returns the string representing the netperf command to use when testing
// connectivity between endpoints.
func Netperf(endpoint string, perfTest PerfTest, options string) string {
	return fmt.Sprintf("netperf -l 3 -t %s -H %s %s", perfTest, endpoint, options)
}

// SuperNetperf returns the string representing the super_netperf command to use when
// testing connectivity between endpoints.
func SuperNetperf(sessions int, endpoint string, perfTest PerfTest, options string) string {
	return fmt.Sprintf("super_netperf %d -t %s -H %s %s", sessions, perfTest, endpoint, options)
}

// Netcat returns the string representing the netcat command to the specified
// endpoint. It takes a variadic optionalValues arguments, This is passed to
// fmt.Sprintf uses in the netcat message.
func Netcat(endpoint string, optionalValues ...interface{}) string {
	if len(optionalValues) > 0 {
		endpoint = fmt.Sprintf(endpoint, optionalValues...)
	}
	return fmt.Sprintf("nc -w 4 %s", endpoint)
}

// PythonBind returns the string representing a python3 command which will try
// to bind a socket on the given address and port. Python is available in the
// log-gatherer pod.
func PythonBind(addr string, port uint16, proto string) string {
	var opts []string
	if strings.Contains(addr, ":") {
		opts = append(opts, "family=socket.AF_INET6")
	} else {
		opts = append(opts, "family=socket.AF_INET")
	}

	switch strings.ToLower(proto) {
	case "tcp":
		opts = append(opts, "type=socket.SOCK_STREAM")
	case "udp":
		opts = append(opts, "type=socket.SOCK_DGRAM")
	}

	return fmt.Sprintf(
		`/usr/bin/python3 -c 'import socket; socket.socket(%s).bind((%q, %d))`,
		strings.Join(opts, ", "), addr, port)
}

// ReadFile returns the string representing a cat command to read the file at
// the give path.
func ReadFile(path string) string {
	return fmt.Sprintf("cat %q", path)
}

// OpenSSLShowCerts retrieve the TLS certificate presented at the given
// host:port when serverName is requested. The openssl cli is available in the
// Cilium pod.
func OpenSSLShowCerts(host string, port uint16, serverName string) string {
	serverNameFlag := ""
	if serverName != "" {
		serverNameFlag = fmt.Sprintf("-servername %q", serverName)
	}
	return fmt.Sprintf("openssl s_client -connect %s:%d %s -showcerts | openssl x509 -outform PEM", host, port, serverNameFlag)
}


text:
"use strict";
var fs = require("fs");
var logger = require("../logger");
/**
 * socket io communication class for read file data from server
 */
var ReadFileEvent = (function () {
    function ReadFileEvent() {
    }
    /**
     * Adds a listener for this event
     * @param socket socket socket io instance
     */
    ReadFileEvent.prototype.onEvent = function (socket) {
        socket.on(ReadFileEvent.eventName, function (readFilePath) {
            fs.readFile(readFilePath, function (err, data) {
                if (err) {
                    logger.error(err);
                    socket.emit(ReadFileEvent.eventName);
                    return;
                }
                socket.emit(ReadFileEvent.eventName, data.toString());
            });
        });
    };
    return ReadFileEvent;
}());
/**
 * event name
 */
ReadFileEvent.eventName = 'readFile';
module.exports = ReadFileEvent;
//# sourceMappingURL=readFileEvent.js.map


text:
#define HOST_REGS 13
#define HOST_CCREG 10
#define EXCLUDE_REG 11
#define SLAVERA_REG 8

#define HOST_IMM8 1
#define HAVE_CMOV_IMM 1
#define CORTEX_A8_BRANCH_PREDICTION_HACK 1
#define USE_MINI_HT 1
//#define REG_PREFETCH 1

/* ARM calling convention:
   r0-r3, r12: caller-save
   r4-r11: callee-save */

#define ARG1_REG 0
#define ARG2_REG 1
#define ARG3_REG 2
#define ARG4_REG 3

/* GCC register naming convention:
   r10 = sl (base)
   r11 = fp (frame pointer)
   r12 = ip (scratch)
   r13 = sp (stack pointer)
   r14 = lr (link register)
   r15 = pc (program counter) */

#define FP 11
#define LR 14
#define HOST_TEMPREG 14

// Note: FP is set to &dynarec_local when executing generated code.
// Thus the local variables are actually global and not on the stack.

extern u8 sh2_dynarec_target[16777216];
extern u32 memory_map[1048576]; // 32-bit

//#define BASE_ADDR 0x6000000 // Code generator target address
#define BASE_ADDR ((u32)&sh2_dynarec_target) // Code generator target address
#define TARGET_SIZE_2 24 // 2^24 = 16 megabytes
//#define TARGET_SIZE_2 25 // 2^25 = 32 megabytes

#ifdef ANDROID
#define __clear_cache clear_cache
#endif


text:
/**
 * @author Jon Carey
 */

#ifndef OW_AUTHORIZERMANAGER_HPP_INCLUDE_GUARD_
#define OW_AUTHORIZERMANAGER_HPP_INCLUDE_GUARD_

#include "OW_config.h"
#include "OW_ServiceIFC.hpp"
#include "OW_Authorizer2IFC.hpp"
#include "OW_CimomCommonFwd.hpp"

namespace OW_NAMESPACE
{

class OW_CIMOMCOMMON_API AuthorizerManager : public ServiceIFC
{
public:

	AuthorizerManager();
	AuthorizerManager(const Authorizer2IFCRef& authorizerRef);

	~AuthorizerManager();

	virtual String getName() const;

	void setAuthorizer(const Authorizer2IFCRef& authorizerRef)
	{
		m_authorizer = authorizerRef;
	}

	void turnOff(OperationContext& context);
	void turnOn(OperationContext& context);
	bool isOn(OperationContext& context);

	/**
	 * Determine if a read of the given instance is allowed. The given
	 * objectPath could be a class path or an instance path.
	 * @param env A reference to a provider environment
	 * @param ns The namespace the instance will be read from
	 * @param className The class name of the instances that will be read.
	 * @param clientPropertyList This is the property list given by the client
	 * 		when requesting the instance(s). The client expects it to have the
	 * 		following meaning:
	 * 			If not NULL then it specifies the only properties that can be
	 *			returned in the instance. If not NULL but the array is empty,
	 * 			then no properties should be returned. If NULL then all
	 * 			properties will be returned.
	 * @param authorizedPropertyList This is the property list the authorizer
	 * 		will placed the authorized property names in. The return value of
	 * 		this method determines how this property list is interpreted. If
	 * 		this method returns NULL, then this propertyList will be iignored
	 * 		on returned. If a pointer to this string array is returned, then
	 * 		authorizedPropertyList contains the property names the client is
	 * 		allowed to retrieve. In this case, if the property list is empty,
	 * 		then the client will not get any properties.
	 * @return true if access is allowed. Otherwise false.
	 */
	bool allowReadInstance(
		const ServiceEnvironmentIFCRef& env,
        const String& ns,
		const String& className,
		const StringArray* clientPropertyList,
		StringArray& authorizedPropertyList,
		OperationContext& context);

#ifndef OW_DISABLE_INSTANCE_MANIPULATION
	/**
	 * Determine if a write of the given instance is allowed.
	 * @param env A reference to a provider environment.
	 * @param ns The namespace the instance will be written to.
	 * @param op The object path of the instance that will be written.
	 * @param dynamic If E_DYNAMIC, then this instance is being written.
	 * 		through a provider. Otherwise it is being written to the
	 * 		static repository.
	 * @param flag Indicates create/modify/delete operation.
	 * @return true if access is allowed. Otherwise false.
	 */
	bool allowWriteInstance(
		const ServiceEnvironmentIFCRef& env,
		const String& ns,
		const CIMObjectPath& op,
		Authorizer2IFC::EDynamicFlag dynamic,
		Authorizer2IFC::EWriteFlag flag,
		OperationContext& context);
#endif

	/**
	 * Determine if a read of the schema is allow for the given namespace.
	 * @param env A reference to a provider environment
	 * @param ns The namespace the schema will be read from.
	 * @return true if access is allowed. Otherwise false.
	 */
	bool allowReadSchema(
		const ServiceEnvironmentIFCRef& env,
		const String& ns,
		OperationContext& context);

#if !defined(OW_DISABLE_SCHEMA_MANIPULATION) || !defined(OW_DISABLE_QUALIFIER_DECLARATION)
	/**
	 * Determine if a write of a schema element is allowed.
	 * @param env A reference to a provider environment
	 * @param ns The namespace the schema write will take place.
	 * @param flag Indicates create/modify/delete operation
	 * @return true if access is allowed. Otherwise false.
	 */
	bool allowWriteSchema(
		const ServiceEnvironmentIFCRef& env,
		const String& ns,
		Authorizer2IFC::EWriteFlag flag,
		OperationContext& context);
#endif

	/**
	 * Determine if the user is allowed access to a namespace.
	 * @param env A reference to a provider environment.
	 * @param ns The namespace that will be accessed.
	 * @return true if access is allowed. Otherwise false.
	 */
	bool allowAccessToNameSpace(
		const ServiceEnvironmentIFCRef& env,
		const String& ns,
		Authorizer2IFC::EAccessType accessType,
		OperationContext& context);

#if !defined(OW_DISABLE_INSTANCE_MANIPULATION) && !defined(OW_DISABLE_NAMESPACE_MANIPULATION)
	/**
	 * Determine if user is allowed to create the given namespace.
	 * @param env A reference to a provider environment.
	 * @param ns The namespace that will be created.
	 * @return true if the creation is authorized. Otherwise false.
	 */
	bool allowCreateNameSpace(
		const ServiceEnvironmentIFCRef& env,
		const String& ns,
		OperationContext& context);

	/**
	 * Determine if the user is allowed to delete the given namespace.
	 * @param env A reference to a provider environment.
	 * @param ns The namespace that will be deleted.
	 * @return true if the deletion is authorized. Otherwise false.
	 */
	bool allowDeleteNameSpace(
		const ServiceEnvironmentIFCRef& env,
		const String& ns,
		OperationContext& context);
#endif

	/**
	 * Determine if the user is allowed to enumerate namespaces.
	 * @param env A reference to a provider environment
	 * @return true if the enumerate is allowed. Otherwise false.
	 */
	bool allowEnumNameSpace(
		const ServiceEnvironmentIFCRef& env,
		OperationContext& context);

	/**
	 * Determine if a method may be invoked.
	 * @param env A reference to a provider environment.
	 * @param ns The namespace containing the instance or class.
	 * @param path The name of the instance or class containing
	 * 		the method.
	 * @param methodName The name of the method.
	 * @return true if access is allowed. Otherwise false.
	 */
	bool allowMethodInvocation(
		const ServiceEnvironmentIFCRef& env,
		const String& ns,
		const CIMObjectPath& path,
		const String& methodName,
		OperationContext& context);

	/**
	 * Called by the CIMOMEnvironment after the CIMServer has be loaded and
	 * initialized.
	 */
	virtual void init(const ServiceEnvironmentIFCRef& env);
	virtual void shutdown();

private:

	Authorizer2IFCRef m_authorizer;
	bool m_initialized;
};

}

#endif


text:
(function($) {

jQuery.fn.pngFix = function(settings) {

	// Settings
	settings = jQuery.extend({
		blankgif: 'blank.gif'
	}, settings);

	var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
	var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

	// jQuery.browser was removed from jquery 1.9
	//if (jQuery.browser.msie && (ie55 || ie6)) {
	if (ie55 || ie6) {

		//fix images with png-source
		jQuery(this).find("img[src$=.png]").each(function() {

			jQuery(this).attr('width',jQuery(this).width());
			jQuery(this).attr('height',jQuery(this).height());

			var prevStyle = '';
			var strNewHTML = '';
			var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
			var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
			var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
			var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
			var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
			var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
			if (this.style.border) {
				prevStyle += 'border:'+this.style.border+';';
				this.style.border = '';
			}
			if (this.style.padding) {
				prevStyle += 'padding:'+this.style.padding+';';
				this.style.padding = '';
			}
			if (this.style.margin) {
				prevStyle += 'margin:'+this.style.margin+';';
				this.style.margin = '';
			}
			var imgStyle = (this.style.cssText);

			strNewHTML += '';
			if (prevStyle != ''){
				strNewHTML = '' + strNewHTML + '';
			}

			jQuery(this).hide();
			jQuery(this).after(strNewHTML);

		});

		// fix css background pngs
		jQuery(this).find("*").each(function(){
			var bgIMG = jQuery(this).css('background-image');
			if(bgIMG.indexOf(".png")!=-1){
				var iebg = bgIMG.split('url("')[1].split('")')[0];
				jQuery(this).css('background-image', 'none');
				jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
			}
		});

		//fix input with png-source
		jQuery(this).find("input[src$=.png]").each(function() {
			var bgIMG = jQuery(this).attr('src');
			jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');';
   		jQuery(this).attr('src', settings.blankgif)
		});

	}

	return jQuery;

};

})(jQuery);