text:
<repo_name>sashka3076/catalog-downloader<file_sep>/README.md
# catalog-downloader
A simple script to download every packages on macOS Software Updates Catalog URLs to your machine automatically.

### How to use:
```bash
git clone https://github.com/Minh-Ton/catalog-downloader.git
cd catalog-downloader
npm install
node index.js
```

branch_name: refs/heads/main


text:
<file_sep>package com.formbuilder.dto;

import lombok.Getter;
import lombok.experimental.Builder;

@Builder
public class ListInformation {
	@Getter
	private String id;

	@Getter
	private String name;
}

branch_name: refs/heads/master

repo_language: Java

repo_name: ayedhedi/spring-mvc-examples


text:
<file_sep>package com.example.picturemaker;

import android.app.Activity;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LiveData;

import com.example.picturemaker.storage.room_tables.Picture;
import com.example.picturemaker.storage.Storage;

import java.util.Objects;

import eightbitlab.com.blurview.BlurView;
import eightbitlab.com.blurview.RenderScriptBlur;

public class PictureActivity extends AppCompatActivity {

    public ImageView image;
    private Picture picture;
    private TextView name;
    private TextView my_score;
    private TextView total_score;
    private ImageView favorite;
    private Button button_start;

    private Storage storage;
    private ImageView imageBackground;
    private BlurView blurLayout;
    private Toolbar toolbar;
    private ViewGroup root;

    public void ShowRating() {
        final AlertDialog.Builder popDialog = new AlertDialog.Builder(this);
        View view = View.inflate(this, R.layout.activity_rating_picture, null);
        popDialog.setView(view);

        final RatingBar progress = view.findViewById(R.id.ratingBar);
        progress.setRating((float) picture.score);

        popDialog.setPositiveButton("Готово",
                (dialog, which) -> {
                    picture.score = (int) progress.getRating();
                    RefreshData();
                    dialog.dismiss();
                }).setNegativeButton("Отмена",
                (dialog, id) -> {
                    RefreshData();
                    dialog.cancel();
                });

        popDialog.create();
        popDialog.show();
    }

    private void RefreshData() {

        this.storage.GetImage(this, this.picture.public_picture, imageBackground);
        this.storage.GetImage(this, this.picture.public_picture, image);

        this.name.setText(this.picture.name);
        String str_rating = getString(R.string.activity_picture_rating).concat(": ");
        this.total_score.setText(str_rating.concat(String.valueOf(this.picture.total_score)));
        this.favorite.setImageResource(this.picture.is_favorite ? R.drawable.ic_favorite_36 : R.drawable.ic_unfavorite_36);

        String str_my_score = getString(R.string.activity_picture_my_score).concat(": ");
        this.my_score.setText(str_my_score.concat(String.valueOf(this.picture.score)));
        final Activity activity = this;

        this.button_start.setOnClickListener(v -> {
            Intent intent = new Intent(activity, PaintActivity.class);
            intent.putExtra("picture_id", picture.id);
            startActivity(intent);
        });

        this.favorite.setOnClickListener(v -> storage.SetFavoritePicture(picture.id, !picture.is_favorite));
    }

    private void LoadItem(Picture picture) {
        this.picture = picture;
        RefreshData();
    }

    private void backArrow() {
        setSupportActionBar(this.toolbar);
        final Drawable upArrow = ContextCompat.getDrawable(this, R.drawable.ic_baseline_arrow_back_ios_24);
        assert upArrow != null;
        upArrow.setColorFilter(ContextCompat.getColor(this, R.color.white), PorterDuff.Mode.SRC_ATOP);
        Objects.requireNonNull(getSupportActionBar()).setHomeAsUpIndicator(upArrow);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("");
        toolbar.setNavigationOnClickListener(v -> finish());
    }

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

        long picture_id = getIntent().getIntExtra("picture_id", 0);

        this.image = findViewById(R.id.picture);
        this.name = findViewById(R.id.activity_picture_name);
        this.my_score = findViewById(R.id.picture_my_score);
        this.total_score = findViewById(R.id.picture_total_score);
        this.favorite = findViewById(R.id.activity_picture_favorite);

        this.button_start = findViewById(R.id.button_start);

        this.storage = Storage.getInstance(this);
        LiveData<Picture> live = this.storage.GetLivePicture(picture_id);
        live.observe(this, this::LoadItem);

        toolbar = (Toolbar) findViewById(R.id.filter_gallery_toolbar2);
        this.backArrow();
        imageBackground = findViewById(R.id.backgroundPicture);
        blurLayout = (BlurView) findViewById(R.id.blurLayout);

        this.root = findViewById(R.id.content_profile_picture);
        blurBackground();
    }

    private void blurBackground() {
        float radius = 8f;

        View decorView = getWindow().getDecorView();
        Drawable windowBackground = decorView.getBackground();

        blurLayout.setupWith(this.root)
                .setFrameClearDrawable(windowBackground)
                .setBlurAlgorithm(new RenderScriptBlur(this))
                .setBlurRadius(radius)
                .setHasFixedTransformationMatrix(true);
    }

}<file_sep>apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.0"

    defaultConfig {
        applicationId "com.example.picturemaker"
        minSdkVersion 23
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        targetCompatibility JavaVersion.VERSION_1_8
        sourceCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    def room_version = "2.2.5"

    implementation "androidx.viewpager2:viewpager2:1.1.0-alpha01"

    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
    implementation "com.google.android.material:material:1.3.0-alpha02"

    //noinspection GradleCompatible
    implementation 'com.android.support:design:28.0.0'
    //noinspection GradleCompatible
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    implementation 'com.mikhaellopez:circularimageview:4.2.0'

    implementation 'com.google.firebase:firebase-storage:19.2.0'
    implementation 'com.firebaseui:firebase-ui-storage:3.1.0'
    implementation 'com.google.firebase:firebase-auth:19.3.2'
    implementation 'com.google.firebase:firebase-database:19.4.0'

    implementation 'com.github.bumptech.glide:glide:4.11.0'
    implementation 'com.google.firebase:firebase-firestore:21.6.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'

    implementation "com.android.support:support-annotations:28.0.0"
    annotationProcessor "com.android.support:support-annotations:28.0.0"

    implementation "android.arch.persistence.room:runtime:$room_version"
    annotationProcessor "android.arch.persistence.room:compiler:$room_version"

    implementation 'com.eightbitlab:blurview:1.6.4'
    implementation 'com.otaliastudios:zoomlayout:1.8.0'
}
<file_sep>package com.example.picturemaker.ui.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.picturemaker.R;
import com.example.picturemaker.storage.Storage;
import com.google.firebase.auth.FirebaseUser;

import java.util.Objects;

public class ProfileFragment extends Fragment {

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

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_profile, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Storage storage = Storage.getInstance(this.getContext());
        FirebaseUser user = storage.getUser();
        TextView tvUsername = Objects.requireNonNull(this.getActivity()).findViewById(R.id.textView10);
        tvUsername.setText("id: ".concat(user.getUid()));

    }

}<file_sep>package com.example.picturemaker.ui.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.example.picturemaker.R;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.Objects;

class ViewPagerFragmentAdapter extends FragmentStateAdapter {

    public ViewPagerFragmentAdapter(@NonNull FragmentActivity fragmentActivity) {
        super(fragmentActivity);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        switch (position) {
            case 1:
                return new TabFragment("Process");
            case 2:
                return new TabFragment("Finish");
            default:
                return new TabFragment("Favorites");
        }
    }

    @Override
    public int getItemCount() {
        return 3;
    }
}

public class CollectionFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_collection, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        String[] titles = new String[]{this.getResources().getString(R.string.collection_tab_favorite),
                this.getResources().getString(R.string.collection_tab_in_process),
                this.getResources().getString(R.string.collection_tab_finished)};

        TabLayout tabLayout = Objects.requireNonNull(this.getActivity()).findViewById(R.id.tab_layout);
        ViewPager2 viewPager = this.getActivity().findViewById(R.id.view_pager);
        viewPager.setAdapter(new ViewPagerFragmentAdapter(this.getActivity()));

        new TabLayoutMediator(tabLayout, viewPager,
                (tab, position) -> tab.setText(titles[position])).attach();
    }

}<file_sep>package com.example.picturemaker.storage;

import android.content.Context;

import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Database;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.Transaction;
import androidx.room.Update;

import com.example.picturemaker.storage.room_tables.Picture;
import com.example.picturemaker.storage.room_tables.ViewPicture;

import java.util.List;

@Dao
interface ViewPictureDao {

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    void insert(ViewPicture viewPicture);

    @Query("DELETE FROM view_picture WHERE viewName IS :viewName AND pictureId=:pictureId")
    void deleteByViewAndPicture(String viewName, long pictureId);

    @Query("SELECT picture.* FROM picture INNER JOIN view_picture ON view_picture.viewName=:viewName AND view_picture.pictureId=picture.id ORDER BY view_picture.id")
    LiveData<List<Picture>> getPicturesFromView(final String viewName);

    @Query("DELETE FROM view_picture WHERE view_picture.viewName=:viewName")
    void deleteAllPicturesFromView(final String viewName);

    @Query("DELETE FROM view_picture")
    void deleteAll();
}

@Dao
interface PictureDao {

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    long insertIgnore(Picture picture);

    @Update
    void update(Picture picture);

    @Transaction
    default boolean is_new(Picture picture) {
        return findByPublicId(picture.public_id) == null;
    }

    @Transaction
    default long insertOrUpdate(Picture picture) {
        long id = insertIgnore(picture);
        if (id == -1) {
            update(picture);
            id = findByPublicId(picture.public_id).id;
        }
        return id;
    }

    @Query("SELECT * FROM Picture WHERE id IS :id")
    Picture findById(long id);

    @Query("SELECT * FROM Picture WHERE id IS :id")
    LiveData<Picture> liveById(long id);

    @Query("SELECT * FROM Picture WHERE public_id IS :public_id")
    Picture findByPublicId(String public_id);
}

@Database(entities = {Picture.class, ViewPicture.class}, version = 37, exportSchema = false)
public abstract class InternalDB extends RoomDatabase {

    private static volatile InternalDB INSTANCE;

    static InternalDB getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (InternalDB.class) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(context, InternalDB.class, "database-name").fallbackToDestructiveMigration().build();
                }
            }
        }
        return INSTANCE;
    }

    public abstract PictureDao pictureDao();

    public abstract ViewPictureDao viewPictureDao();
}<file_sep>package com.example.picturemaker.adapters;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.picturemaker.PictureActivity;
import com.example.picturemaker.R;
import com.example.picturemaker.storage.room_tables.Picture;
import com.example.picturemaker.storage.Storage;

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

class ViewHolderCollectionRV extends RecyclerView.ViewHolder {
    public TextView text;
    public ImageView favorite;
    public View layer;
    public ImageView image;

    public ViewHolderCollectionRV(View itemView) {
        super(itemView);
        image = (ImageView) itemView.findViewById(R.id.imageview);
        text = (TextView) itemView.findViewById(R.id.picture_name);
        favorite = (ImageView) itemView.findViewById(R.id.favorite_image_item_gallery);
        layer = itemView;
    }
}

public class AdapterCollectionRV extends RecyclerView.Adapter<ViewHolderCollectionRV> {
    Context context;
    int layout_item;
    boolean first;
    int spacing_vertical;
    int spacing_horizontal;
    List<Picture> pictures;
    Storage storage;

    public AdapterCollectionRV(Context context, int layout_item, int spacing_vertical, int spacing_horizontal, boolean first) {
        this.context = context;
        this.first = first;
        this.layout_item = layout_item;
        this.spacing_horizontal = spacing_horizontal;
        this.spacing_vertical = spacing_vertical;
        this.pictures = new ArrayList<>();
        this.storage = Storage.getInstance(context);
    }

    @NonNull
    @Override
    public ViewHolderCollectionRV onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(this.layout_item, parent, false);
        return new ViewHolderCollectionRV(v);
    }

    @Override
    public void onBindViewHolder(final ViewHolderCollectionRV holder, final int position) {
        Picture picture = this.pictures.get(position);

        storage.GetImage(context, picture.public_picture, holder.image);
        holder.text.setText(picture.name);

        holder.layer.setOnClickListener(v -> {
            Intent intent = new Intent(context, PictureActivity.class);
            intent.putExtra("picture_id", picture.id);
            context.startActivity(intent);
        });

        holder.favorite.setImageResource(picture.is_favorite ? R.drawable.ic_favorite_36 : R.drawable.ic_unfavorite_36);
        holder.favorite.setOnClickListener(v -> storage.SetFavoritePicture(picture.id, !picture.is_favorite));
    }

    public List<Picture> getData() {
        return this.pictures;
    }

    public void setData(List<Picture> pictures) {
        this.pictures = pictures;
    }

    @Override
    public int getItemCount() {
        return this.pictures.size();
    }
}
<file_sep>package com.example.picturemaker.adapters;

import android.content.Context;
import android.graphics.drawable.GradientDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.picturemaker.R;

import java.util.List;

class ViewHolderColorsRV extends RecyclerView.ViewHolder {

    private final TextView text;
    public View layer;

    public ViewHolderColorsRV(View itemView) {
        super(itemView);
        layer = itemView;
        text = itemView.findViewById(R.id.color_shape);
    }

    public void setBrush(Integer color, Integer n) {
        GradientDrawable drawable = (GradientDrawable) text.getBackground();
        drawable.setColor(color);
        this.text.setText(String.valueOf(n));
    }
}

public class AdapterColorsRV extends RecyclerView.Adapter<ViewHolderColorsRV> {
    int layout_item;
    int spacing_vertical;
    int spacing_horizontal;
    Context context;
    List<Integer> colors;

    public AdapterColorsRV(Context context, List<Integer> colors, int layout_item, int spacing_vertical, int spacing_horizontal) {
        this.context = context;
        this.layout_item = layout_item;
        this.spacing_horizontal = spacing_horizontal;
        this.spacing_vertical = spacing_vertical;
        this.colors = colors;
    }

    @NonNull
    @Override
    public ViewHolderColorsRV onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(this.layout_item, parent, false);
        return new ViewHolderColorsRV(v);
    }

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

        Integer color = this.colors.get(position);
        holder.setBrush(color, position + 1);

        if ((this.spacing_horizontal > 0 || this.spacing_vertical > 0) && position < this.getItemCount() - 1) {
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(holder.itemView.getLayoutParams().width, holder.itemView.getLayoutParams().height);
            params.setMargins(0, this.spacing_vertical, this.spacing_horizontal, 0);
            holder.itemView.setLayoutParams(params);
        }
    }

    @Override
    public int getItemCount() {
        return colors.size();
    }
}
<file_sep>package com.example.picturemaker.storage.room_tables;

import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.Index;
import androidx.room.PrimaryKey;

@Entity(indices = {@Index(value = {"public_id"}, unique = true)})
public class Picture {

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id")
    public int id;

    @ColumnInfo(name = "public_id")
    public String public_id;

    @ColumnInfo(name = "name_id")
    public Long name_id;

    @ColumnInfo(name = "name")
    public String name;

    @ColumnInfo(name = "level")
    public int level;

    @ColumnInfo(name = "total_score")
    public int total_score;

    @ColumnInfo(name = "public_picture")
    public String public_picture;

    @ColumnInfo(name = "is_favorite")
    public boolean is_favorite;

    @ColumnInfo(name = "score")
    public int score;

    @ColumnInfo(name = "progress")
    public int progress;

    public Picture() {
    }

    public Picture(int id, String public_id, Long name_id, String name, int level, int total_score, String public_picture, boolean is_favorite, int score, int progress) {
        this.id = id;
        this.public_id = public_id;
        this.name_id = name_id;
        this.name = name;
        this.level = level;
        this.total_score = total_score;
        this.public_picture = public_picture;
        this.is_favorite = is_favorite;
        this.score = score;
        this.progress = progress;
    }
}
<file_sep>package com.example.picturemaker.ui.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.example.picturemaker.FilterGalleryActivity;
import com.example.picturemaker.R;
import com.example.picturemaker.adapters.AdapterGalleryRV;
import com.example.picturemaker.storage.Storage;
import com.example.picturemaker.storage.room_tables.Picture;
import com.example.picturemaker.support.PictureDiffUtilCallback;
import com.example.picturemaker.support.SpacesItemDecoration;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static android.app.Activity.RESULT_OK;

public class GalleryFragment extends Fragment {

    RecyclerView recyclerView;
    private AdapterGalleryRV adapterGalleryRV;
    private Storage storage;
    private String author;
    private String genre;
    private String level;
    private Map<String, Object> parametersFilter = new Hashtable<>();
    private Map<String, Object> parametersSort = new Hashtable<>();
    private Spinner category;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_gallery, container, false);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            this.genre = data.getStringExtra("genre");
            this.level = data.getStringExtra("level");
            this.author = data.getStringExtra("author");

            Map<String, Object> parameters = new Hashtable<>();

            if (!this.level.equals(this.getString(R.string.any)))
                parameters.put("level", this.level);
            if (!this.genre.equals(this.getString(R.string.any)))
                parameters.put("genre", this.genre);
            if (!this.author.equals(this.getString(R.string.any)))
                parameters.put("author", this.author);

            this.parametersFilter = parameters;
            this.refreshData();
        }
    }

    private void refreshData() {
        this.storage.LoadPicturesByGallery(this.parametersFilter, this.parametersSort);
    }

    private void RefreshAdapter(List<Picture> pictures) {
        PictureDiffUtilCallback pictureDiffUtilCallback = new PictureDiffUtilCallback(adapterGalleryRV.getData(), pictures);
        DiffUtil.DiffResult productDiffResult = DiffUtil.calculateDiff(pictureDiffUtilCallback);
        adapterGalleryRV.setData(pictures);
        productDiffResult.dispatchUpdatesTo(adapterGalleryRV);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        this.storage = Storage.getInstance(this.getContext());
        TextView filter_view = (TextView) Objects.requireNonNull(this.getActivity()).findViewById(R.id.filter_view);

        filter_view.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), FilterGalleryActivity.class);
            intent.putExtra("author", this.author);
            intent.putExtra("level", this.level);
            intent.putExtra("genre", this.genre);
            startActivityForResult(intent, 0);
        });

        recyclerView = (RecyclerView) Objects.requireNonNull(this.getActivity()).findViewById(R.id.rv_gallery);
        ((SimpleItemAnimator) Objects.requireNonNull(recyclerView.getItemAnimator())).setSupportsChangeAnimations(false);
        adapterGalleryRV = new AdapterGalleryRV(this.getContext(), R.layout.item_pictute_gallery, 30, 30, false);
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS);

        recyclerView.addItemDecoration(new SpacesItemDecoration(16));

        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapterGalleryRV);

        LiveData<List<Picture>> liveData = this.storage.GetLiveDataFromView("Gallery");
        liveData.observe(getViewLifecycleOwner(), this::RefreshAdapter);

        this.category = (Spinner) Objects.requireNonNull(this.getActivity()).findViewById(R.id.spinner);
        String[] items = new String[]{this.getString(R.string.sort_descending_ratings),
                this.getString(R.string.sort_ascending_ratings),
                this.getString(R.string.sort_descending_difficulty),
                this.getString(R.string.sort_ascending_difficulty)};

        ArrayAdapter<String> category_adapter = new ArrayAdapter<>(Objects.requireNonNull(this.getContext()), android.R.layout.simple_spinner_dropdown_item, items);
        this.category.setAdapter(category_adapter);
        this.category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                HashMap<String, Object> parameters = new HashMap<>();
                switch (i) {
                    case 0:
                        parameters.put("order_field", "total_score");
                        parameters.put("is_asc", false);
                        break;
                    case 1:
                        parameters.put("order_field", "total_score");
                        parameters.put("is_asc", true);
                        break;
                    case 2:
                        parameters.put("order_field", "level_id");
                        parameters.put("is_asc", false);
                        break;
                    case 3:
                        parameters.put("order_field", "level_id");
                        parameters.put("is_asc", true);
                        break;
                }
                parametersSort = parameters;
                refreshData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }
}

languages: Java Gradle

repo_name: AlertRED/PictureMaker


text:
<file_sep>$("#registrationForm").validate({
	errorPlacement: function (error, element) {
		if (error) {
			if(!element.val()) {
				return;
			}
		setInvalid(element)
		}
	}
});

var $formElements = $(".handle");

$formElements.keyup(function () {
	if ($(this).valid() == true) {
		setValid($(this))
	}
});

$formElements.click(function () {
	disableSelections();
	$("label[for='" + $(this).attr('id') + "']").css("color", "white");
});

var disableSelections = function () {
	var elements = $(".handle");
	for (var i = 0; i < elements.length; i++) {
		refreshLabel($(elements[i]))
	}
};

var refreshLabel = function($element) {
	if(!$element.hasClass("error")) {
		$("label[for='" + $element.attr('id') + "']").css("color", "#5a5b5c");
	}

	if($element.hasClass("valid")) {
		var label = $("label[for='" + $element.attr('id') + "']");
		label.css("color", "#6abd97");
	}
};

var setValid = function($element) {
	var label = $("label[for='" + $element.attr('id') + "']");
	label.css("color", "#6abd97");
	$element.removeClass("error");
	$element.addClass("valid");
};

var setInvalid = function(element) {
	element.removeClass("valid");
	element.addClass("error");

	var label = $("label[for='" + $(element).attr('id') + "']");

	if (element.hasClass("phone-node")) {
		$("#phoneNumber").css("color", "red");
	}
	label.css("color", "red");
};

repo_language: JavaScript


text:
<file_sep>
.PHONY: create events describe list

create:
	aws cloudformation create-stack --stack-name myteststack --template-body file://create-stack.yml

events:
	aws cloudformation describe-stack-events --stack-name myteststack

describe:
	aws cloudformation describe-stacks --stack-name myteststack

list:
	aws cloudformation list-stacks

update:
	aws cloudformation update-stack --stack-name myteststack --template-body file://update-stack.yml

clean:
	aws cloudformation delete-stack --stack-name myteststack<file_sep>
```
aws cloudformation create-stack --stack-name myteststack --template-body file://create-stack.yml
```

```
aws cloudformation describe-stack-events --stack-name myteststack
```

```
aws cloudformation describe-stacks --stack-name myteststack
```

```
aws cloudformation list-stacks
```

languages: Makefile Markdown

repo_language: Makefile

repo_name: jnaalisv/cloudformation-demo


text:
<file_sep><?php
$html='';
for($i=1;$i<=100;$i++){
	if ($i%3==0 && $i%5==0){
		$html.='FizzBuzz';
	}else if($i%3==0){
		$html.='Fizz';
	}else if($i%5==0){
		$html.='Buzz';
	}else{
		$html.=$i;
	}
	// placing some indentation
	$html.=($i>=100 ? '' : '--');
}

echo $html;
?>

repo_language: PHP

repo_name: zapbuild/fizzbuzz


text:
<repo_name>tyad/nodestarter<file_sep>/nodestarter.sh
#!/bin/sh/
git clone https://github.com/creationix/nvm.git ~/.nvm
source ~/.nvm/nvm.sh
nvm install v0.10.24

echo source ~/.nvm/nvm.sh >> ~/.bashrc
echo nvm use v0.10.24

repo_language: Shell

repo_name: tyad/nodestarter


text:
<repo_name>wushufeng/gt_p90a_newrtu<file_sep>/README.md
# gt_p90a_newrtu
bottle

repo_language: Markdown


text:
<file_sep><!DOCTYPE html>

	<title>Admin Panel</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<?php
session_start();
$conn = mysqli_connect('localhost', 'root', '', 'vratsad_code-week');
if (!$conn) {
	die("Connection failed: mysqli_connect_error()");
} else {
}
?>

Code Week 2015

	<form action="login.php" method="post">
		<input type="text" name="username" placeholder="username" id="usr" />

		<input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" id="pass" />

		<input type="submit" value="Login" />
	</form>
<?php
if (!empty($_POST)) {
	$_SESSION['username'] = $_POST['username'];
	$_SESSION['password'] = $_POST['<PASSWORD>'];
	$username = $_SESSION['username'];
	$password_query ="SELECT password FROM admin WHERE username = '$username'";
	$password_result = mysqli_query($conn, $password_query);
	$password_row = mysqli_fetch_assoc($password_result);
	if ($password_row['password'] !== $_SESSION['password']) {
		echo "Wrong username/password!";
	} else {
		header('Location: page1_admin.php');
	}
}
?>

<file_sep>
	<?php $page_name = 'Admin menu'?>
	<?php require_once('header.php');?>

 Welcome to Code Week 2015 admin page. Please choose what you wish to do:

		See Students

		View Sent E-mails

<file_sep>-- phpMyAdmin SQL Dump
-- version 4.1.12
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Aug 02, 2015 at 04:46 PM
-- Server version: 5.6.16
-- PHP Version: 5.5.11

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `vratsad_code-week`
--

-- --------------------------------------------------------

--
-- Table structure for table `admin`
--

CREATE TABLE IF NOT EXISTS `admin` (
  `username` varchar(20) CHARACTER SET cp1251 NOT NULL,
  `password` varchar(64) CHARACTER SET cp1251 NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `admin`
--

INSERT INTO `admin` (`username`, `password`) VALUES
('admin', '<PASSWORD>');

-- --------------------------------------------------------

--
-- Table structure for table `ages`
--

CREATE TABLE IF NOT EXISTS `ages` (
  `age_group` varchar(100) NOT NULL,
  PRIMARY KEY (`age_group`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `ages`
--

INSERT INTO `ages` (`age_group`) VALUES
('над 40 години'),
('от 13 до 19 години'),
('от 20 до 29 години'),
('от 30 до 40 години'),
('под 13 години');

-- --------------------------------------------------------

--
-- Table structure for table `apply`
--

CREATE TABLE IF NOT EXISTS `apply` (
  `course_num` int(11) NOT NULL,
  `student_id` int(11) NOT NULL,
  `test_result` int(11) NOT NULL,
  KEY `course_num` (`course_num`),
  KEY `student_id` (`student_id`),
  KEY `test_result` (`test_result`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- --------------------------------------------------------

--
-- Table structure for table `courses`
--

CREATE TABLE IF NOT EXISTS `courses` (
  `course_num` int(11) NOT NULL,
  `course_name` varchar(50) NOT NULL,
  `hours` int(11) NOT NULL,
  `num_students` int(11) NOT NULL,
  `description` varchar(300) NOT NULL,
  PRIMARY KEY (`course_num`),
  KEY `course_name` (`course_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `courses`
--

INSERT INTO `courses` (`course_num`, `course_name`, `hours`, `num_students`, `description`) VALUES
(101, 'Android', 20, 20, 'Java'),
(102, 'java', 20, 20, 'java'),
(103, 'PHP/MYSQL', 40, 12, ''),
(104, 'Wordpress/HTML', 20, 10, '');

-- --------------------------------------------------------

--
-- Table structure for table `experiences`
--

CREATE TABLE IF NOT EXISTS `experiences` (
  `type` varchar(100) NOT NULL,
  PRIMARY KEY (`type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `experiences`
--

INSERT INTO `experiences` (`type`) VALUES
('без опит'),
('напреднал'),
('начинаещ');

-- --------------------------------------------------------

--
-- Table structure for table `mail_templates`
--

CREATE TABLE IF NOT EXISTS `mail_templates` (
  `id_template` int(11) NOT NULL AUTO_INCREMENT,
  `head` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `content` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`id_template`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `occupations`
--

CREATE TABLE IF NOT EXISTS `occupations` (
  `type_occupation` varchar(60) NOT NULL,
  PRIMARY KEY (`type_occupation`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `occupations`
--

INSERT INTO `occupations` (`type_occupation`) VALUES
('безработен'),
('друго'),
('зает'),
('студент'),
('учащ');

-- --------------------------------------------------------

--
-- Table structure for table `sent_mails`
--

CREATE TABLE IF NOT EXISTS `sent_mails` (
  `id_sent` int(11) NOT NULL AUTO_INCREMENT,
  `e-mail` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `content` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`id_sent`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `statuses`
--

CREATE TABLE IF NOT EXISTS `statuses` (
  `id_status` int(10) NOT NULL AUTO_INCREMENT,
  `status_type` varchar(100) NOT NULL,
  PRIMARY KEY (`id_status`),
  UNIQUE KEY `status_type` (`status_type`),
  KEY `id_status` (`id_status`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `statuses`
--

INSERT INTO `statuses` (`id_status`, `status_type`) VALUES
(1, 'approved'),
(3, 'declined'),
(2, 'not approved'),
(4, 'rejected');

-- --------------------------------------------------------

--
-- Table structure for table `students`
--

CREATE TABLE IF NOT EXISTS `students` (
  `student_id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(20) NOT NULL,
  `last_name` varchar(20) NOT NULL,
  `age` varchar(100) NOT NULL,
  `occupation` varchar(60) NOT NULL,
  `previous_experience` varchar(100) NOT NULL,
  `mail` varchar(100) NOT NULL,
  `course` varchar(30) NOT NULL,
  `phone` int(10) NOT NULL,
  `implementation` varchar(300) NOT NULL,
  `contribution` varchar(300) NOT NULL,
  `status` varchar(100) NOT NULL,
  PRIMARY KEY (`student_id`),
  UNIQUE KEY `student_id_2` (`student_id`),
  KEY `age` (`age`),
  KEY `age_2` (`age`),
  KEY `previous_experience` (`previous_experience`),
  KEY `ocupation` (`occupation`),
  KEY `cource` (`course`),
  KEY `age_3` (`age`),
  KEY `ocupation_2` (`occupation`),
  KEY `course` (`course`),
  KEY `status` (`status`),
  KEY `status_2` (`status`),
  KEY `course_2` (`course`),
  KEY `student_id` (`student_id`),
  FULLTEXT KEY `first_name` (`first_name`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;

--
-- Dumping data for table `students`
--

INSERT INTO `students` (`student_id`, `first_name`, `last_name`, `age`, `occupation`, `previous_experience`, `mail`, `course`, `phone`, `implementation`, `contribution`, `status`) VALUES
(1, 'Ivan', 'Ivanov', '20 - 29', 'employed', 'beginner', '<EMAIL>', 'php', 656565, 'asdfsaf', 'asdf', 'declined'),
(2, 'Petar', 'Petrov', 'over 40', 'schoolboy / schoolgirl', 'inexperienced', '<EMAIL>', 'php', 55956655, 'sdfasdfasdf', 'asdfasdf', 'approved'),
(3, 'George', 'Takei', '30 - 40', 'unemployed', 'advanced', '<EMAIL>', 'java', 898656886, 'asaasdf', 'asdfasdf', 'approved'),
(4, 'Иванка', 'Борисова', '20-29', 'unempoyed', 'begginer', '<EMAIL>', '', 0, '', '', ''),
(5, 'Петър', 'Великов', '20-29', 'unempoyed', '', '<EMAIL>', 'java', 0, 'o', 'gh', ''),
(6, 'Илияна', 'Първанова', 'от 30 до 40 години', 'друго', 'без опит', '<EMAIL>', 'PHP/MYSQL', 0, 'да, ще ми бъде много полезно за работата', 'със сигурност ще повлия', '');

--
-- Constraints for dumped tables
--

--
-- Constraints for table `apply`
--
ALTER TABLE `apply`
  ADD CONSTRAINT `apply_ibfk_1` FOREIGN KEY (`course_num`) REFERENCES `courses` (`course_num`) ON DELETE CASCADE ON UPDATE CASCADE;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
	// Start the session
	session_start();
	//create connection
	$conn = mysqli_connect('localhost', 'vratsad', 'ProgramistB@c3', 'vratsad_code-week');
	if (!$conn) {
	die ("Connection failed: mysqli_connect_error()");
} else {
	//echo "Connected succsessfuly";
}
if (isset($_POST['submit'])) {
	$errors = array();
	$a = trim($_POST['first_name']);
	if(!isset($a) or empty($a))
	{
		$errors['first_name'] = "<NAME>ъведете име";
	}
if (isset($_POST['submit'])) {
	$errors1 = array();
	$b = trim($_POST['last_name']);
	if(!isset($b) or empty($b))
	{
		$errors1['last_name'] = "<NAME>ъ<NAME>";
	}
}
if (isset($_POST['submit'])) {
	$errors4 = array();
	$x = trim($_POST['age']);
	if(!isset($x) or empty($x))
	{
		$errors4['age'] = "Моля въведете възрастова група";
	}
}

if (isset($_POST['submit'])) {
	$errors5 = array();
	$y = trim($_POST['occupation']);
	if(!isset($y) or empty($y))
	{
		$errors5['occupation'] = "Моля въведете статус";
	}
}
	if (isset($_POST['submit'])) {
	$errors3 = array();
	$e = trim($_POST['level']);
	if(!isset($e) or empty($e))
	{
		$errors3['level'] = "Моля въведете опит";
	}
}
	$d = $_POST["course_name"];
	if (isset($_POST['submit'])) {
	$errors2 = array();
	$phone = trim($_POST['phone']);
	if(!isset($phone) or empty($phone))
	{
		$errors2['phone'] = "Моля въведете телефонен номер";
	}
}
	$impl = $_POST["implementation"];
	$contribut = $_POST["contribution"];
	//validation e-mail
	if (empty($_POST["mail"])) {
    $emailErr = "Моля въведете валиден e-mail!";
  } else {
    $c = $_POST["mail"];
    // check if e-mail address is well-formed
    if (!filter_var($c, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Невалиден формат на e-mail!";
    }
  }

    if(empty($errors))
    {
	    mysqli_query($conn, "SET NAMES UTF8");
		$newstudent="INSERT INTO `vratsad_code-week`.`students` (`first_name`, `last_name`, `age`, `occupation`, `previous_experience`, `mail`, `course`, `phone`, `implementation`, `contribution`)
		VALUES ('$a', '$b', '$x', '$y', '$e', '$c', '$d', 'phone', '$impl', '$contribut')";
		$res = mysqli_query($conn, $newstudent);
		if (mysqli_affected_rows($conn) > 0) {
			header("Location: page1.php?reg=true&course=$d");
		}
	}
}else{
	$errors = array();
	$errors['first_name'] = '';
	$errors1['last_name'] = '';
	$errors2['phone'] = '';
	$errors3['level'] = '';
	$errors4['age'] = '';
	$errors5['occupation'] = '';
}
?>

<!DOCTYPE html>

	<title> Регистрация </title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

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

<?php
if(isset($_GET['reg'])){
	$course = $_GET['course'];
	$registered = $_GET['reg'];
	if ($registered) {
		echo "
";
		echo "
";
		echo "
";
		echo "
";
		echo " Благодарим, че се регистрирахте за CodeWeek-Враца 2015г. ";
		echo "
";
		echo "Ще получите email за потвърждение сега и седмица преди събитието email с подробности за вашия модул - $course ";
		echo " Back ";
		echo "
";
		echo "
";
	}
}
?>
<form method="post" action="page1.php" class="form-horizontal">

 CodeWeek

 Форма за регистрация за участие в безплатен курс в рамките на Code Week 2015 година

 * Задължително поле

<form class="form-horizontal" action="page1.php" method="post">

    	Име*

      	<input type="first_name" class="form-control" name="first_name" placeholder="Име">
      	<?php echo " $errors[first_name] "; ?>

    	Фамилия*

      	<input type="last_name" class="form-control" name="last_name" placeholder="Фамилия">
      	<?php echo " $errors1[last_name] "; ?>

    	Email*

      	<input type="email" class="form-control" name="mail" placeholder="Email">

    	Телефон*

      	<input type="phone" class="form-control" name="phone" placeholder="Телефон">
      	<?php echo " $errors2[phone] "; ?>

 Изберете курс, който искате да запишете

		Курс

		<select name="course_name" id="course_name" class="form-control">
  	<?php
  	$sel_course = "SELECT course_name FROM `courses`";
	$rescourse = mysqli_query($conn, $sel_course);

    if (mysqli_num_rows($rescourse) > 0) {

     while($row = mysqli_fetch_assoc($rescourse)) {
         foreach ($row as $key => $value) {
         	echo "<option value='$value' ";
         	if ($row['course_name'] == $value) {
         		echo "selected";
         	}
         	echo ">".$value."</option>";
         }
     }
}
		echo ">".$value."</option>";

  	?>
  	</select>

Какъв опит имате по темата на курса?

	<?php
	mysqli_query($conn, "SET NAMES UTF8");
  	$sel_exp = "SELECT type FROM `experiences`";
	$resexp = mysqli_query($conn, $sel_exp);
    if (mysqli_num_rows($resexp) > 0) {
    	while ($row = mysqli_fetch_assoc($resexp)) {
    		echo "";
    		echo "<input type='radio' name='level' id='level1' value='$row[type]'>$row[type]";
			echo "";
			echo "
";
    	}
    }
  	?>
  	<?php echo " $errors3[level] "; ?>

 С какво се занимавате в момента?

		<?php
		mysqli_query($conn, "SET NAMES UTF8");
  		$sel_occ = "SELECT type_occupation FROM `occupations`";
		$resocc = mysqli_query($conn, $sel_occ);

    	if (mysqli_num_rows($resocc) > 0) {
    	while ($row = mysqli_fetch_assoc($resocc)) {
    		echo "";
    		echo "<input type='radio' name='occupation' id='occupation' value='$row[type_occupation]'>$row[type_occupation]";
			echo "";
			echo "
";
    		}
    	}
  		?>
  		<?php echo " $errors5[occupation] "; ?>

Възраст:

		<?php
		mysqli_query($conn, "SET NAMES UTF8");
  		$sel_age = "SELECT age_group FROM `ages`";
		$resage = mysqli_query($conn, $sel_age);

    	if (mysqli_num_rows($resage) > 0) {
    	while ($row = mysqli_fetch_assoc($resage)) {
    		echo "";
    		echo "<input type='radio' name='age' id='age' value='$row[age_group]'>$row[age_group]";
			echo "";
			echo "
";
    	}
    }
  	?>
  	<?php echo " $errors4[age] "; ?>

Ще използвате ли наученото на събитието в последствие и как?

		<textarea class="form-control" rows="3" name="implementation" placeholder="Text input"></textarea>

Как то би допринесло за бъдещото ви развитие?

		<textarea class="form-control" rows="3" name="contribution" placeholder="Text input"></textarea>

		<input class="btn btn-primary" type="submit" name="submit" value="Регистрация">

</form>

<file_sep>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<?php
$conn = mysqli_connect('localhost', 'root', '', 'vratsad_code-week');
if (!$conn) {
	die ("Connection failed: mysqli_connect_error()");
}
	mysqli_query($conn, "SET NAMES UTF8");
	$status_query = "SELECT status_type FROM statuses";
	$status_result = mysqli_query($conn, $status_query);
	if (!empty($_GET['id'])) {
		$id = $_GET['id'];
	}
?>
<!DOCTYPE html>

	<meta charset="UTF-8">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">

	<title><?php echo $page_name;?></title>

<file_sep>Back to main menu

<form method="POST" action="index.php">
	<select name="filter_status" >
		<option value= ""></option>
		<option value="approved">approved</option>
		<option value="declined">declined</option>
		<option value="rejected">rejected</option>
		<option value="pending">pending</option>
		<option value="not approved">not approved</option>
	</select>
	<select name="filter_course">
	<option value= ""></option>
		<option value="PHP/MYSQL">PHP/MYSQL</option>
		<option value="Android">Android</option>
		<option value="java">java</option>
		<option value="Wordpress/HTML">Wordpress/HTML</option>
	</select>
	<input type="submit" name="filter">
</form>
<?php
session_start();
$page_name = "Students";
require_once('header.php');
	if(!empty($_POST['send'])){
		foreach ($_POST['selected'] as $key => $value) {
			echo "$key - $value
";
		}
	}
	$page_name = 'Students';
	$no = 1;
	$q = "SELECT * FROM students";
	if (isset($_POST['filter'])) {
		if ($_POST['filter_status'] == null) {
		$search_term2 = mysqli_real_escape_string($conn, $_POST['filter_course']);
		$q .= " WHERE course = '$search_term2'";
	} elseif ($_POST['filter_course'] == null) {
		$search_term = mysqli_real_escape_string($conn, $_POST['filter_status']);
		$q .= " WHERE status = '$search_term'";
	} else {
		$search_term = mysqli_real_escape_string($conn, $_POST['filter_status']);
		$search_term2 = mysqli_real_escape_string($conn, $_POST['filter_course']);
		$q .= " WHERE status = '$search_term' AND course = '$search_term2'";
	}

	}
	$result = mysqli_query($conn, $q);
	echo "<form method='post' action='send_email.php' name='checkbox'>";
	echo "
<input type='checkbox' onClick='toggle(this)' /> Select ALL
";
	echo "
";

	if (mysqli_num_rows($result) > 0  ) {
		echo "

		ID
		First Name
		Last Name
		Age
		Occupation
		Experience
		E-mail
		Course
		Phone
		Implementation
		Contribution
		Status
		Edit Status
		Select

";
	echo "
";
	while ($row = mysqli_fetch_assoc($result)) {
		echo "$row[student_id]	";
		echo "$row[first_name]	";
		echo "$row[last_name]	";
		echo "$row[age]	";
		echo "$row[occupation]	";
		echo "$row[previous_experience]	";
		echo "$row[mail]	";
		echo "$row[course]	";
		echo "$row[phone]	";
		echo "$row[implementation]	";
		echo "$row[contribution]	";
		echo "$row[status]	";
		$id = $row['student_id'];
		echo "UPDATE	";
		echo "<input type='checkbox' value='$row[student_id]' name='selected[]'>	";
		echo "
";
	}
}
echo "
</dic>";
?>
	Back to main menu
	<input type="submit" class='btn btn-info' value="Send to Selected" name="send">

</form>
<file_sep><?php
session_start();
$page_name = 'Send Emails';
    require_once('header.php');
    if(!empty($_POST['send'])){
        $id_mail= "";
        foreach ($_POST['selected'] as $key => $value) {
            $id_mail .= "$value, ";
            }
            $id_mail= substr($id_mail, 0, -2);
        }
    if(!empty($_POST['Send2'])){
            $mail= mysqli_query($conn, "SELECT student_id, mail FROM students WHERE student_id IN($_POST[id_mail])");
            while ($row_mail = mysqli_fetch_assoc($mail)) {
                echo "$row_mail[mail] ";
            $to = $row_mail['mail'];
            $subject = $_POST['head'];
            $message = $_POST['body'];
            $headers = 'From: <EMAIL>' . "\r\n" .
            'Please do not reply to this message' . "\r\n" .
            'X-Mailer: PHP/' . phpversion();
            mail($to, $subject, $message, $headers);
            $sent_mails= mysqli_query($conn, "INSERT INTO sent_mails (id_st, mail_head, content) VALUES ('$_POST[id_mail]', '$subject', '$message') ");
            }
        }
        mysqli_close($conn);
?>
<form name='mail2' method='post' action='send_email.php'>

<input type="hidden" name="id_mail" value="<?php echo $id_mail; ?>">

<input type='text' name='head' placeholder='header'>

<textarea name='body' rows="4" cols="50" placeholder='body'></textarea>

<input class='btn btn-danger'type='submit' name="Send2" value='Send'>
</form><file_sep><?php
	$page_name = "Sent Emails";
	require_once ('header.php');
	$q = "SELECT students.student_id, students.first_name, students.last_name, students.mail, students.course, students.status,
	sent_mails.mail_head, sent_mails.content
	FROM students
	INNER JOIN sent_mails ON students.student_id = sent_mails.id_st";
	$result = mysqli_query($conn, $q);
	echo "
";
	if (mysqli_num_rows($result)>0) {
		echo "

		ID
		First Name
		Last Name
		E-mail
		Course
		Mail Head
		Message
		Status

";
	}
	echo "
";
	while ($row = mysqli_fetch_assoc($result)) {
		echo "$row[student_id]	";
		echo "$row[first_name]	";
		echo "$row[last_name]	";
		echo "$row[mail]	";
		echo "$row[course]	";
		echo "$row[mail_head]	";
		echo "$row[content]	";
		echo "$row[status]	";
		echo "
";
	}
	echo "
";
?><file_sep><?php
	$page_name = "Update Student Status";
	require_once('header.php');
	$q = "SELECT first_name,
	last_name,
	age,
	occupation,
	previous_experience,
	mail,
	course,
	phone,
	implementation,
	contribution,
	status
	FROM students WHERE student_id = $id";
	$result = mysqli_query($conn, $q);
	$row = mysqli_fetch_assoc($result);
?>
<?php
?>

Change User №<?php echo $id?>

		<form class="form-horizontal" method="post" action="update_status.php">
			<input type="hidden" name="id" value="<?php echo $id;?>">

				First name

					<input type="text" class="form-control" name="first_name" id="fn" value="<?php echo $row['first_name'];?>">

				Last name

					<input type="text" class="form-control" name="last_name" id="ln" value="<?php echo $row['last_name'];?>">

				Status

					<select name="status" id="status" class="form-control">
						<?php
						if (mysqli_num_rows($status_result) > 0) {
							while ($status_row = mysqli_fetch_assoc($status_result)) {
								foreach ($status_row as $value) {
									echo "<option value='$value' ";
									if ($row['status'] == $value) {
										echo "selected";
									}
									echo ">".$value."</option>";
								}
							}
						}
						?>
					</select>

				<button type="submit" class="btn btn-info">Update Student's Status</button>

		</form>

			Back to Students

		<?php
		if (!empty($_POST)) {
			$id = $_POST['id'];
			$first_name = $_POST['first_name'];
			$last_name = $_POST['last_name'];
			$status = $_POST['status'];
			$update_q = "UPDATE students
			SET status = '$status'
			WHERE student_id = $id ";
			if (mysqli_query($conn, $update_q)) {
				header('Location: index.php');
			}
		}
		?>

languages: SQL PHP

repo_language: SQL

repo_name: code-week/phpProject


text:
<repo_name>maiordom/islider<file_sep>/test/webdriver.js
'use strict';

const webdriver = require('webdriverio');
const expect = require('chai').expect;
const URL = 'http://localhost:3001/demo/';

const options = {
    desiredCapabilities: {
        browserName: 'chrome'
    }
};

let client;

describe('Функциональные тесты для Islider', () => {
    beforeEach(() => {
        client = webdriver.remote(options);

        client.addCommand('mouse', function(selector, eventType, offsetLeft, offsetTop) {
            return this.execute(function(selector, eventType, offsetLeft, offsetTop) {
                evt = document.createEvent('MouseEvents');
                evt.initMouseEvent(eventType, true, true, window, 0, 0, 0, offsetLeft, offsetTop, false, false, false, false, 0, null);
                $(selector)[0].dispatchEvent(evt);
            }, selector, eventType, offsetLeft, offsetTop);
        });

        return client.init();
    });

    afterEach(() => {
        return client.end();
    });

    it('Клик по правой стороне от правого ползунка сдвигает его вправо', function() {
        let offsetOld;
        let offsetNew;

        return client
            .url(URL)
            .execute(() => {
                var el = $('.example-1 .islider__right').eq(0);

                return {
                    x: el.offset().left,
                    width: el.width()
                };
            })
            .then(function(res) {
                offsetOld = res.value.x;
                return this.mouse('.example-1', 'mousedown', res.value.x + res.value.width + 50, 0);
            })
            .pause(300)
            .execute(() => {
                return $('.example-1 .islider__right').eq(0).offset().left;
            })
            .then(res => {
                offsetNew = res.value;
                expect(offsetNew > offsetOld).to.be.true;
            });
    });

    it('Клик по левой стороне от правого ползунка сдвигает его влево', function() {
        let offsetOld;
        let offsetNew;

        return client
            .url(URL)
            .execute(() => {
                var el = $('.example-1 .islider__right').eq(0);

                return {
                    x: el.offset().left,
                    width: el.width()
                };
            })
            .then(function(res) {
                offsetOld = res.value.x;
                return this.mouse('.example-1', 'mousedown', res.value.x - 50, 0);
            })
            .pause(300)
            .execute(() => {
                return $('.example-1 .islider__right').eq(0).offset().left;
            })
            .then(res => {
                offsetNew = res.value;
                expect(offsetNew < offsetOld).to.be.true;
            });
    });

    it('Перемещение правого слайдера в левый край двигает соседний слайдер', () => {
        let data;

        return client
            .url(URL)
            .execute(function() {
                var el = $('.islider:eq(1)');
                var rightHandle = el.find( '.islider__right' );

                return {
                    elOffset: el.offset(),
                    rightHanleOffset: rightHandle.offset()
                };
            })
            .then(res => {
                data = res.value;
            })
            .then(function() {
                return this.mouse('.islider:eq(1) .islider__right', 'mousedown',data.rightHanleOffset.left + 5, data.rightHanleOffset.top + 5);
            })
            .then(function() {
                return this.mouse('.islider:eq(1)', 'mousemove', data.elOffset.left, data.elOffset.top);
            })
            .then(function() {
                return this.mouse('.islider:eq(1) .islider__right', 'mouseup', data.elOffset.left, data.elOffset.top);
            })
            .pause(300)
            .execute(() => {
                return {
                    leftPos: $('.islider:eq(1) .islider__left').position().left,
                    rightPos: $('.islider:eq(1) .islider__right').position().left,
                    leftValue: $('.islider:eq(1)').data().islider.leftVal(),
                    rightValue: $('.islider:eq(1)').data().islider.rightVal(),
                }
            })
            .then((res) => {
                expect(res.value.leftPos).to.equal(res.value.rightPos);
                expect(res.value.leftValue).to.equal(res.value.rightValue);
            })
    });

    it('Перемещение левого слайдера в правый край двигает соседний слайдер', () => {
        let offset;

        return client
            .url(URL)
            .execute(() => {
                return $('.islider:eq(1) .islider__left').offset();
            })
            .then(res => {
                offset = res.value;
            })
            .then(function() {
                return this.mouse('.islider:eq(1) .islider__left', 'mousedown', offset.left + 5, offset.top + 5);
            })
            .then(function() {
                return this.mouse('.islider:eq(1)', 'mousemove', offset.left + 405, offset.top + 5);
            })
            .then(function() {
                return this.mouse('.islider:eq(1) .islider__left', 'mouseup', offset.left + 405, offset.top + 5);
            })
            .pause(300)
            .execute(() => {
                return {
                    leftSlider: $('.islider:eq(1) .islider__left').position().left,
                    rightSlider: $('.islider:eq(1) .islider__right').position().left
                };
            })
            .then(res => {
                expect(res.value.leftSlider).to.equal(res.value.rightSlider);
            });
    });

    it('Клик по треку сдвигает левый ползунок вправо', function() {
        let offsetOld;
        let offsetNew;

        return client
            .url(URL)
            .execute(() => {
                var el = $('.example-1 .islider__left').eq(0);

                return {
                    x: el.offset().left,
                    width: el.width()
                };
            })
            .then(function(res) {
                offsetOld = res.value.x;
                return this.mouse('.example-1', 'mousedown', res.value.x + res.value.width + 50, 0);
            })
            .pause(300)
            .execute(() => {
                return $('.example-1 .islider__left').eq(0).offset().left;
            })
            .then(res => {
                offsetNew = res.value;
                expect(offsetNew).to.not.equal(offsetOld);
            });
    });

    it('Клик по левому краю трека сдвигает левый ползунок влево', function() {
        return client
            .url(URL)
            .mouse('.example-2', 'mousedown', 0, 0)
            .pause(300)
            .execute(() => {
                return $('.example-2 .islider__left').eq(0).position().left;
            })
            .then(res => {
                expect(res.value).to.equal(0);
            });
    });
});<file_sep>/src/islider.styl
@import 'nib'

/* =======================
   ------- iSlider -------
   ======================= */

b = '.islider'

{b}
    position relative
    border-radius 35px

    & *
        margin 0
        padding 0

    &__box
        position relative

    &__path
        position absolute
        border-radius 35px

    &_has_anim &__path
        transition left .2s ease, width .2s ease, height .2s ease, top .2s ease

    &__slider
        position absolute
        z-index 1
        width 26px
        height 26px

    &_has_anim &__slider
        transition left .2s ease, top .2s ease

    &__slider:before
        content ''
        display block
        background none
        position absolute
        border 1px solid #939393
        width 24px
        height 24px
        background #fafafa
        border-radius 50%

    &__slider:after
        content ''
        display block
        left 50%
        top 50%
        margin-left -5px
        margin-top -5px
        position absolute
        width 10px
        height 10px
        border-radius 50%

    &__path-box
        background none !important
        overflow hidden

    &__path-orig
        border-radius 35px

    &_range-max &__path-orig
        position absolute
        right 0
        width 100%

    &_range-max &__path-orig
        position absolute
        bottom 0
        height 100%

.vertical
    height 180px
    width 20px
    box-shadow inset 0 0 5px 1px rgba(95, 95, 95, 0.3)

    {b}__slider
        left -3px

    {b}__path
        width 100%

    {b}__path-orig
        height 100%
        min-height 40px

/* horizontal layout */

{b}_horizontal
    width 250px
    height 20px
    box-shadow inset 0 2px 5px 1px rgba(95, 95, 95, 0.3)

    {b}__slider
        top -3px

    {b}__path
        height 100%

    {b}__path-orig
        height 100%
        min-width 40px

    {b}__left
        margin-left -26px

    {b}__box
        height 100%

    &{b}_range {b}__box
        margin 0 26px

    &{b}_min {b}__box
        margin-left 26px

    &{b}_max {b}__box
        margin-left 26px

    &{b}_range {b}__path
        margin-left -13px
        padding-left 26px

    &{b}_min {b}__path
        margin-left -26px

    &{b}_max {b}__path
        margin-left -26px
        padding-left 13px

/* end */

/* vertical layout */

{b}_vertical

    {b}__left
        margin-top -26px

    &{b}_range {b}__box
        top 26px

    &{b}_min {b}__box
        top 26px

    &{b}_max {b}__box
        top 26px

    &{b}_range {b}__path
        margin-top -13px
        padding-top 26px

    &{b}_min {b}__path
        margin-top -26px

    &{b}_max {b}__path
        margin-top -26px
        padding-top 13px

/* end */
<file_sep>/src/islider-control.js
/* global IsliderDrag:true Utils:true Defaults:true */
function IsliderControl(element, properties) {
    this.element = element;
    this.properties = properties || {};
    this.freeRide = function() {};
    this.setPath = function() {};
    this.options = {};
    this.events = {};
    this.path = null;
    this.box = null;
    this.slider = null;
    this.leftElement = null;
    this.rightElement = null;
    this.elementWidth = null;
    this.handleMetric = null;
    this.metricType = null;
    this.coordType = null;
    this.interface = null;
    this.leftSlider = null;
    this.rightSlider = null;
    this.activeSlider = null;
    this.isVertical = false;
    this.isCrossing = false;

    this.init();
    return this.interface;
}

IsliderControl.prototype = {
    on(eventName, callback) {
        this.events[eventName] = callback;
        return this.interface;
    },

    trigger(eventName, data) {
        if (this.events[eventName]) {
            this.events[eventName].apply(null, data);
        }
    },

    init() {
        this.interface = this.getInterface();
        this.extend();
        this.generate();
        this.cacheNodes();
        this.checkIsVertical();
        this.setVars();
        this.setSetPathHandler();
        this.setSliders();
        this.isRangeSingle();
        this.setInitialData();
        this.bindEvents();
    },

    bindEvents() {
        this.element.on('mousedown', this.onElementClick.bind(this));
        this.leftSlider.on('move', this.onLeftMove.bind(this));
        this.leftSlider.on('stopSlide', this.onStopSlide.bind(this));
        this.rightSlider.on('move', this.onRightMove.bind(this));
        this.rightSlider.on('stopSlide', this.onStopSlide.bind(this));
        this.slider.on('mousedown', this.onStartSlide.bind(this));
        this.slider.on('touchstart', this.onStartSlide.bind(this));
        this.slider.on('mouseenter', this.onHoverElement.bind(this));
        this.slider.on('mouseleave', this.onUnhoverElement.bind(this));
    },

    onElementClick(e) {
        if ($(e.target).hasClass(this.options.slider)) {
            return;
        }

        this.freeRide(e);
    },

    getFreeRideData(e) {
        let width = this.getWidth();
        let elementOffset = this.element.offset();
        let mouseCoord = Utils.getPageCoords(e);

        mouseCoord = this.options.orientation === 'horizontal'
            ? mouseCoord.left - elementOffset.left
            : mouseCoord.top - elementOffset.top;

        return {
            width: width,
            mouseCoord: mouseCoord
        };
    },

    rangeFreeRide(e) {
        let hasMoved = false;
        let coord;
        let distance;

        this.cacheParams();

        let data = this.getFreeRideData(e);
        let width = data.width;
        let mouseCoord = data.mouseCoord;
        let sliderLeft = this.getLeft();
        let sliderRight = this.getRight();

        if (mouseCoord < sliderLeft) {
            coord = mouseCoord - this.handleMetric * 0.5;
            coord = coord < 0 ? 0 : coord;
            this.onLeftMove(coord);
            hasMoved = true;
        } else if (mouseCoord > sliderRight + this.handleMetric) {
            coord = mouseCoord - this.handleMetric * 1.5;
            coord = coord > width ? width : coord;
            this.onRightMove(coord);
            hasMoved = true;
        } else {
            distance = this.getDistance();
            if (sliderLeft + this.handleMetric < mouseCoord && mouseCoord < sliderLeft + this.handleMetric + distance / 2) {
                coord = mouseCoord - this.handleMetric * 0.5;
                if (coord > sliderRight) {
                    coord = sliderRight;
                }
                this.onLeftMove(coord);
                hasMoved = true;
            } else {
                coord = mouseCoord - this.handleMetric * 1.5;
                if (coord < sliderLeft) {
                    coord = sliderLeft;
                }
                this.onRightMove(coord);
                hasMoved = true;
            }
        }

        if (hasMoved) {
            this.triggerStopSlide();
        }
    },

    minMaxFreeRide(e) {
        let data = this.getFreeRideData(e);
        let coord = data.mouseCoord - this.handleMetric * 0.5;

        coord = coord < 0
            ? 0
            : coord > data.width
                ? data.width
                : coord;

        this.onLeftMove(coord);
        this.triggerStopSlide();
    },

    onHoverElement(e) {
        $(e.target).addClass(this.options.hover);
    },

    onUnhoverElement(e) {
        $(e.target).removeClass(this.options.hover);
    },

    onStopSlide() {
        this.element.addClass(this.options.hasAnim);
        this.activeSlider.element.removeClass(this.options.active);
        this.triggerStopSlide();
    },

    onStartSlide(e) {
        if (e.target === this.leftSlider.element[0]) {
            this.activeSlider = this.leftSlider;
        } else if (e.target === this.rightSlider.element[0]) {
            this.activeSlider = this.rightSlider;
        }

        this.activeSlider.startSlide(e);
        this.element.removeClass(this.options.hasAnim);
        this.activeSlider.element.addClass(this.options.active);
        this.cacheParams();

        return false;
    },

    triggerStopSlide() {
        this.element.trigger('islider.stop-slide');
    },

    extend() {
        $.extend(true, this.options, Defaults, this.properties);
    },

    cacheParams() {
        this.leftSlider.position = this.getLeft(true);
        this.rightSlider.position = this.getRight(true);
        this.elementWidth = this.getWidth(true);
    },

    cacheNodes() {
        this.element.addClass(this.options.islider);
        this.slider = this.element.find('.' + this.options.slider);
        this.leftElement = this.element.find('.' + this.options.left);
        this.rightElement = this.element.find('.' + this.options.right);
        this.path = this.element.find('.' + this.options.path);
        this.box = this.element.find('.' + this.options.box);

        setTimeout(function() {
            this.element.addClass(this.options.hasAnim);
        }.bind(this), 10);
    },

    setVars() {
        this.isVertical = this.options.orientation === 'vertical';
        this.metricType = this.isVertical ? 'height' : 'width';
        this.coordType = this.isVertical ? 'top' : 'left';
        this.handleMetric = this.leftElement[this.metricType]() || this.rightElement[this.metricType]();
        this.elementWidth = this.getWidth(true);

        if (this.isVertical) {
            this.box.height(this.elementWidth);
        }
    },

    setSetPathHandler() {
        this.setPath = this.options.range === true
            ? this.setRangePath
            : this.options.range === 'min'
                ? this.setMinPath
                : this.setMaxPath;
    },

    getWidth(readEl) {
        if (!readEl) {
            return this.elementWidth;
        }

        let param = this.isVertical
            ? this.element[0].offsetHeight
            : this.element[0].offsetWidth;

        return param - this.handleMetric * (this.options.range === true ? 2 : 1);
    },

    checkIsVertical() {
        if (this.options.orientation === 'vertical') {
            this.element.addClass('islider_vertical');
        } else {
            this.element.addClass('islider_horizontal');
        }
    },

    isRangeSingle() {
        if (this.options.range === 'min') {
            this.options.values[1] = this.options.value;
            this.element.addClass('islider_min');
            this.freeRide = this.minMaxFreeRide;
        } else if (this.options.range === 'max') {
            this.element.addClass('islider_max');
            let hook = this.options.orientation === 'horizontal' ? 'right' : 'bottom';
            this.path[0].style[hook] = 0;
            this.options.values[0] = this.options.value;
            this.options.values[1] = this.options.domain[1];
            this.freeRide = this.minMaxFreeRide;
        } else {
            this.element.addClass('islider_range');
            this.freeRide = this.rangeFreeRide;
        }
    },

    generate() {
        if (!this.options.generate) {
            return;
        }

        let box = $('<div>').addClass(this.options.box).appendTo(this.element);
        $('<div>').addClass(this.options.left).addClass(this.options.slider).appendTo(box);
        $('<div>').addClass(this.options.right).addClass(this.options.slider).appendTo(box);
        $('<div>').addClass(this.options.path).appendTo(box);
    },

    setSliders() {
        let props = {
            orientation: this.options.orientation,
            domain: this.options.domain,
            step: this.options.step,
            getWidth: this.getWidth.bind(this)
        };

        this.leftSlider = new IsliderDrag(this.leftElement, props);
        this.rightSlider = new IsliderDrag(this.rightElement, props);
    },

    setInitialData() {
        if (this.options.range === true) {
            this.leftSlider.setValue(this.options.values[0]);
            this.rightSlider.setValue(this.options.values[1]);
        } else {
            this.leftSlider.setValue(this.options.value);
        }

        this.cacheParams();
        this.setPath(this.getLeft(), this.getDistance());

        if (this.options.range !== true) {
            this.rightElement.hide();
        }
    },

    getLeft(readElement) {
        if (readElement) {
            return this.leftSlider.getCoord();
        } else {
            return this.leftSlider.position;
        }
    },

    getRight(readElement) {
        if (readElement) {
            return this.rightSlider.getCoord();
        } else {
            return this.rightSlider.position;
        }
    },

    getDistance() {
        return this.getRight() - this.getLeft();
    },

    isLeftCrossing(x) {
        return x >= this.getRight();
    },

    isRightCrossing(x) {
        return x <= this.getLeft();
    },

    onLeftMove(x) {
        this.leftMoveHandler(x);
        this.options.onSlide(this.options.values[0], this.options.values, 'left');
    },

    onRightMove(x) {
        this.rightMoveHandler(x);
        this.options.onSlide(this.options.values[1], this.options.values, 'right');
    },

    leftMoveHandler(x) {
        let pathWidth = this.getRight() - x;
        this.options.values[0] = this.leftSlider.getValue(x);
        this.leftSlider.setCoord(x);
        this.setPath(x, pathWidth < 0 ? 0 : pathWidth);

        if (this.options.range === true) {
            if (this.isLeftCrossing(x)) {
                this.isCrossing = true;
                this.rightSlider.setCoord(x);
                this.options.values[1] = this.options.values[0];
            } else if (this.isCrossing) {
                this.isCrossing = false;
                this.rightSlider.setCoord(this.rightSlider.position);
                this.options.values[1] = this.rightSlider.getValue();
            }
        }
    },

    rightMoveHandler(x) {
        this.options.values[1] = this.rightSlider.getValue(x);
        this.rightSlider.setCoord(x);

        if (this.options.range === true) {
            if (this.isRightCrossing(x)) {
                this.isCrossing = true;
                this.leftSlider.setCoord(x);
                this.options.values[0] = this.options.values[1];
                this.setPath(x, 0);
            } else {
                this.setPath(this.getLeft(), x - this.getLeft());
                if (this.isCrossing) {
                    this.leftSlider.setCoord(this.leftSlider.position);
                    this.options.values[0] = this.leftSlider.getValue();
                }
            }
        } else {
            this.setPath(this.getLeft(), x - this.getLeft());
        }
    },

    setRangePath(left, width) {
        this.path[0].style[this.metricType] = (width / this.getWidth()) * 100 + '%';
        this.path[0].style[this.coordType] = (left / this.getWidth()) * 100 + '%';
    },

    setMaxPath(left) {
        this.path[0].style[this.metricType] = 100 - (left / this.getWidth()) * 100 + '%';
    },

    setMinPath(left) {
        this.path[0].style[this.metricType] = ((left + this.handleMetric / 2) / this.getWidth()) * 100 + '%';
    },

    leftVal(val) {
        if (typeof val === 'number') {
            this.cacheParams();
            this.leftMoveHandler(this.leftSlider.scaleValToCoord(val));
        } else {
            return this.leftSlider.getValue();
        }
    },

    rightVal(val) {
        if (typeof val === 'number') {
            this.cacheParams();
            this.rightMoveHandler(this.rightSlider.scaleValToCoord(val));
        } else {
            return this.rightSlider.getValue();
        }
    },

    getInterface() {
        return {
            on: this.on.bind(this),
            getDist: this.getDistance.bind(this),
            reset: this.setInitialData.bind(this),
            leftVal: this.leftVal.bind(this),
            rightVal: this.rightVal.bind(this)
        };
    }
};
<file_sep>/src/islider.js
/* eslint no-unused-vars: 0 */
/* global IsliderControl */
(function($, root, undefined) { // eslint-disable-line
    'use strict';

    const Utils = {
        getPageCoords(e) {
            if (e.originalEvent.changedTouches || e.originalEventtargetTouches) {
                let page = (e.originalEvent.changedTouches[0] || e.originalEventtargetTouches[0]);
                return {
                    left: page.pageX,
                    top: page.pageY
                };
            } else {
                return {
                    left: e.pageX,
                    top: e.pageY
                };
            }
        }
    };

    const ns = 'islider';

    const Defaults = {
        islider: `${ns}`,
        left: `${ns}__left`,
        right: `${ns}__right`,
        slider: `${ns}__slider`,
        path: `${ns}__path`,
        box: `${ns}__box`,
        hover: `${ns}_hover`,
        active: `${ns}_active`,
        focus: `${ns}_focus`,
        hasAnim: `${ns}_has_anim`,
        orientation: 'horizontal',
        range: 'min',
        step: 1,
        generate: true,
        value: 0,
        domain: [0, 1],
        values: [0, 0],
        onSlide: function(value, values) {}
    };

    // @@control
    // @@drag

    $.fn.islider = function(props) {
        let item;
        let instance;

        $(this).each(function() {
            item = $(this);
            if (item.data('islider')) {
                console.log('islider already init', this);
            } else {
                instance = new IsliderControl(item, props);
                item.data('islider', instance);
            }
        });

        return this;
    };

})(jQuery, window, undefined); // eslint-disable-line
<file_sep>/src/islider-drag.js
/* global Utils:true */
function IsliderDrag(element, properties) {
    this.element = element;
    this.properties = properties;
    this.moveHandler = function() {};
    this.setCoord = function() {};
    this.events = {};
    this.position = null;
    this.range = null;
    this.xMin = null;
    this.xMax = null;
    this.sliderOffset = null;
    this.mouseOffset = null;
    this.tmpCoord = null;
    this.scaleValToCoord = function() {};
    this.scaleCoordToVal = function() {};

    this.init();
};

IsliderDrag.prototype = {
    getCoord(getCoord) {
        if (this.properties.step > 1) {
            return () => {
                return this.trimMouseValue(getCoord());
            };
        }

        return getCoord;
    },

    init() {
        this.cacheObjects();
        this.reset();
    },

    cacheObjects() {
        let isVertical = this.properties.orientation === 'vertical';
        this.moveHandler = isVertical ? this.moveVerticalHandler : this.moveHorizontalHandler;
        this.setCoord = isVertical ? this.setY : this.setX;
        this.getCoord = this.getCoord(isVertical ? this.getY : this.getX);
    },

    reset() {
        this.range = [0, this.properties.getWidth()];
        this.setRange(this.range);
        this.setScale(this.range, this.properties.domain);
    },

    setRange(range) {
        this.xMin = range[0];
        this.xMax = range[1];
    },

    setScale(range, domain) {
        this.scaleValToCoord = this.scale(domain, range);
        this.scaleCoordToVal = this.scale(range, domain);
    },

    on(eventName, callback) {
        this.events[eventName] = callback;
    },

    trigger(eventName, data) {
        if (this.events[eventName]) {
            this.events[eventName].apply(null, data);
        }
    },

    startSlide(e) {
        this.reset();
        this.setMouseOffset(e);
        this.addDocumentEventHandlers();
        this.trigger('startSlide');
    },

    scale(domain, range) {
        let u = this.uninterpolateNumber(domain[0], domain[1]);
        let i = this.interpolateNumber(range[0], range[1]);

        return x => i(u(x));
    },

    uninterpolateNumber(a, b) {
        b = b - (a = +a) ? 1 / (b - a) : 0;
        return x => (x - a) * b;
    },

    interpolateNumber(a, b) {
        b -= a;
        return t => a + b * t;
    },

    addDocumentEventHandlers() {
        let that = this;

        $(document.body).on({
            'mousemove.slider touchmove.slider': function() {
                that.moveHandler.apply(that, arguments);
            },
            'mouseup.slider touchend.slider touchcancel.slider': function() {
                that.removeDocumentEventHandlers.apply(that, arguments);
            }
        });

        document.body.onselectstart = this.returnFalse;
        document.ondragstart = this.returnFalse;
    },

    returnFalse() {
        return false;
    },

    trimMouseValue(x) {
        let val = this.scaleCoordToVal(x);
        let step = (this.properties.step > 0) ? this.properties.step : 1;
        let valModStep = (val - this.range[0]) % step;
        let alignValue = val - valModStep;

        if (Math.abs(valModStep) * 2 >= step) {
            alignValue += (valModStep > 0) ? step : (-step);
        }

        return this.scaleValToCoord(alignValue);
    },

    getPosision(offset) {
        let x = offset + this.tmpCoord;

        if (this.properties.step > 1) {
            x = this.trimMouseValue(x);
        }

        if (this.xMin > x) {
            x = this.xMin;
        } else if (x > this.xMax) {
            x = this.xMax;
        }

        return x;
    },

    moveVerticalHandler(e) {
        let offset = Utils.getPageCoords(e).top - this.mouseOffset.y - this.sliderOffset.top;
        this.trigger('move', [this.getPosision(offset)]);
    },

    moveHorizontalHandler(e) {
        let offset = Utils.getPageCoords(e).left - this.mouseOffset.x - this.sliderOffset.left;
        this.trigger('move', [this.getPosision(offset)]);
    },

    setValue(val) {
        this.setCoord(this.scaleValToCoord(val));
    },

    getValue(x) {
        return this.scaleCoordToVal(typeof x === 'number' ? x : this.getCoord());
    },

    getX() {
        return this.element[0].offsetLeft - parseInt(this.element.css('marginLeft'), 10);
    },

    getY() {
        return this.element[0].offsetTop - parseInt(this.element.css('marginTop'), 10);
    },

    setX(x) {
        this.element[0].style.left = (parseInt(x, 10) / this.properties.getWidth()) * 100 + '%';
    },

    setY(y) {
        this.element[0].style.top = (parseInt(y, 10) / this.properties.getWidth()) * 100 + '%';
    },

    setMouseOffset(e) {
        this.sliderOffset = this.element.offset();
        this.tmpCoord = this.getCoord();
        this.mouseOffset = {
            x: Utils.getPageCoords(e).left - this.sliderOffset.left,
            y: Utils.getPageCoords(e).top - this.sliderOffset.top
        };
    },

    removeDocumentEventHandlers() {
        document.body.onselectstart = null;
        document.ondragstart = null;
        $(document.body).off('mousemove.slider mouseup.slider touchmove.slider');
        this.trigger('stopSlide');
    }
};
<file_sep>/pre-commit.js
'use strict';

const shell = require('shelljs');
const _ = require('lodash');

let result = shell.exec('git diff --cached --name-only --diff-filter=ACM', {silent: true});

if (!result.output) {
    shell.exit(0);
}

let files = _.compact(result.output.split('\n'));

files = files.filter(function (file) {
    return /src\/.*\.js$/.test(file);
});

if (!files.length) {
    shell.exit(0);
}

files.forEach(function (file) {
    var result = shell.exec('eslint ' + __dirname + '/' + file);

    if (result.code) {
        shell.exit(1);
    }
});
<file_sep>/README.md
islider
=======

http://sati.16mb.com/islider/

languages: Stylus Markdown JavaScript

repo_language: Stylus

repo_name: maiordom/islider


text:
<repo_name>songcy6202/CppTest<file_sep>/testTree.cc
#include "scy_test.h"
using namespace scy_test;

int main(int argc, const char *argv[])
{
	BinaryTree<int> binarytree(10,100);
	binarytree.printBinaryTree();
	return 0;
}
<file_sep>/testC++11s.cpp
// testC++11s.cpp : 定义控制台应用程序的入口点。
//

#include <map>
#include <iostream>
#include <vector>
#include <string>
#include <functional>//greater
#include <memory>
#include <unordered_map>
#include <regex>

using namespace std;

struct A
{
	int i = 0;  //##
	int j;
	A(int m, int n) :i(m), j(n){}
	A(){}
	A(int v) :j(v){}
	~A(){ cout << j << " destructor" << endl; }
};

A operator+(int n, const A & a)
{
	return a;
}

template<class T1,class T2>
auto add(T1 x, T2 y)->decltype(x + y)
{
	return x + y;
}

auto func(int m, int n) -> A  //##
{
	return{ m, n };  //##
}

int main(int argc, const char *argv[])
{
	// 1: unify  initialize
	int arr[3]{1, 2, 3};
	vector<int> iv{ 1, 2, 3 };
	map<int, string> mp{ { 1, "a" }, { 2, "b" } };
	string str{ "hello world" };
	int *p = new int[20]{1, 2, 3};
	A *pa = new A{ 3, 7 };

	// 2: auto decltype
	auto i = 100;      //i is int
	auto pp = new A(0);  //p is A*
	auto k = 12345LL;  //k is long long
	map<string, int, greater<string>> mp2;
	for (auto it = mp.begin(); it != mp.end(); ++it)
		cout << it->first << " ," << it->second;

	decltype(arr) x1;      // TODO: x1 is int  arr is int[] or int ???
	decltype((i)) ii = i;  // ii is a int&

	// 3: shared_ptr
	shared_ptr<A> sp1(new A(2));
	shared_ptr<A> sp2(sp1);
	cout << "shared_ptr" << sp1->j << "," << sp2->j << endl;
	shared_ptr<A> sp3;
	A *ptra = sp1.get();
	sp1.reset();  //sp1 is null now
	A *q = new A(3);
	sp1.reset(q);
	shared_ptr<A> sp5;
	//sp5.reset(q); error

	// 4: nullptr
	int *p1 = nullptr;
	int *p2 = NULL;
	shared_ptr<double> p3 = nullptr;
	if (p1 == p2)
		cout << "equal 1" << endl;
	//if (p3 == p2) p3 and p2 types are different
	bool b = nullptr;  //nullptr -> false
	//int  i = nullptr; error

	// 5: for
	int ary[]{1, 2, 3, 4, 5};
	for (int &e : ary)
	{
		e *= 10;
	}
	for (int e : ary)
		cout << e << " ";
	cout << endl;
	vector<int> st(ary, ary + 5);
	for (auto & it : st)
		it *= 10;
	for (auto it : st)
		cout << it << " ";
	cout << endl;

	// 6: right reference
	//class A;
	class B{};
//	B & r = B();  //TODO:????
	B && rr = B();

	// 7: unordered_map
	unordered_map<string, int> turingWinner;
	turingWinner.insert(make_pair("songcy", 2018));
	turingWinner.insert(make_pair("James", 2000));
	turingWinner["songcy"] = 2020;
	turingWinner["new"] = 2001;
	for (auto it : turingWinner)
		cout << it.first << " " << it.second << " " ;
	cout << endl;

	// 8: regex
	regex reg("b.?p.*k");
	cout << regex_match("boppggk", reg) << endl;
	cout << regex_match("boopggk", reg) << endl;

	/***************************
	 * gdb 4.8.1 implement c++11 Expect regex and gc library What fuck!
	 * VS is ok
	 ***************************/
	/*
	regex reg2("\\d{3}([a-zA-Z]+).(\\d{2}|N/A)\\s\\1"); // \\s -> " "
	string correct = "123Hello N/A Hello";
	string incorrect = "123hello 12 Hello";
	cout << regex_match(correct, reg2) << endl;
	cout << regex_match(incorrect, reg2) << endl;
	*/

	// 9: Lambda  [=] [] [&] [x,&y] [=,&x,&y] [&,x,y]
	int x = 100, y = 200, z = 300;
	cout << [](double a, double b){return a + b; }(1.2, 2.5) << endl;
	auto ff = [=, &y, &z](int n)
	{
		cout << x << endl;
		y++, z++;
		return n*n;
	};
	cout << ff(15) << endl;
	int a[4] = { 45, 2, 1, 123 };
	sort(a, a + 4, [](int x, int y)->bool{return x % 10 < y % 10; });
	for_each(a, a + 4, [](int x){cout << x << " "; });
	function<int(int)> fib = [&fib](int n)
	{ return n <= 2 ? 1 : fib(n - 1) + fib(n - 2); };
	cout << fib(5) << endl;

	return 0;
}

<file_sep>/test.cc
#include"scy_test.h"
#include"mergesort.h"
#include"Insertsort.h"
#include<iostream>
#include<algorithm>
using namespace std;
using namespace scy_test;

int main(int argc, const char *argv[])
{
	const int NUM = 10;
	vector<RandomArray<int> > randvec(NUM);

	{
		timer t("mergesort");
		for(int i = 0; i < NUM; ++i)
		{
			vector<int> iv = randvec[i].getUnsortedArray();
			mergesort(iv, 0, iv.size()-1);
			IsSorted(iv);
		}
		/*
		RandomArray<int> arr(40,1000);
		auto iv = arr.getUnsortedArray();
		mergesort(iv, 0, iv.size()-1);
		IsSorted(iv);
		*/
	}

	{
		timer t("std::sort");
		for(int i = 0; i < NUM; ++i)
		{
			vector<int> iv = randvec[i].getUnsortedArray();
			sort(iv.begin(),iv.end());
			IsSorted(iv);
		}
	}

	{
		timer t("std::stable_sort");
		for(int i = 0; i < NUM; ++i)
		{
			vector<int> iv = randvec[i].getUnsortedArray();
			stable_sort(iv.begin(),iv.end());
			IsSorted(iv);
		}
	}

	{
		timer t("insertsort");
		//RandomArray<int> arr(40,1000);
		for(int i = 0; i < NUM; ++i)
		{
			vector<int> iv = randvec[i].getUnsortedArray();
			Insertsort(iv, iv.size());
			IsSorted(iv);
		}
	}
	{
		timer t("insertsort recursious");
		for(int i = 0; i < NUM; ++i)
		{
			vector<int> iv = randvec[i].getUnsortedArray();
			InsertsortR(iv, iv.size() - 1, iv.size());
			IsSorted(iv);
		}
		/*
		RandomArray<int> arr(40,1000);
		auto iv = arr.getUnsortedArray();
		InsertsortR(iv, iv.size() - 1, iv.size());
		IsSorted(iv);
		*/
	}
	return 0;
}
<file_sep>/README.md
##CppTest
* 打印运行调试信息
```c++
    scy_test::Print(vec);
```
* 记录比较函数运行时间
```c++
    {
      scy_test::timer t("myquicksort");
      myqsort(A);
    }

    /*输出
    -------------------------
    myquicksort
    running time : 2.15ms
    -------------------------
    */
```
* 快速成成随机数据
```c++
    RandomArray<int> randarry(40,1000);  // 1000以内 40个未排序数组
    vector<int> iv = randarry.getUnsortedArray(); //iv 是随生成的未排序数组
```

<file_sep>/Insertsort.h
#include"scy_test.h"
/**********************************************
*	insert sort
***********************************************/
template<typename T>
void Insertsort(T& A, int len)
{
	if(len <= 1)
		return;
	for(int i = 1; i < len; ++i)
	{
		auto key = A[i];
		int k = i-1;  //insert A[i] into sorted queue A[0 --- j-1]
		while(k>=0 && key<=A[k])
		{
			A[k+1] = A[k];
			k--;
		}
		A[k+1] = key;
//		scy_test::Print(A);
	}
}

/**********************************************
*	insert sort recursively
***********************************************/
template<typename T>
void InsertsortR(T& A, int k, int len)
{
	if(len <= 1)
		return;
	if(k == 0)
		return;
	InsertsortR(A, k-1, len);
	auto key = A[k];
	int i = k-1;
	while(key<A[i] && i>=0)
	{
		A[i+1] = A[i];
		i--;
	}
	A[i+1] = key;
//	scy_test::Print(A);
}
<file_sep>/scy_test.h
/************************************************
 * filename	:  scy_test.h
 * author	:  songcy
 * email	:  <EMAIL>
 * last modified :  2014-10-01 11:09
 * description	:
************************************************/
#ifndef _SCY_TEST_H_
#define _SCY_TEST_H_

#include<iostream>
#include<cstdlib>
#include<vector>
#include<sys/time.h>
#include<climits>
#include<algorithm>
#include<string>

namespace scy_test
{

	/***************************
	*	judge wether the array is sorted
	***************************/
	template<typename T>
	bool IsSorted(std::vector<T> tv)
	{
		for(auto i = tv.begin()+1; i != tv.end(); ++i)
		{
			if(*i < *(i-1))
			{
#ifndef NOTEST
				std::cout<< *i <<" < " <<*(i-1)<<std::endl;
				std::cout<<" unsorted ! "<<std::endl;
#endif
				return false;
			}
		}
		return true;
	}

	/***************************
	*	print info
	***************************/
	inline void Print(const char * str)
	{
#ifndef NOTEST
		std::cout<<str<<std::endl;
#endif
	}
	template<typename T>
	inline void Print(T &t)
	{
#ifndef NOTEST
		std::cout<< t <<std::endl;
#endif
	}

	template<typename T>
	inline void Print(T t[], size_t len)
	{
#ifndef NOTEST
		for(size_t i = 0; i < len; ++i)
			std::cout<<t[i]<<" ";
		std::cout<<std::endl;
#endif
	}
	template<typename T>
	inline void Print(std::vector<T> iv)
	{
#ifndef NOTEST
		for(auto i = iv.begin(); i != iv.end(); ++i)
			std::cout<<*i<<" ";
		std::cout<<std::endl;
#endif
	}

	/***************************
	*  record function's running time
	*  example:
	*  {
	*  		timer t("quicksort");
	*  		funtion code...
	*  	}
	***************************/
	class timer
	{
	public:
		timer(const char *info_):
			starttime(0),
			endtime(0),
			info(info_)
		{
			gettimeofday(&tv,NULL);
			starttime = tv.tv_sec * 1000 + tv.tv_usec/1000;
			std::cout<<"--------------------------"<<std::endl;
			std::cout<<"- \" "<<info<<" \""<<std::endl;
		}
		~timer()
		{
			gettimeofday(&tv,NULL);
			endtime = tv.tv_sec*1000 + tv.tv_usec/1000;
			std::cout<<"- running time : "<<endtime-starttime<<" ms "<<std::endl;
			std::cout<<"--------------------------"<<std::endl;
		}
	private:
		struct timeval tv;  //to create time in 0.001s
		time_t starttime;
		time_t endtime;
		std::string info;
	};

	/***************************
	*  create
	*  unsorted/nearsorted/sorted/rsorted
	*  array for sort functions
	***************************/

	template<typename T>
	class RandomArray
	{
	public:
		RandomArray(size_t size, int mval = INT_MAX):
			unsortedvec(std::vector<T>(size)),
			nearlysortedvec(std::vector<T>(size)),
//			tlist(list<T>(size)),
			size(size),
			max_value(mval)
		{
//			t = new T[size];
			srand((unsigned)time(NULL));
			createDataRandomly();
		}
		RandomArray():
			unsortedvec(std::vector<T>(defaultsize)),
			nearlysortedvec(std::vector<T>(defaultsize)),
//			tlist(list<T>(1)),
			size(defaultsize),
			max_value(INT_MAX)
		{
//			t = new T[1];
			srand((unsigned int)time(NULL));
			createDataRandomly();
		}
		~RandomArray() { }

		// not return & to protect datas' order in class
		std::vector<T> getUnsortedArray() {  return unsortedvec; }
		std::vector<T> getNearlysortedArray(){ return nearlysortedvec;}
		std::vector<T> getSortedArray(){ return sortedvec;}
		std::vector<T> getRsortedArray(){ return sortedvec;}

	private:
		void createDataRandomly()
		{
			for(size_t i = 0; i < size; ++i)
			{
				unsortedvec[i] = rand() % max_value;
				/*
				std::cout<<tvec[i]<<" -------log info";
				std::cout<<"\n";
				*/
			}
			sortedvec = unsortedvec;
			std::sort(sortedvec.begin(), sortedvec.end());
			rsortedvec = sortedvec;
			std::reverse(rsortedvec.begin(), rsortedvec.end());
			int extend_value = 0;
			int scope = 200;  //random in range (a ,a+200)
			for(int i = 0; i < size ; ++i)
			{
				nearlysortedvec[i] = (rand() % max_value ) % scope + extend_value;
				if( i % 30 == 0)
					extend_value += scope;
			}
		}
		RandomArray(const RandomArray &);
		RandomArray& operator=(const RandomArray &);
		std::vector<T> unsortedvec;
		std::vector<T> nearlysortedvec;
		std::vector<T> sortedvec;
		std::vector<T> rsortedvec;
//		T * t;
//		list<T> tlist;
		size_t size;
		const int max_value;
		static const int defaultsize = 10000;
//		static unsigned randseed;
	};

	/**********************************************
	 * TODO:create binary tree
	 ***********************************************/
	template<typename T>
	class Node
	{
		public:
			Node *left;
			Node *right;
			T val;
	};
	template<typename T>
	class BinaryTree
	{
		public:
			void traverseTree(void (*fun)());
			size_t size()
			{
				return node_count;
			}
			BinaryTree(size_t nodenum, int max):
				node_count(nodenum),
				maxval(max),
				nodevec(0)
			{
				createRandomBinaryTree();
			}
			~BinaryTree()
			{
				for(int i = 0; i < nodevec.size(); ++i)
					delete nodevec[i];
			}
			Node<T>* getRoot()
			{
				return root;
			}
			void printBinaryTree()
			{
				int count = 0;
				traverseTree(root, count);
			}
		private:
			void createRandomBinaryTree()
			{
				int count = 0;
				RandomArray<int> randarray(node_count, maxval);
				std::vector<int> ivec =  randarray.getUnsortedArray();
				root = new Node<T>;
				root->left = root->right = NULL;
				root->val = ivec[0];
				createRandomBinaryTreeChild(root, ivec, 1);
			}

			void createRandomBinaryTreeChild(Node<T> *node, std::vector<int>& ivec, int index)
			{
				std::cout<<"index: "<<index<<std::endl;
				if(index >= ivec.size()-1)
					return;
				int ranleft = rand()%2;
				int ranright = rand()%2;
				if(ranleft == 0)
				{
					Node<T> *newnode = new Node<T>;
					nodevec.push_back(newnode);
					newnode->val = ivec[index];
					newnode->left = NULL;
					newnode->right = NULL;
					node->left = newnode;
					createRandomBinaryTreeChild(node->left, ivec, index+1);
					index++;
				}
				if(ranright == 0)
				{
					Node<T> *newnode = new Node<T>;
					nodevec.push_back(newnode);
					newnode->val = ivec[index];
					newnode->left = NULL;
					newnode->right = NULL;
					node->right = newnode;
					createRandomBinaryTreeChild(node->right, ivec, index+1);
				}
			}
			void traverseTree(Node<T>* node,int count)
			{
				if(node == NULL)
					return;

				if(node->left)
					std::cout<<node->left->val<<"<-";
				else
					std::cout<<"NULL<-";
				std::cout<<node->val;
				if(node->right)
					std::cout<<"->"<<node->right->val;
				else
					std::cout<<"->NULL";
				std::cout<<"\t";
				printf("deep =  %d\n",count);

				count++;
				traverseTree(node->left,count);
				traverseTree(node->right,count);

			}
//			void createSortedBinaryTree();  //TODO
//			void createFullBinaryTree();    //TODO
			std::vector< Node<T>* > nodevec;
			size_t node_count;
			int maxval;
			Node<T> *root;
	};

}

#endif
<file_sep>/mergesort.h
#ifndef _MERGESORT_H_
#define _MERGESORT_H_

#include"scy_test.h"
#include<cassert>
#include<algorithm>

template<typename T>
void mymerge(T& A, int p, int q, int r,T& B)
{
	int k = p;
	int i = p;
	int j = q + 1;
	for( ; i<=q && j<=r; ++k)
	{
		if(A[i] < A[j])
			B[k] = A[i++];
		else
			B[k] = A[j++];
	}
	if(i <= q)
		for(int l = 0; l <= q-i; ++l)
			B[k+l] = A[i+l];
	if(j <= r)
		for(int l = 0; l <= r-j; ++l)
			B[k+l] = A[j+l];

}

template<typename T>
void mergesort(T& A, int left, int right)
{
	static T B = T(A.size(),0);
	if(left >= right)
		return;
	int i = (left + right)/2;
	mergesort(A, left, i);
	mergesort(A, i + 1, right);
	mymerge(A, left, i, right, B);
	std::copy(B.begin() + left, B.begin() + right +1, A.begin() + left);
}
#endif

languages: Markdown C++