text:
<repo_name>GoIany/GuitarAssistant<file_sep>/app/src/main/java/com/poly/GuitarAssistant/Instrument/UserAdapter.java
package com.poly.GuitarAssistant.Instrument;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

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

import com.poly.GuitarAssistant.R;

import java.util.ArrayList;

public class UserAdapter extends RecyclerView.Adapter<UserAdapter.CustomViewHolder> {

    private ArrayList<PersonalData> mList = null;
    private Activity context = null;
    public Context acontext;

    public UserAdapter(Activity context, ArrayList<PersonalData> list) {
        this.context = context;
        this.mList = list;
        acontext = context;
    }
    class CustomViewHolder extends RecyclerView.ViewHolder {
        protected ImageView file_path;
        protected TextView name;
        protected TextView company;
        protected TextView price;
        protected TextView store;
        protected TextView price2;
        protected TextView store2;
        protected TextView price3;
        protected TextView store3;
        protected TextView price4;
        protected TextView store4;
        protected LinearLayout Linear_link;
        protected LinearLayout Linear_link2;
        protected LinearLayout Linear_link3;
        protected LinearLayout Linear_link4;

        public CustomViewHolder(View view) {
            super(view);
            /*
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.d("태그", "onClick: "+getAdapterPosition());
                    String s1 = store.getText().toString()+price.getText().toString(),
                            s2 = store2.getText().toString()+price2.getText().toString(),
                            s3 = store3.getText().toString()+price3.getText().toString(),
                            s4 = store4.getText().toString()+price4.getText().toString();
                    coustemDialog cd = new coustemDialog(acontext,name.getText().toString(),s1,s2,s3,s4,getAdapterPosition(),acontext);
                    cd.show();

                }
            });

             */
            this.file_path = (ImageView) view.findViewById(R.id.imageView_list_imgurl);
            this.name = (TextView) view.findViewById(R.id.textView_list_name);
            this.company = (TextView) view.findViewById(R.id.textView_list_company);
            this.price = (TextView) view.findViewById(R.id.textView_list_price);
            this.store = (TextView) view.findViewById(R.id.textView_list_store);
            this.price2 = (TextView) view.findViewById(R.id.textView_list_price2);
            this.store2 = (TextView) view.findViewById(R.id.textView_list_store2);
            this.price3 = (TextView) view.findViewById(R.id.textView_list_price3);
            this.store3 = (TextView) view.findViewById(R.id.textView_list_store3);
            this.price4 = (TextView) view.findViewById(R.id.textView_list_price4);
            this.store4 = (TextView) view.findViewById(R.id.textView_list_store4);
            Linear_link = (LinearLayout)view.findViewById(R.id.Linear_link);
            Linear_link2 = (LinearLayout)view.findViewById(R.id.Linear_link2);
            Linear_link3 = (LinearLayout)view.findViewById(R.id.Linear_link3);
            Linear_link4 = (LinearLayout)view.findViewById(R.id.Linear_link4);
            Linear_link.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View view) {
                    if(mList.get(getAdapterPosition()).getMember_link() != "") {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(mList.get(getAdapterPosition()).getMember_link()));
                        context.startActivity(intent);
                    }
                }
            });
            Linear_link2.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View view) {
                    if(mList.get(getAdapterPosition()).getMember_link2() != "") {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(mList.get(getAdapterPosition()).getMember_link2()));
                        context.startActivity(intent);
                    }
                }
            });
            Linear_link3.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View view) {
                    if(mList.get(getAdapterPosition()).getMember_link3() != "") {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(mList.get(getAdapterPosition()).getMember_link3()));
                        context.startActivity(intent);
                    }
                }
            });
            Linear_link4.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View view) {
                    if(mList.get(getAdapterPosition()).getMember_link4() != "") {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(mList.get(getAdapterPosition()).getMember_link4()));
                        context.startActivity(intent);
                    }
                }
            });

        }
    }

    @Override
    public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_list, null);
        CustomViewHolder viewHolder = new CustomViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull CustomViewHolder viewholder, int position) {

        viewholder.name.setText(mList.get(position).getMember_name());
        viewholder.company.setText(mList.get(position).getMember_company());
        viewholder.price.setText(mList.get(position).getMember_price());
        viewholder.store.setText(mList.get(position).getMember_store());
        viewholder.price2.setText(mList.get(position).getMember_price2());
        viewholder.store2.setText(mList.get(position).getMember_store2());
        viewholder.price3.setText(mList.get(position).getMember_price3());
        viewholder.store3.setText(mList.get(position).getMember_store3());
        viewholder.price4.setText(mList.get(position).getMember_price4());
        viewholder.store4.setText(mList.get(position).getMember_store4());

        GlideApp.with(viewholder.itemView).load(mList.get(position).getMember_file_path())
                .override(150,150).into(viewholder.file_path);
    }

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

}<file_sep>/app/src/main/java/com/poly/GuitarAssistant/Lecture/tong1.java
package com.poly.GuitarAssistant.Lecture;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.poly.GuitarAssistant.GuitarChord.UnderbarMenu;
import com.poly.GuitarAssistant.R;

import java.util.ArrayList;

public class tong1 extends AppCompatActivity implements FrameLayout.OnClickListener {
    FrameLayout startBtn, stopBtn, button;
    ViewFlipper viewFlipper;
    ImageView img_lecture1,img_lecture2,img_lecture3;
    ListView listView;
    SingerAdapter adapter;
    TextView lecture_Title;
    UnderbarMenu underbarMenu;
    @Override
    protected void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_tong1);
        listView = findViewById(R.id.listview);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setCustomView(R.layout.lecture_bar_layout);
        lecture_Title = findViewById(R.id.lecture_title);

        Resources res = getResources();
        img_lecture1 = findViewById(R.id.img_lecture_1);
        img_lecture2 = findViewById(R.id.img_lecture_2);
        img_lecture3 = findViewById(R.id.img_lecture_3);
        img_lecture1 .setColorFilter(res.getColor(R.color.lecture_icon_color));
        img_lecture2.setColorFilter(res.getColor(R.color.lecture_icon_color));
        img_lecture3.setColorFilter(res.getColor(R.color.lecture_icon_color));

        adapter = new SingerAdapter();

        startBtn = findViewById(R.id.let1);
        stopBtn = findViewById(R.id.let2);
        button = findViewById(R.id.let3);
        viewFlipper = findViewById(R.id.viewFlipper);

        startBtn.setOnClickListener(this);
        stopBtn.setOnClickListener(this);
        button.setOnClickListener(this);

        underbarMenu = findViewById(R.id.UnderBarMenu2);
        underbarMenu.setActivity(this);
        underbarMenu.setFlipperAct2(viewFlipper);
    }

    class SingerAdapter extends BaseAdapter {
        ArrayList<SingerItem> items = new ArrayList<SingerItem>();
        @Override
        public int getCount() {
            return items.size();
        }

        public void addItem(SingerItem item) {
            items.add(item);
        }

        public void deleteItem(){
            items.clear();
        }

        @Override
        public Object getItem(int position) {
            return items.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            SingerItemView singerItemView = null;
            if(convertView == null){
                singerItemView = new SingerItemView(getApplicationContext());
            }
            else{
                singerItemView = (SingerItemView)convertView;
            }
            SingerItem item = items.get(position);
            singerItemView.setName(item.getName());
            singerItemView.setMobile(item.getMobile());
            singerItemView.setImage(item.getResId());
            return singerItemView;
        }
    }
    @Override
    public void onClick(View v) {
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id ) {
                SingerItem item=(SingerItem)adapter.getItem(position);
                Intent mInternet = new Intent(Intent.ACTION_VIEW, Uri.parse(item.getUrl()));
                startActivity(mInternet);
            }
        });
        switch(v.getId())
        {
            case R.id.let1:
                listView.clearChoices();
                adapter.notifyDataSetChanged();
                adapter.deleteItem();
                listView.setAdapter(adapter);
                tongbeginer();
                tongmiddle();
                tonghigh();
                viewFlipper.setDisplayedChild(1);
                lecture_Title.setText("통기타");
                break;

            case R.id.let2:
                listView.clearChoices();
                adapter.notifyDataSetChanged();
                adapter.deleteItem();
                listView.setAdapter(adapter);
                illbeginer();
                illmiddle();
                illhigh();
                viewFlipper.setDisplayedChild(1);
                lecture_Title.setText("일렉기타");
                break;
            case R.id.let3:
                listView.clearChoices();
                adapter.notifyDataSetChanged();
                listView.setAdapter(adapter);
                basebegin();
                basemiddle();
                basehigh();
                viewFlipper.setDisplayedChild(1);
                lecture_Title.setText("베이스");
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu01,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id ) {

                SingerItem item=(SingerItem)adapter.getItem(position);
                Intent mInternet = new Intent(Intent.ACTION_VIEW, Uri.parse(item.getUrl()));
                startActivity(mInternet);
            }
        });

        viewFlipper.setDisplayedChild(1);
        switch(item.getItemId())
        {
            case R.id.all:
                adapter.deleteItem();
                listView.setAdapter(adapter);
                tongbeginer();
                tongmiddle();
                tonghigh();
                illbeginer();
                illmiddle();
                illhigh();
                basebegin();
                basemiddle();
                basehigh();
                lecture_Title.setText("강의영상");
                break;
            case R.id.base1:
                adapter.deleteItem();
                listView.setAdapter(adapter);
                basebegin();
                lecture_Title.setText("베이스-초급");
                break;
            case R.id.base2:
                adapter.deleteItem();
                listView.setAdapter(adapter);
                basemiddle();
                lecture_Title.setText("베이스-중급");
                break;
            case R.id.base3:
                adapter.deleteItem();
                listView.setAdapter(adapter);
                basehigh();
                lecture_Title.setText("베이스-고급");
                break;
            case R.id.tong1:
                adapter.deleteItem();
                listView.setAdapter(adapter);
                tongbeginer();
                lecture_Title.setText("통기타-초급");
                break;
            case R.id.tong2:
                adapter.deleteItem();
                listView.setAdapter(adapter);
                tongmiddle();
                lecture_Title.setText("통기타-중급");
                break;
            case R.id.tong3:
                adapter.deleteItem();
                listView.setAdapter(adapter);
                tonghigh();
                lecture_Title.setText("통기타-고급");
                break;
            case R.id.ill1:
                adapter.deleteItem();
                listView.setAdapter(adapter);
                illbeginer();
                lecture_Title.setText("일렉기타-초급");
                break;
            case R.id.ill2:
                adapter.deleteItem();
                listView.setAdapter(adapter);
                illmiddle();
                lecture_Title.setText("일렉기타-중급");
                break;
            case R.id.ill3:
                adapter.deleteItem();
                listView.setAdapter(adapter);
                illhigh();
                lecture_Title.setText("일렉기타-고급");
                break;
        }
        return super.onOptionsItemSelected(item);

    }

    @Override
    public void onBackPressed() {
        if( (viewFlipper.getDisplayedChild() == 1)){
            listView.clearChoices();
            adapter.notifyDataSetChanged();
            adapter.deleteItem();
            listView.setAdapter(adapter);
            viewFlipper.setDisplayedChild(0);
            lecture_Title.setText("강의영상");
        }else{
            AlertDialog.Builder builder = new AlertDialog.Builder(this);

            builder.setTitle("종료 하시겠습니까");

            builder.setPositiveButton("예", new DialogInterface.OnClickListener(){
                @Override
                public void onClick(DialogInterface dialog, int id)
                {
                    finish();
                }
            });

            builder.setNegativeButton("아니오", new DialogInterface.OnClickListener(){
                @Override
                public void onClick(DialogInterface dialog, int id)
                {
                }
            });
            builder.show();
        }
    }

    public void tongbeginer(){
        adapter.addItem(new SingerItem("기타 튜닝(조율)하기","\n채널:꿀잼기타\n        Honeyjam guitar",R.drawable.c1,"https://youtu.be/f0UREMH4s7E"));
        adapter.addItem(new SingerItem("왕초보를 위한\n통기타 강좌","채널:꿀잼기타\n        Honeyjam guitar",R.drawable.c2,"https://youtu.be/1CKOrteG3TA"));
        adapter.addItem(new SingerItem("칼립소 주법","\n채널:꿀잼기타\n        Honeyjam guitar",R.drawable.c3,"https://youtu.be/uhWp4KdJ2q8"));
        adapter.addItem(new SingerItem("악센트 연주하는법","\n 채널:꿀잼기타\n        Honeyjam guitar",R.drawable.c4,"https://youtu.be/xC9Z_AF2V-g"));

    }
    public void tongmiddle(){
        adapter.addItem(new SingerItem("통기타 더블 스트로크","\n채널:딩기리닷컴",R.drawable.c5,"https://youtu.be/XIkV1tNRVrs"));
        adapter.addItem(new SingerItem("해머링 온, 풀링 오프","\n채널:Grab the Guitar",R.drawable.c6,"https://youtu.be/Lkiz7WR8RYY"));
        adapter.addItem(new SingerItem("오른손 커팅|왼손 커팅 방법","\n채널:Grab the Guitar",R.drawable.c7,"https://youtu.be/7oC8ZLrkMr0"));
        adapter.addItem(new SingerItem("바레코드 완전 정복","\n채널:Grab the Guitar",R.drawable.c8,"https://youtu.be/w7M7vubClJc"));

    }
    public void tonghigh(){
        adapter.addItem(new SingerItem("퍼커시브 주법","\nGrab the Guitar",R.drawable.c9,"https://youtu.be/YDuIYNx9GQA"));
        adapter.addItem(new SingerItem("핑거스타일 연주\n(메이플스토리ost)","\nTongdangi 통단기",R.drawable.c10,"https://youtu.be/xChEHnQkyQE"));
        adapter.addItem(new SingerItem("핑거스타일 연주\n(Flower Dance)","\nTongdangi 통단기",R.drawable.c11,"https://youtu.be/nY2NXRLugpo"));
        adapter.addItem(new SingerItem("핑거스타일 연주 \n황혼 Twilight","\nTongdangi 통단기",R.drawable.c12,"https://youtu.be/eARJISQA1JQ"));
    }
    public void illbeginer() {

        adapter.addItem(new SingerItem("일렉기타, 코드 스트로크", "\nEmotional Guitarist AZ", R.drawable.c13, "https://youtu.be/TOLY6F1iJCs"));
        adapter.addItem(new SingerItem("일렉기타, 코드 아르페지오", "\nEmotional Guitarist AZ", R.drawable.c14, "https://youtu.be/Y8iH5kXBgfg"));
        adapter.addItem(new SingerItem("일렉기타, 커팅주법", "\nEmotional Guitarist AZ", R.drawable.c15, "https://youtu.be/K9EYda-M_1Y"));
        adapter.addItem(new SingerItem("일렉기타, 슬라이드", "\nEmotional Guitarist AZ", R.drawable.c16, "https://youtu.be/4uIvLopffJg"));
    }
    public void illmiddle(){
        adapter.addItem(new SingerItem("피킹하모닉스","\nEmotional Guitarist AZ",R.drawable.c17,"https://youtu.be/MBeIy9zI-tk"));
        adapter.addItem(new SingerItem("메이저 스케일","\nEmotional Guitarist AZ",R.drawable.c18,"https://youtu.be/VgPSNudlxts"));
        adapter.addItem(new SingerItem("펜타토닉 스케일","\nEmotional Guitarist AZ",R.drawable.c19,"https://youtu.be/W07tLZasgXQ"));
        adapter.addItem(new SingerItem("일레기타 테크닉,옥타브 주법","\nEmotional Guitarist AZ",R.drawable.c20,"https://youtu.be/hn1PXfoUPnc"));

    }
    public void illhigh(){

        adapter.addItem(new SingerItem("스윕 피킹","\nEmotional Guitarist AZ",R.drawable.c21,"https://youtu.be/2hjE5yfJd2I"));
        adapter.addItem(new SingerItem("테핑 (Triptych 태핑 레슨)","\nEmotional Guitarist AZ",R.drawable.c22,"https://youtu.be/o8N7kqfBzsA"));
        adapter.addItem(new SingerItem("라이크 주법","\nEmotional Guitarist AZ",R.drawable.c23,"https://youtu.be/2HXJMJFOKMU"));
        adapter.addItem(new SingerItem("아밍","\nEmotional Guitarist AZ",R.drawable.c24,"https://youtu.be/_yzeqIBo43c"));
    }
    public void basebegin(){
        adapter.addItem(new SingerItem("베이스 기초레슨","채널:ADAM TV Music Studio",R.drawable.c25,"https://youtu.be/VBMMGvwnwJM"));
        adapter.addItem(new SingerItem("베이스기타 악보의 \n종류와 보는법","채널:손록손록",R.drawable.c26,"https://youtu.be/IBwHGxJF9P4"));
        adapter.addItem(new SingerItem("크로매틱 연습","채널:Yc Bass",R.drawable.c27,"https://youtu.be/fazraiIhOwo"));
        adapter.addItem(new SingerItem("슬라이드 & 글리산도","채널:Guitarcamp 기타캠프",R.drawable.c28,"https://youtu.be/KLpH8AE6kHM"));
    }

    public void basemiddle(){
        adapter.addItem(new SingerItem("지판(계이름) 빨리외우는 \n방법","\n채널:Yc Bass",R.drawable.c29,"https://youtu.be/K3_RYEuP0K0"));
        adapter.addItem(new SingerItem("핑거루프","\n채널:Yc Bass",R.drawable.c30,"https://youtu.be/S0REaGpe_F"));
        adapter.addItem(new SingerItem("슬랩 초보 탈출","\n채널:베이스의선율",R.drawable.c31,"https://youtu.be/EArHofnr_Lo"));
        adapter.addItem(new SingerItem("4화음 코드(CM7, C7)","\n채널:베이스의선율",R.drawable.c32,"https://youtu.be/EOzrkEOfbPs"));

    }
    public void basehigh(){
        adapter.addItem(new SingerItem("필인 가이드","\n채널:ADAM TV Music Studio",R.drawable.c33,"https://youtu.be/NkTCqk3cqeI"));
        adapter.addItem(new SingerItem("슬랩연주","\n채널:쟈횽",R.drawable.c34,"https://youtu.be/HS50mCFWwok"));
        adapter.addItem(new SingerItem("스케일 활용 및 연습방법","\n채널:베이시스트안성진.",R.drawable.c35,"https://youtu.be/XJwcJB2mS5U"));
        adapter.addItem(new SingerItem("메이져 펜타토닉","\n채널:우선생의베이스아카데미",R.drawable.c36,"https://youtu.be/2baW_IXw4V4"));
    }

}<file_sep>/app/src/main/java/com/poly/GuitarAssistant/GuitarChord/GuitarFretView.java
package com.poly.GuitarAssistant.GuitarChord;

import android.content.Context;
import android.content.res.Resources;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.poly.GuitarAssistant.R;

public class GuitarFretView extends HorizontalScrollView {

    boolean inti = true;
    int fretBetween, fretWidth;

    public GuitarFretView(Context context) {
        super(context);
    }

    public GuitarFretView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public GuitarFretView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if(inti){
            fretWidth = (int) getResources().getDimension(R.dimen.GuitarFretWidth);
            //프렛간 거리 초기화
            Resources res = getResources();
            fretBetween = (int) ((this.getWidth() - res.getDimension(R.dimen.GuitarFretSideMargin)*2 - res.getDimension(R.dimen.GuitarFretWidth)*5 )/4);

            LinearLayout linearLayout = (LinearLayout) this.getChildAt(0);
            int tvCount = (linearLayout.getChildCount()-3)/2;
            int count = 2;

            for(int c=0; c<tvCount; c++){
                TextView tv = (TextView) linearLayout.getChildAt(count);
                ViewGroup.LayoutParams params =  tv.getLayoutParams();
                params.width = fretBetween;
                tv.setLayoutParams(params);
                count += 2;
            }
            inti = false;
        }
    }

    public  void setFret(int fret){
        if(fret > 21)
            fret = 21;
        smoothScrollTo((fret-1)*(fretWidth + fretBetween),0);
    }

    //스크롤 제한
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return true;
    }

}
<file_sep>/app/src/main/java/com/poly/GuitarAssistant/GuitarChord/BtnChordSelecter.java
package com.poly.GuitarAssistant.GuitarChord;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.poly.GuitarAssistant.R;

public class BtnChordSelecter extends LinearLayout{
    TextView chordTv;
    Boolean selcectingRoot = true;
    String rootChord = "C", typeChord = "maj", rootSide = "";
    final String mType[] = {"m", "m6", "mb6", "m7", "mmaj7", "m7b5", "m9", "m11","7", "7b5", "7#5", "7b9","maj", "maj7", "maj79", "6", "dim7", "9", "69", "11", "5", "dim"};
    LinearLayout linearLayout;
    ChordChanged chordChanged = null;

    interface ChordChanged{
        void chordChange(String chord, boolean type);
    }

    public void setChordChanged(ChordChanged c){
        chordChanged = c ;
    }

    public BtnChordSelecter(Context context) {
        super(context);
        init(context);
    }

    public BtnChordSelecter(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public BtnChordSelecter(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public void init(Context context){
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        linearLayout = (LinearLayout) ( (LinearLayout) inflater.inflate(R.layout.btnselecter_layout,this) ).getChildAt(0);

        chordTv = (TextView) linearLayout.getChildAt(0);
        TableLayout tableLayout = (TableLayout) linearLayout.getChildAt(1);

        for(int c1=0; c1 < tableLayout.getChildCount(); c1++){
            TableRow tableRow = (TableRow) tableLayout.getChildAt(c1);
            for(int c2=0; c2 < tableRow.getChildCount(); c2++){
                Button button = (Button) tableRow.getChildAt(c2);
                String btnString = button.getText().toString();
                Drawable drawable = getResources().getDrawable(R.drawable.btn_root_round);
                View.OnClickListener onClickListener;

                if(btnString.equals("sus2/4") || btnString.equals("b/#")){
                    onClickListener = new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            specialSelected( (String) ((Button) v).getText() );
                        }
                    };
                }else if(drawable.getConstantState().equals(button.getBackground().getConstantState() ) ){
                    onClickListener = new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            rootChordSelected( (String) ((Button) v).getText() );
                        }
                    };
                }else{
                    onClickListener = new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            typeChordSelected( (String) ((Button) v).getText() );
                        }
                    };
                }
                button.setOnClickListener(onClickListener);
            }
        }

    }

    public void setChord(String rootside,String type){
        if(rootside.endsWith("#"))
            rootSide = "#";
        rootChord = rootside.replace("#","");

        switch (type){
            case "Major":
                typeChord = "maj";
                break;
            case "maj7/9":
                typeChord = "maj79";
                break;
            case "m(maj7)":
                typeChord = "mmaj7";
                break;
            case "6/9":
                typeChord = "69";
                break;
            default:
                typeChord = type;
        }

        chordTv.setText(rootChord+rootSide+" "+type);
    }

    public String[] getChord(){
        String[] s = {"",""};
        if(rootSide.equals("b")){
            switch (rootChord){
                case "D":
                    s[0]="C#";
                    break;
                case "E":
                    s[0]="D#";
                    break;
                case "G":
                    s[0]="F#";
                    break;
                case "A":
                    s[0]="G#";
                    break;
                case "B":
                    s[0]="A#";
                    break;
            }
        }else
            s[0]=rootChord+rootSide;

        switch (typeChord){
            case "maj":
                s[1] = "Major";
                break;
            case "maj79":
                s[1] = "maj7/9";
                break;
            case "mmaj7":
                s[1] = "m(maj7)";
                break;
            case "69":
                s[1] = "6/9";
                break;
            default:
                s[1] = typeChord;
        }
        return s;
    }

    public void rootChordSelected(String chord){
        selcectingRoot = true;
        String mChord = (String) chordTv.getText();
        mChord = mChord.replace(rootChord+rootSide,chord+"");

        rootChord = chord;
        rootSide = "";

        chordTv.setText(mChord);
        chordChanged.chordChange(rootChord,PajiSelecter.main);
    }

    public void typeChordSelected(String chord){
        selcectingRoot = false;
        if(     chord.equals("add9") ||
                chord.equals("13") ||
                chord.equals("aug")) {
            typeChord = chord;
            chordTv.setText(rootChord + rootSide + " " + typeChord);
            chordChanged.chordChange(typeChord,PajiSelecter.side);
        }else{
            isChordPossible(chord);
        }

    }

    public void isChordPossible(String chord){
        String s = typeChord + chord;

        for(int c=0; c<mType.length; c++){
            if(mType[c].startsWith(s)){
                typeChord = s;

                for(int cc=c; cc<mType.length; cc++){
                    if(mType[cc].equals(s)){
                        switch (typeChord){
                            case "maj":
                                chordTv.setText(rootChord+rootSide+" Major");
                                chordChanged.chordChange("Major", PajiSelecter.side);
                                break;
                            case "maj79":
                                chordTv.setText(rootChord+rootSide+" maj7/9");
                                chordChanged.chordChange("maj7/9", PajiSelecter.side);
                                break;
                            case "mmaj7":
                                chordTv.setText(rootChord+rootSide+" m(maj7)");
                                chordChanged.chordChange("m(maj7)", PajiSelecter.side);
                                break;
                            case "69":
                                chordTv.setText(rootChord+rootSide+" 6/9");
                                chordChanged.chordChange("6/9", PajiSelecter.side);
                                break;
                            default:
                                chordTv.setText(rootChord+rootSide+" "+typeChord);
                                chordChanged.chordChange(typeChord, PajiSelecter.side);
                        }
                        return;
                    }
                }
                chordTv.setText(rootChord+rootSide+" "+typeChord);
                return;
            }
        }
        typeChord = chord;
        if(typeChord.equals("maj")){
            chordTv.setText(rootChord+rootSide+" Major");
            chordChanged.chordChange("Major", PajiSelecter.side);
        }else if( typeChord.equals("m") ||
                typeChord.equals("6") ||
                typeChord.equals("7") ||
                typeChord.equals("9") ||
                typeChord.equals("11") ||
                typeChord.equals("5")){
            chordTv.setText(rootChord+rootSide+" "+typeChord);
            //pajiSelecter.codeChanged(typeChord,PajiSelecter.side);
            chordChanged.chordChange(typeChord, PajiSelecter.side);
        }else
            chordTv.setText(rootChord+rootSide+" "+typeChord);

    }

    public void specialSelected(String chord){
        String bSide = rootSide, bRoot = rootChord;

        if(chord.equals("sus2/4")){
            if(typeChord.equals("sus2"))
                typeChord = "sus4";
            else
                typeChord = "sus2";
            //pajiSelecter.codeChanged(typeChord,PajiSelecter.side);
            chordChanged.chordChange(typeChord, PajiSelecter.side);
            chordTv.setText(rootChord+rootSide+" "+typeChord);
        }else{
            if(selcectingRoot){
                if(     rootChord.equals("D") ||
                        rootChord.equals("G") ||
                        rootChord.equals("A")){
                    if(rootSide.equals("#"))
                        rootSide = "b";
                    else
                        rootSide = "#";
                }else if(rootChord.equals("C") ||
                        rootChord.equals("F")){
                    rootSide = "#";
                }else{
                    rootSide = "b";
                }
                if(rootSide.equals("b")){
                    switch (rootChord){
                        case "D":
                            chordChanged.chordChange("C#", PajiSelecter.main);
                            break;
                        case "E":
                            chordChanged.chordChange("D#", PajiSelecter.main);
                            break;
                        case "G":
                            chordChanged.chordChange("F#", PajiSelecter.main);
                            break;
                        case "A":
                            chordChanged.chordChange("G#", PajiSelecter.main);
                            break;
                        case "B":
                            chordChanged.chordChange("A#",PajiSelecter.main);
                            break;
                    }
                }else
                    chordChanged.chordChange(rootChord+rootSide,PajiSelecter.main);

                String mChord = (String) chordTv.getText();
                mChord = mChord.replace(bRoot+bSide,rootChord+rootSide);
                chordTv.setText(mChord);

                //chordTv.setText(rootChord+rootSide+" "+typeChord);
            }else{
                if(typeChord.equals("m"))
                    typeChord = "mb";
                else if(typeChord.equals("m7"))
                    typeChord = "m7b";
                else if(typeChord.equals("7#"))
                    typeChord = "7b";
                else if(typeChord.equals("7") ||
                        typeChord.equals("7b"))
                    typeChord = "7#";
                chordTv.setText(rootChord+rootSide+" "+typeChord);
            }
        }

    }

}

<file_sep>/app/src/main/java/com/poly/GuitarAssistant/GuitarChord/GuitarChordView.java
package com.poly.GuitarAssistant.GuitarChord;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class GuitarChordView extends FrameLayout {

    GuitarFretView guitarFretView;
    GuitarPajiView guitarPajiView;
    boolean init = true;

    public GuitarChordView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public GuitarChordView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

    }

    public GuitarChordView(@NonNull Context context) {
        super(context);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if(init) {
            guitarFretView = (GuitarFretView) this.getChildAt(1);
            guitarPajiView = (GuitarPajiView) this.getChildAt(2);
        }
    }

    public  void setLineDirection(Boolean direction){
        guitarPajiView.setLineDirection(direction);
    }

    public void GuitarPajiChanged(int paji, int line){
        //기타 파지 변경
        int p[] = {0,0,0,0};
        boolean l[] = {false, false, false, false, false, false,};
        int pow = 1000000000,
            pow2 = 10000;
        boolean first = true;

        if(guitarPajiView != null && guitarFretView != null) {
            //프렛 파지 디코드
            for (int c = 0; c < 4; c++) {
                int c1 = paji % pow / (pow / 100),
                    c2 = line % pow2 / (pow2 / 10) ;
                if (c1 != 99) {
                    if (first) {        //전체프랫
                        guitarFretView.setFret(paji%10*10 + c2);
                        first = false;
                    } else               //파지 프렛
                        p[c] += c2 * 100;
                    p[c] += c1;         //파지 대입
                }
                pow /= 100;
                pow2 /= 10;
            }

            // 라인 디코드
            pow = 1000000000;
            if(line / pow == 1)
                l[0] = true;
            for (int c = 1; c < 6; c++) {
                if (line % pow / (pow / 10) == 1)
                    l[c] = true;
                pow /= 10;
            }
            guitarPajiView.setPaji(p, l);
        }
    }

}

repo_name: GoIany/GuitarAssistant


text:
<repo_name>Shamakhi/Java_Additional_Exercise<file_sep>/L1-Extra/8.17/TicTacToe.java
import java.util.Random;

public class TicTacToe{
    private int players     = 0;
    private int winner      = 0;
    private int playerTurn  = 0;

    private enum GameStatus{INITIALISE, RUNNING, EXIT, WON, DRAW};

    Random randomGenerator = new Random();

    GameStatus gameStatus = GameStatus.INITIALISE;

    Board gameBoard = new Board();
    InputManager inputManager = new InputManager();
    Agent player1;
    Agent player2;

    public void setGameStatus(GameStatus gameStatus){
        this.gameStatus = gameStatus;
    }

    public GameStatus getGameStatus(){
        return this.gameStatus;
    }

    public void run(){
        while(getGameStatus() != GameStatus.EXIT){
            if(getGameStatus() == GameStatus.INITIALISE){
                if(initialise()){
                    setGameStatus(GameStatus.RUNNING);
                }
            }
            if(getGameStatus() == GameStatus.RUNNING){
                switch(playerTurn){
                    case 1:
                        player1.move();
                        checkWinCondition();
                        break;
                    case 2:
                        player2.move();
                        checkWinCondition();
                        break;
                }

                playerTurn = (playerTurn == 1) ? 2 : 1;
            }
        }
    }

    private boolean initialise(){
        reset();

        while(players == 0 && gameStatus != GameStatus.EXIT){
            printMenu();
        }
        if(players == 1){
            player1 = new Human(gameBoard, 1, inputManager);
            player2 = new Computer(gameBoard, 2);
        }
        if(players == 2){
            player1 = new Human(gameBoard, 1, inputManager);
            player2 = new Human(gameBoard, 2, inputManager);
        }

        playerTurn = 1 + randomGenerator.nextInt(2);
        return true;
    }

    private void printMenu(){
        System.out.println("\nWelcome to TicTacToe\n");
        System.out.println("1. PvC");
        System.out.println("2. PvP");
        System.out.println("0. Exit");
        System.out.print("> ");

        int choice = inputManager.getIntInput();

        if(choice == 0)
            setGameStatus(GameStatus.EXIT);
        else if(choice == 1 || choice == 2)
            players = choice;
        else
            System.out.println("Invalid menu entry. Try again.");
    }

    private void printEndStatus(){
        if(winner > 0)
            System.out.printf("\nCongratulations player %d won!!\n", winner);
        else
            System.out.println("\nGame ended in a draw\n");

        gameBoard.printBoard();
    }

    private void checkWinCondition(){

        if(gameBoard.checkVictory()){
            setGameStatus(GameStatus.WON);
            winner = gameBoard.getWinner();
        }
        if(gameBoard.checkDraw()){
            setGameStatus(GameStatus.DRAW);
        }

        if(getGameStatus() != GameStatus.RUNNING){
            printEndStatus();
            System.out.println("Play Again? (y/n)");
            System.out.print("> ");
            if(inputManager.getCharInput() == 'y'){
                reset();
                run();
            }else{
                setGameStatus(GameStatus.EXIT);
            }
        }
    }

    private void reset(){
        gameBoard.reset();

        gameStatus = GameStatus.RUNNING;
        players = 0;
        winner = 0;
        playerTurn = 0;
    }
}
<file_sep>/L0-Extra/E2/src/com/company/Main.java
package com.company;
import java.util.*;
public class Main {

    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        int a;
        System.out.println("enter a");
        a=input.nextInt();
        if(a>5){
            System.out.println("a is bigger than 5");

        }
        else if(a>10){
            System.out.println(" a is bigger than 10 too");
        }

	// write your code here
    }
}
<file_sep>/README.md
# Java_Additional_Exercise
Java Uni Exercises(naiau)

branch_name: refs/heads/master

languages: Java Markdown

repo_language: Java


text:
<file_sep># Pixel Art Maker Project

This is a Udacity course project.

## Contributing

This repository is for a Udacity course project. Therefore, we most likely will not accept pull requests.
<file_sep>/** Select color input */
let colorPicker = '#000';
$('#colorPicker').change(function(){
    colorPicker = $('#colorPicker').val();
});

/** Apply the selected color to the grid cell when clicked */
$('#pixelCanvas').on('click','td',function(){
    $(this).css('background-color',colorPicker);
});

/** When size is submitted by the user, call makeGrid() */
$('#sizePicker').submit(function(event){
    event.preventDefault();
    let inputHeight = $('#inputHeight').val();
    let inputWeight = $('#inputWeight').val();
    makeGrid(inputHeight,inputWeight);
});

/**
* Create the grid based on user input
* @param {number} h - height or the number of rows
* @param {number} w - width or the number of columns
*/
function makeGrid(h,w) {
    $('#pixelCanvas').children('tr').remove();
    for (let i = 1; i <= h; i++) {
        $('#pixelCanvas').append(`<tr class="row-${i}"></tr>`);
        for (let j = 1; j <= w; j++) {
            $('#pixelCanvas').children(`.row-${i}`).append('	');
        }
    }
}

languages: Markdown JavaScript

repo_language: Markdown

repo_name: ryohei-ono/pixel-art-maker


text:
<repo_name>VictorPPB/Exploratory-Data-Analysis<file_sep>/README.md
# Exploratory-Data-Analysis

This master branch has the code and the plot for the first course proyect in Exploratory Data Analysis.

VMO
<file_sep>/Code4Plots.R
### Code4Plots

# Clear all:
dev.off()
rm(list=ls())

# Getting data
setwd("~/Documents/OnlineCourses/Exploratory Data Analysis/Proyects/P1")
data <- read.csv("household_power_consumption.txt",  sep=';', header=T, na.strings="?",
                        check.names=F, stringsAsFactors=F, comment.char="", quote='\"')

data$Date <- as.Date(data$Date, format="%d/%m/%Y")
## Subset
data <- subset(data, subset=(Date >= "2007-02-01" & Date <= "2007-02-02"))
## convert the Date and Time variables
data$Datetime <- NULL
data$Datetime <- as.POSIXct(paste(as.Date(data$Date), data$Time))

#Use variables with direct names
attach(data)

## Plot 1
hist(Global_active_power, main="Global Active Power",
     xlab="Global Active Power (kilowatts)", ylab="Frequency", col="red")
## Save file
dev.copy(png, file="plot1.png", height=500, width=600)
dev.off()

## Plot 2
plot(Datetime,Global_active_power, main="",
     xlab="", ylab="Global Active Power (kilowatts)",t="l")
## Save file
dev.copy(png, file="plot2.png", height=500, width=600)
dev.off()

## Plot 3
plot(Sub_metering_1~Datetime, type="l",
     ylab="Global Active Power (kilowatts)", xlab="")
lines(Sub_metering_2~Datetime,col='Red')
lines(Sub_metering_3~Datetime,col='Blue')
legend("topright", lty=1, lwd=2,col=c("black", "red", "blue"),
       legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"))
## Save file
dev.copy(png, file="plot3.png", height=500, width=600)
dev.off()

## Plot 4 & Save

png(filename="plot4.png",height=500, width=600)
par(mfrow=c(2,2))
plot(Global_active_power~Datetime, type="l",
     ylab="Global Active Power (kilowatts)", xlab="")
plot(Voltage~Datetime, type="l",
     ylab="Voltage (volt)", xlab="Datetime")
plot(Sub_metering_1~Datetime, type="l",
     ylab="Global Active Power (kilowatts)", xlab="")
lines(Sub_metering_2~Datetime,col='Red')
lines(Sub_metering_3~Datetime,col='Blue')
legend("topright",  lty=1, lwd=2, bty="n",col=c("black", "red", "blue"),
       legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"))
plot(Global_reactive_power~Datetime, type="l",
     ylab="Global Rective Power (kilowatts)",xlab="Datetime")

dev.off()

languages: Markdown R

repo_name: VictorPPB/Exploratory-Data-Analysis


text:
<file_sep>var User = require('../models/user');

module.exports.IOHandler = (io) => {
    io.on('connection', (socket) => {
        console.log('user connected: ' + socket.id);
        module.exports = socket;

        socket.on('login', (id) => {
          console.log('loggin in...');
          console.log('MongoId: ', id);
          User.findOneAndUpdate({ _id: id }, { socketId: socket.id, online: true })
          .then(user => {
            console.log(user);
          });
        });

        socket.on('msg', (data) => {
          console.log('Sending msg: ' + data.message + ' to ' + data.to);

          User.findOne({ socketId: data.to })
          .then(user => {
            var online = user.online;
            var toUser = user.username;
            if (online) {
              io.to(data.to).emit('pmsg', { to: toUser, from: data.from, message: data.message, status: 'sent', read: false, image: false, audio: false });
              // User.findOneAndUpdate({ socketId: data.to }, { lastMsg: data.message, $push: { chats: { to: toUser, from: data.from, message: data.message } } }, {upsert: true})
              // .then(user => {
              //   console.log(user);
              // });
              user.lastMsg = data.message;
              user.chats.push({ to: toUser, from: data.from, message: data.message });
              user.save();

              User.findOne({ username: data.from })
              .then(user => {
                user.chats.push({ to: toUser, from: data.from, message: data.message });
                user.save();
              });
            } else {
              User.findOne({ username: data.from })
              .then(user => {
                user.chats.push({from: data.from, to: toUser, message: data.message });
                user.save();
                User.findOne({ socketId: data.to })
                  .then(user => {
                    user.chats.push({from: data.from, to: toUser, message: data.message });
                    user.save();
                  });
                if (data.message.indexOf('hey') > -1 || data.message.indexOf('hi') > -1 || data.message.indexOf('hello') > -1) {
                  io.to(user.socketId).emit('pmsg', {from: toUser, to: data.from, message: 'Hi, I am currently offline', status: 'sent', read: false, image: false, audio: false });
                  user.chats.push({from: toUser, to: data.from, message: 'Hi, I am currently offline'});
                  user.save();
                  User.findOne({ socketId: data.to })
                  .then(user => {
                    user.chats.push({from: toUser, to: data.from, message: 'Hi, I am currently offline'});
                    user.save();
                  });
                } else if (data.message.indexOf('when') > -1) {
                  io.to(user.socketId).emit('pmsg', {from: toUser, to: data.from, message: 'I\'ll text you when i\'ll be online', status: 'sent', read: false, image: false, audio: false });
                  user.chats.push({from: toUser, to: data.from, message: 'I\'ll text you when i\'ll be online'});
                  user.save();
                  User.findOne({ socketId: data.to })
                  .then(user => {
                    user.chats.push({from: toUser, to: data.from, message: 'I\'ll text you when i\'ll be online'});
                    user.save();
                  });
                } else if (data.message.indexOf('Ok') > -1 || data.message.indexOf('OK') > -1 || data.message.indexOf('Okay') > -1 || data.message.indexOf('OKAY') > -1 || data.message.indexOf('ok') > -1) {
                  io.to(user.socketId).emit('pmsg', {from: toUser, to: data.from, message: ':)', status: 'sent', read: false, image: false, audio: false });
                  user.chats.push({from: toUser, to: data.from, message: ':)'});
                  user.save();
                  User.findOne({ socketId: data.to })
                  .then(user => {
                    user.chats.push({from: toUser, to: data.from, message: ':)'});
                    user.save();
                  });

                }
              });
            }
          });
        });

        socket.on('read', (username) => {
            User.findOne({ username: username })
            .then(result => {
                console.log("chats XYZ ", result.chats);
                for(let i=0; i<result.chats.length; i++) {
                  result.chats[i].read = true;
                }
                result.save();
            });
        });

        socket.on('image', (data) => {
          console.log('image invoked');
          // console.log(data.buff);
          io.to(data.to).emit('imgmsg', data.buff);
          User.findOne({ socketId: data.to })
          .then(user => {
            console.log(user);
            const toUser = user.username
            user.chats.push({ to: user.username, from: data.from, image: true, base64: data.buff });
            user.save()
            User.findOne({ username: data.from })
          .then(user => {
            console.log(user);
            user.chats.push({ to: toUser, from: data.from, image: true, base64: data.buff });
            user.save();
          });
        });

          });

          socket.on('audio', (data) => {
            console.log('audio invoked');
            // console.log(data.buff);
            io.to(data.to).emit('audmsg', data.buff);
            User.findOne({ socketId: data.to })
            .then(user => {
              console.log(user);
              const toUser = user.username
              user.chats.push({ to: user.username, from: data.from, audio: true, base64: data.buff });
              user.save()
              User.findOne({ username: data.from })
            .then(user => {
              console.log(user);
              user.chats.push({ to: toUser, from: data.from, audio: true, base64: data.buff });
              user.save();
            });
          });

            });

        socket.on('disconnect', () => {
          console.log(socket.id + ' disconnected');
          User.findOneAndUpdate({ socketId: socket.id }, { online: false})
          .then(user => {
            console.log(user);
          });
        });

        socket.on('logout', () => {
          User.findOneAndUpdate({ socketId: socket.id }, { online: false})
          .then(user => {
            console.log(user);
          });
          // socket.disconnect();
        });
      });
};
<file_sep>var express = require('express');
var router = express.Router();
var passport = require('passport');
var loginController = require('../controller/login');
var userController = require('../controller/user');
var socket = require('socket.io');

/* GET users listing. */
router.get('/', function(req, res, next) {
  userController.getUsers(req, res, next);
});

 /**
 * @swagger
 * components:
 * securitySchemes:
 *   bearerAuth:            # arbitrary name for the security scheme
 *     type: http
 *     scheme: bearer
 *     bearerFormat: JWT
 *
 *
 * definitions:
 *   User:
 *     properties:
 *       username:
 *         type: string
 *       firstname:
 *         type: string
 *       lastname:
 *         type: string
 *       socketId:
 *         type: string
 *       lastMsg:
 *         type: string
 *       online:
 *         type: boolean
 *       chats:
 *         type: array
 *
 */
/**
 * @swagger
 * /users/login:
 *   post:
 *     tags:
 *       - user
 *     description: login user
 *     produces:
 *       - application/json
 *     parameters:
 *       - name: user
 *         description: user login
 *         in: body
 *         required: true
 *         schema:
 *           $ref:'#/definitions/User'
 *     responses:
 *       200:
 *         description: Login succesfully
 *       401:
 *         description: User not found
 *       403:
 *         description: Username and password don't match
 */
router.post('/login', passport.authenticate('local'), (req, res, next) => {
  loginController.login(req, res, next);
});

/**
 * @swagger
 * /users/register:
 *   post:
 *     tags:
 *       - user
 *     description: register user
 *     produces:
 *       - application/json
 *     parameters:
 *       - name: user
 *         description: user resgistration
 *         in: body
 *         required: true
 *         schema:
 *           $ref:'#/definitions/User'
 *     responses:
 *       200:
 *         description:  succesfully
 *
 */
router.post('/signup', (req, res, next) => {
  loginController.signup(req, res, next);
});

router.post('/:sockedId/send', (req, res, next) => {
  // userController.sendMsg(socket)
})

router.get('/checkJWTToken', (req, res) => {
  passport.authenticate('jwt', {session: false}, (err, user, info) => {
    console.log("entered");
    console.log(user);
    console.log(req.user);
    if (err)
      return next(err);

    if (!user) {
      console.log("User doesn't exists");
      res.statusCode = 401;
      res.setHeader('Content-Type', 'application/json');
      return res.json({status: 'JWT invalid!', success: false, err: info});
    }
    else {
      console.log("User exists");
      res.statusCode = 200;
      res.setHeader('Content-Type', 'application/json');
      return res.json({status: 'JWT valid!', success: true, user: user});

    }
  }) (req, res);
});

module.exports = router;
<file_sep>import { AuthService } from './../../services/auth.service';
import { UserService } from './../../services/user.service';
import { ChatService } from './../../services/chat.service';
import { Component, OnInit } from '@angular/core';
import { Subscription, from } from 'rxjs';
import { FsService } from 'ngx-fs';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { ImageCompressService, ResizeOptions, ImageUtilityService, IImage, SourceImage } from 'ng2-image-compress';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  message: string;
  to: string;
  touser: string;
  messages: string[] = [];
  users: any[] = [];
  username: string = undefined;
  interval: any;
  userSubscription: Subscription;
  chatSubscription: Subscription;
  id: string;
  chats: any;
  chat_users = new Set();
  path: string;
  fileToUpload: File = null;
  imageurl: any;
  FILE: any;
  selectedImage: any;
  processedImages: any = [];
  showTitle = false;
  length: number;

  constructor(private chatService: ChatService, private userService: UserService, private authService: AuthService, private fsService: FsService, private domSanitizer: DomSanitizer) {

   this.userSubscription = userService.getUsers().subscribe(users => {
      // this.users = users;
      this.users = [];
      this.users.push(...users);
      console.log(this.users);

    if (!authService.string_id) {
      authService.getId().subscribe(id => {
        this.id = id;
        chatService.getChats(id).subscribe(chats => {
          this.chats = chats;
          console.log(chats);
          for (let i = 0; i < chats.length(); i++) {
            this.chat_users.add(chats[i].from);
          }
          console.log(this.chat_users);
        });
      });
    } else {
      this.id = authService.string_id;
      chatService.getChats(this.id).subscribe(chats => {
        this.chats = chats;
        console.log(chats);
        for (let i = 0; i < chats.length; i++) {
          this.chat_users.add(chats[i].from);
        }
        console.log(this.chat_users);
      });
    }
  });

    this.username = authService.string_user;

    this.chatSubscription =  this.chatService
    .getMessages()
    .subscribe((messageObject: any) => {
      // this.messages.push(message);
      for (let i = 0; i < this.users.length; i++) {
        if (this.users[i].username === messageObject.to || this.users[i].username === messageObject.from) {
          console.log('This message is intended from ' + messageObject.from + ' to ' + messageObject.to);
          this.users[i].chats.push(messageObject);
        }
      }
    });

    // this.interval = setInterval(() => {
    //   userService.getUsers().subscribe(users => {
    //     // this.users = users;
    //     this.users = [];
    //   this.users.push(...users);
    //   console.log(this.users);
    // });
    // }, 10000);

    userService.getUsers().subscribe(users => {
      // this.users = users;
      this.users = [];
    this.users.push(...users);
    console.log(this.users);
  });
  }

  sendMessageTo() {
    console.log(this.to);
    if (this.message ) {
      this.messages.push(this.username + ': ' + this.message);
      this.chatService.sendMessageTo(this.to, this.username, this.message);
      console.log(this.to);
      for (let i = 0; i < this.users.length; i++) {
        if (this.users[i].username === this.touser || this.users[i].username === this.username) {
          console.log('This message is intended from ' + this.username + ' to ' + this.touser);
          this.users[i].chats.push({ to: this.touser, from: this.username, message: this.message, status: this.sendMessageTo, read: false, image: false, audio: false });
        }
      }
      this.message = '';

    }
  }
  ngOnInit() {
  this.chatService
    .getMessages()
    .subscribe((message: string) => {
      this.messages.push(message);
    });
  }

  logout() {
    clearInterval(this.interval);
    this.userSubscription.unsubscribe();
    this.chatSubscription.unsubscribe();
    this.authService.logOut();
  }

  focus(username) {
    console.log(username + '\'s messages');
    this.chatService.readMsg(username);
    for (let i = 0; i < this.users.length; i++) {
      if (this.users[i].read === false) {
        this.users[i].read = true;
      }
    }
  }

  console() {
    console.log(this.path);
  }

  changeListener($event): void {
    this.readThis($event.target);
  }

  readThis(inputValue: any): void {
    const file: File = inputValue.files[0];
    console.log(file);
    const type = file.type.split('/')[0];
    const myReader: FileReader = new FileReader();

    myReader.onloadend = (e) => {
      this.FILE = myReader.result;
      // this.imageurl = this.domSanitizer.bypassSecurityTrustUrl(myReader.result.toString());
      this.chatService.sendMessageTo(this.to, this.username, null, this.FILE, type);
    };
    myReader.readAsDataURL(file);

    const images: Array<IImage> = [];

    ImageCompressService.filesArrayToCompressedImageSource(Array.from(inputValue.files)).then(observableImages => {
      observableImages.subscribe((image) => {
        images.push(image);
      }, (error) => {
        console.log('Error while converting');
      }, () => {
                this.processedImages = images;
                this.showTitle = true;
                // console.log()
      });
    });

  }

  preview(event) {
    const modal = <HTMLDivElement>document.getElementById('myModal');
    console.log(event.srcElement);
    const modalImg = <HTMLImageElement>document.getElementById('img01');

      modal.style.display = 'block';
      modalImg.src = event.srcElement.src;

     const span = <HTMLSpanElement>document.getElementsByClassName('close')[0];
     span.onclick = function() {
       modal.style.display = 'none';
     };

  }
}
<file_sep>import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs';
import { localUrl } from 'src/constants';

@Injectable({
  providedIn: 'root'
})
export class ChatService {

    private url = 'http://localhost:3000';
    private socket;

    constructor(private http: HttpClient) {
        this.socket = io(this.url);
    }

    public sendDisconnect() {
      this.socket.emit('logout');
    }

    public sendId(id) {
      this.socket.emit('login', id);
    }

    public sendMessageTo(to, from, message = null, buff = null, type = 'image') {
      // tslint:disable-next-line:no-non-null-assertion
      if (message != null && buff == null ) {
        this.socket.emit('msg', { message: message, to: to, from: from });
      } else if (message == null && buff != null) {
        console.log('image invoked');
        if (type === 'image') {
        this.socket.emit('image', { buff: buff, to: to, from: from });
        } else if (type === 'audio') {
          this.socket.emit('audio', { buff: buff, to: to, from: from });
          }
      }
    }

    public getMessages = () => {
      return Observable.create((observer) => {
          this.socket.on('pmsg', (messageObject) => {
            console.log(messageObject);
              observer.next(messageObject);
          });
      });
    }

    getChats(id): Observable<any> {
      return this.http.get<any>(localUrl + id + '/chats');
    }

    readMsg(user) {
      this.socket.emit('read', user);
    }

}

languages: TypeScript JavaScript

repo_language: TypeScript

repo_name: khatrimann/chat-app


text:
<repo_name>Miss-ada/slugshell-java<file_sep>/SingleCommand.java
import java.util.List;

public class SingleCommand {
	String cmd;
	List<String> args;
	public SingleCommand(String c, List<String> ar){
		cmd = c;
		args = ar;
	}
}<file_sep>/README.md
# slugshell-java

An implementation of shell using java.

### Environment
* Linux/Unix System
* Python 3

### How to Start
Install dependency by pip install -r requirements.txt

### Acknowledgments
Course CMPS203 Programming Languages, Spring 2018, UC, Santa Cruz

### License
This project is under MIT License. For more details and copyrights of 3rd parties, please refer to the LICENSE file. Copyright (c) 2018 <NAME> and <NAME>

repo_name: Miss-ada/slugshell-java


text:
<repo_name>cavicchioli/wargen<file_sep>/wargen/README.md
# wargen

Server: 192.168.3.11:6080/

<file_sep>/wargen/views/usuarios/listar.ejs
<!DOCTYPE html>

    <title><%=titulo %></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

<%=titulo %>

<% for(var i=0; i<data.length; i++) {%>

<%= data[i] %>

<% } %>

<file_sep>/wargen/config/development.js
module.exports = {

    title: 'WARGEN (development)',
    port: 3000,
    connectionString: process.env.DATABASE_URL || 'postgres://postgres:postgres123@localhost:5432/wargenDB'
};<file_sep>/wargen/views/usuarios/cadastro.ejs
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<title></title>

	  <link href="/stylesheets/bootstrap/bootstrap.min.css" rel="stylesheet" />

	  <link href="/stylesheets/template/AdminLTE.css" rel="stylesheet" />

		  WARGEN

Registrar novo usuário

		<form action="/signup" method="post" enctype="application/x-www-form-urlencoded">

			<input name="usuario[nome]" type="text" class="form-control" placeholder="Nome completo">

			<input name="usuario[email]" type="email" class="form-control" placeholder="Email">

			<input name="usuario[email_conf]" type="email" class="form-control" placeholder="Confirmar email">

			<input name="usuario[senha]" type="<PASSWORD>" class="form-control" placeholder="<PASSWORD>">

			<input name="usuario[senha_conf]" type="<PASSWORD>" class="form-control" placeholder="Confirmar senha">

			  <button type="submit" class="btn btn-primary btn-block btn-flat">Registrar</button>

		</form>

		Eu já possuo uma conta

<file_sep>/wargen/controllers/appController.js
exports.viewApp = function (req, res) {
    res.render('blank');
};<file_sep>/wargen/views/three.ejs

<!DOCTYPE html>

    <title>three.js webgl - geometry - cube</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

<file_sep>/wargen/controllers/three.js
exports.three = function (req, res) {
    res.render('three');
};<file_sep>/wargen/config/production.js
module.exports = {

    title: 'WARGEN (production)',
    port: 6080,
    connectionString: process.env.DATABASE_URL || 'postgres://postgres:postgres123@localhost:5432/wargenDB'

};<file_sep>/wargen/routes/appRoutes.js
module.exports = function (app) {
    var appCtrl = app.controllers.appController;

    //app.get('/usuario/listar', userCtrl.viewListar);
    //app.get('/usuario/listar', userCtrl.listaUsuarios);

    app.get('/app', appCtrl.viewApp);
    //app.post('/login', userCtrl.validaUsuario);

};<file_sep>/wargen/views/usuarios/login.ejs
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<title></title>

	<link href="/stylesheets/bootstrap/bootstrap.min.css" rel="stylesheet" />

	 <link href="/stylesheets/template/AdminLTE.css" rel="stylesheet" />

		WARGEN

Informe sua credencial para iniciar

		<form action="/login" method="post" enctype="application/x-www-form-urlencoded">

			<input name="login[email]" type="email" class="form-control" placeholder="Email">

			<input name="login[senha]" type="password" class="form-control" placeholder="Senha">

			  <button type="submit" class="btn btn-primary btn-block btn-flat">Entrar</button>

		</form>

		Esqueci a senha

		Registar novo usuário

<file_sep>/wargen/routes/userRoutes.js
module.exports = function (app) {
    var userCtrl = app.controllers.userController;

    app.get('/usuario/listar', userCtrl.viewListar);
    //app.get('/usuario/listar', userCtrl.listaUsuarios);

    app.get('/login', userCtrl.viewLogin);
    app.post('/login', userCtrl.validaUsuario);

    app.get('/cadastro', userCtrl.viewCadastro);
    app.post('/cadastro', userCtrl.insereUsuario);

};<file_sep>/wargen/models/userModel.js
/*MODEL*/
module.exports = {

    listaUsuarios: function (req, res) {
        var pg = require('pg');
        var conf = require('../config');

        var db = new pg.Client(conf.connectionString);

        db.connect();

        var query = db.query("select * from usuarios");

        query.on("row", function (row, result) {
            result.addRow(row);
        });

        query.on("end", function (result) {
            db.end();
            res.writeHead(200, { 'Content-Type': 'text/plain' });
            res.write(JSON.stringify(result.rows, null, "    ") + "\n");
            res.end();
        });
    },

    insereUsuario : function (req, res) {

        var pg = require('pg-promise')(/*options*/);
        var conf = require('../config');

        var db = pg(conf.connectionString);

        db.func('sp_wargen_cadastra_usuario', [req.body.usuario.nome, req.body.usuario.email, req.body.usuario.email_conf, req.body.usuario.senha, req.body.usuario.senha_conf])
            .then(function (data) {
            console.log("DATA:", data); // print data;
            console.log(data[0].p_msg);

            if (data[0].p_msg === ("OK"))
                res.redirect('\\login');
        })
             .catch(function (error) {
            console.log("ERROR:", error); // print the error;
        });

    },

    deletaUsuario : function (req, res) {
        res.redirect('\\login');
    },

    validaUsuario : function (req, res) {
        //pg-promise
        var pg = require('pg-promise')(/*options*/);

        // Database connection details;
        var conf = require('../config');

        var db = pg(conf.connectionString); // database instance;

        db.func('sp_wargen_valida_usuario', [req.body.login.email, req.body.login.senha])
            .then(function (data) {

           response.send(data);
            //res.json(data);
        })
             .catch(function (error) {
            console.log("ERROR:", error); // print the error;
        });
    }

};

languages: Markdown EJS JavaScript

repo_name: cavicchioli/wargen


text:
<file_sep>package com.grant.smith;

import java.util.*;
import java.awt.geom.Point2D;
import java.io.*;

public class VRPartitionSolution {

	// Stores the information about the problem
	public VRProblem prob;
	// Stores the solution after solve() is ran
	public List<Route> soln;
	// Stores the circles used to create the solution
	ArrayList<Circle> circles;

	public VRPartitionSolution(VRProblem problem){
		this.prob = problem;
	}

	//Students should implement another solution
	public void solve(){

		// Create a circle that encompasses all nodes
		Circle root = new Circle(prob.depot.x, prob.depot.y, 0.0);
		for(Customer c : prob.customers){
			root.add(c);
		}
		// Shrink the circle so that it just covers all of the nodes within it
		root.shrink();

		// Create the list to contain all off the circles
		circles = new ArrayList<Circle>();
		// Add the first circle to the list
		circles.add(root);

		boolean overCap = true;
		while(overCap){
			overCap = false;
			for(int i = 0; i < circles.size(); i++){
				// Get the circle for this iteration
				Circle c = circles.get(i);
				// Check if this circle should be kept (if is contains any nodes)
				if(!c.keepAlive()) { circles.remove(i); continue;} // If this circle shouldn't be kept, remove it
				if(c.demand > prob.depot.c){
					// Get the farthest node in this circle
					Customer farthest = c.farthestNode();

					// Create a new circle between that node and this circle's centre
				    double mx = (farthest.x + c.pos.x)/2;
				    double my = (farthest.y + c.pos.y)/2;
					Circle newC = new Circle( new Point2D.Double(mx,my), c.radius/2);

					// Loop through all the circles and try to steal nodes
					for(Circle others : circles){
						newC.steal(others);
						if(others.demand <= prob.depot.c)
							others.canBeStolenFrom = false;
					}

					// Add the new circle to the list
					circles.add(newC);

					// Check if we need to keep looping the 'while'
					if(c.demand > prob.depot.c || newC.demand > prob.depot.c)
						overCap = true;

				}

			}

			// Merge all circles if they cross over and merging them wouldn't put them over capacity
			boolean merged = true;
			while(merged){ // If there was a merge, check again to see if there are any more
				merged = false;
				// Loop through every circle for each circle
				for(int i = 0; i < circles.size()-1; i++){
					for(int j = i+1; j < circles.size(); j++){ // Don't loop through circles that have already checked this circle
						// Get circle ci and circle cj
						Circle ci = circles.get(i);
						Circle cj = circles.get(j);
						// Check if they should be merged
						if((ci.demand + cj.demand <= prob.depot.c) && (ci.pos.distance(cj.pos) <= ci.radius*2 + cj.radius*2)){
							// merge the circles
							circles.remove(cj);
							ci.mergeRoutes(cj);
							// Shrink the circle so that it just covers all of the nodes within it
							ci.shrink();
							// state that there was a merge
							merged = true;
						}
					}
				}
			}

			// Resize and reposition all of the circles depending on the farthest node within them and their position
			for(int i = 0; i < circles.size(); i++){
				Circle c = circles.get(i);
				Customer farthest = c.farthestNode();
				if(farthest == null){ circles.remove(i); continue;}
				// Get the midpoint between the circle's position and the farthest node's position
			    double mx = (farthest.x + c.pos.x)/2;
			    double my = (farthest.y + c.pos.y)/2;
			    // Set the circle's position to the calculated midpoint
				c.pos.setLocation(mx, my);
				// Shrink the circle so that it just covers all of the nodes within it
				c.shrink();

			}
		}

		for(Circle c : circles){
			if(c.size() > 1){
				c.improve(prob.depot);
			}
		}

		soln = new LinkedList<Route>();

		soln.addAll(circles);

		//Remove the circles so that they don't render
		circles.clear();

	}

	//Calculate the total journey
	public double solnCost(){
		double cost = 0;
		for(List<Customer>route:soln){
			Customer prev = this.prob.depot;
			for (Customer c:route){
				cost += prev.distance(c);
				prev = c;
			}
			//Add the cost of returning to the depot
			cost += prev.distance(this.prob.depot);
		}
		return cost;
	}

	public Boolean verify(){
		//Check that no route exceeds capacity
		Boolean okSoFar = true;
		for(Route route : soln){
			//Start the spare capacity at
			int total = 0;
			for(Customer c:route)
				total += c.c;
			if (total>prob.depot.c){
				System.out.printf("********FAIL Route starting %s is over capacity %d\n",
						route.get(0),
						total
						);
				okSoFar = false;
			}
		}
		//Check that we keep the customer satisfied
		//Check that every customer is visited and the correct amount is picked up
		Map<String,Integer> reqd = new HashMap<String,Integer>();
		for(Customer c:this.prob.customers){
			String address = String.format("%fx%f", c.x,c.y);
			reqd.put(address, c.c);
		}
		for(Route route:this.soln){
			for(Customer c:route){
				String address = String.format("%fx%f", c.x,c.y);
				if (reqd.containsKey(address))
					reqd.put(address, reqd.get(address)-c.c);
				else
					System.out.printf("********FAIL no customer at %s\n",address);
			}
		}
		for(String address:reqd.keySet())
			if (reqd.get(address)!=0){
				System.out.printf("********FAIL Customer at %s has %d left over\n",address,reqd.get(address));
				okSoFar = false;
			}
		return okSoFar;
	}

	public void readIn(String filename) throws Exception{
		BufferedReader br = new BufferedReader(new FileReader(filename));
		String s;
		this.soln = new ArrayList<Route>();
		while((s=br.readLine())!=null){
			Route route = new Route();
			String [] xycTriple = s.split(",");
			for(int i=0;i<xycTriple.length;i+=3)
				route.add(new Customer(
						(int)Double.parseDouble(xycTriple[i]),
						(int)Double.parseDouble(xycTriple[i+1]),
						(int)Double.parseDouble(xycTriple[i+2])));
			soln.add(route);
		}
		br.close();
	}

	public void writeSVG(String probFilename,String solnFilename) throws Exception{
		String[] colors = "chocolate cornflowerblue crimson cyan darkblue darkcyan darkgoldenrod".split(" ");
		int colIndex = 0;
		String hdr =
				"<?xml version='1.0'?>\n"+
						"<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' '../../svg11-flat.dtd'>\n"+
						"<svg width='8cm' height='8cm' viewBox='0 0 500 500' xmlns='http://www.w3.org/2000/svg' version='1.1'>\n";
		String ftr = "</svg>";
		StringBuffer psb = new StringBuffer();
		StringBuffer ssb = new StringBuffer();
		psb.append(hdr);
		ssb.append(hdr);
		for(List<Customer> route:this.soln){
			ssb.append(String.format("<path d='M%s %s ",this.prob.depot.x,this.prob.depot.y));
			for(Customer c:route)
				ssb.append(String.format("L%s %s",c.x,c.y));
			ssb.append(String.format("z' stroke='%s' fill='none' stroke-width='2'/>\n",
					colors[colIndex++ % colors.length]));
		}
		for(Customer c:this.prob.customers){
			String disk = String.format(
					"<g transform='translate(%.0f,%.0f)'>"+
							"<circle cx='0' cy='0' r='%d' fill='pink' stroke='black' stroke-width='1'/>" +
							"<text text-anchor='middle' y='5'>%d</text>"+
							"</g>\n",
							c.x,c.y,10,c.c);
			psb.append(disk);
			ssb.append(disk);
		}
		for(Circle c : this.circles){
			String disk = String.format(
					"<g transform='translate(%.0f,%.0f)'>"+
							"<circle cx='0' cy='0' r='%d' fill='none' stroke='black' stroke-width='1'/>" +
							"<text text-anchor='middle' y='5'>%s</text>"+
							"</g>\n",
							c.pos.x, c.pos.y, (int)c.radius, "");
			psb.append(disk);
			ssb.append(disk);
		}
		String disk = String.format("<g transform='translate(%.0f,%.0f)'>"+
				"<circle cx='0' cy='0' r='%d' fill='pink' stroke='black' stroke-width='1'/>" +
				"<text text-anchor='middle' y='5'>%s</text>"+
				"</g>\n", this.prob.depot.x,this.prob.depot.y,20,"D");
		psb.append(disk);
		ssb.append(disk);
		psb.append(ftr);
		ssb.append(ftr);
		PrintStream ppw = new PrintStream(new FileOutputStream(probFilename));
		PrintStream spw = new PrintStream(new FileOutputStream(solnFilename));
		ppw.append(psb);
		spw.append(ssb);
		ppw.close();
		spw.close();
	}
	public void writeOut(String filename) throws Exception{
		PrintStream ps = new PrintStream(filename);
		for(List<Customer> route:this.soln){
			boolean firstOne = true;
			for(Customer c:route){
				if (!firstOne)
					ps.print(",");
				firstOne = false;
				ps.printf("%f,%f,%d",c.x,c.y,c.c);
			}
			ps.println();
		}
		ps.close();
	}
}
<file_sep>package com.grant.smith;

import java.util.*;
import java.io.*;

public class VRClarkeWrightSolution {

	// Stores the information about the problem
	public VRProblem prob;
	// Stores the solution after solve() is ran
	public List<Route> soln;

	public VRClarkeWrightSolution(VRProblem problem){
		this.prob = problem;
	}

	//The dumb solver adds one route per customer
	public void oneRoutePerCustomerSolution(){
		this.soln = new ArrayList<Route>();
		for(Customer c:prob.customers){
			Route route = new Route();
			route.add(c);
			soln.add(route);
		}
	}

	// Clarke Wright solver function
	public void solve(){
		// Create a route for each customer
		oneRoutePerCustomerSolution();

		// Calculate the savings list for the problem
		List<SavingsNode> savings = getSavings();

		// Loop through each saving
		for (SavingsNode savingsNode : savings) {
			// Get the route where ci is the first customer
			Route route0 = routeWhereCustomerIsLast(savingsNode.ci);
			if(route0 != null){ // check if we found a route for route0
				// Get the route where cj is the first customer
				Route route1 = routeWhereCustomerIsFirst(savingsNode.cj);
				if(route1 != null){ // check if we found a route for route1
					if(route0 == route1){ continue;} // if route0 and route1 are the same, do nothing
					if (route0.demand + route1.demand <= prob.depot.c) { // if merge is feasible
						// Merge the two routes
						soln.remove(route1);
						route0.mergeRoutes(route1);
					}
				}
			}
		}

	}

	// returns a route where c is the last element in a route
	private Route routeWhereCustomerIsLast(Customer c){
		for(Route r : soln){
			if(r.getEnd() == c) return r;
		}
		return null;
	}

	// returns a route where c is the first element in a route
	private Route routeWhereCustomerIsFirst(Customer c){
		for(Route r : soln){
			if(r.getStart() == c) return r;
		}
		return null;
	}

	// Calculates the savings list
	public List<SavingsNode> getSavings(){
		// Create a list of customers for the savings list to use
		List<Customer> customers = new ArrayList<Customer>();
		// loop through every route
		for(Route r : soln){
			if(r.demand < prob.depot.c){
				// add the start of the route to the list
				customers.add(r.getStart());
				// if the route is larger than just 1 element, add the end as well
				if(r.size() > 1)
					customers.add(r.getEnd());
			}
		}

		// Create the savings list
		List<SavingsNode> savings = new ArrayList<SavingsNode>();
		// Loop through each node and add the relative savings to the savings list if there is a saving to be made
		for(int i = 0; i < customers.size(); i++){
			for(int j = i; j < customers.size(); j++){
				if(i == j) continue;
				Customer ci = customers.get(i);
				Customer cj = customers.get(j);
				double saving = (prob.depot.distance(ci) + prob.depot.distance(cj)) - ci.distance(cj) ;
				if(saving > 0)
					savings.add(new SavingsNode(ci,cj,saving));
			}
		}
		// Sort the list into descending order
		Collections.sort(savings);
		return savings;
	}

	//Calculate the total journey
	public double solnCost(){
		double cost = 0;
		for(List<Customer>route:soln){
			Customer prev = this.prob.depot;
			for (Customer c:route){
				cost += prev.distance(c);
				prev = c;
			}
			//Add the cost of returning to the depot
			cost += prev.distance(this.prob.depot);
		}
		return cost;
	}

	public Boolean verify(){
		//Check that no route exceeds capacity
		Boolean okSoFar = true;
		for(Route route : soln){
			//Start the spare capacity at
			int total = 0;
			for(Customer c:route)
				total += c.c;
			if (total>prob.depot.c){
				System.out.printf("********FAIL Route starting %s is over capacity %d\n",
						route.get(0),
						total
						);
				okSoFar = false;
			}
		}
		//Check that we keep the customer satisfied
		//Check that every customer is visited and the correct amount is picked up
		Map<String,Integer> reqd = new HashMap<String,Integer>();
		for(Customer c:this.prob.customers){
			String address = String.format("%fx%f", c.x,c.y);
			reqd.put(address, c.c);
		}
		for(Route route:this.soln){
			for(Customer c:route){
				String address = String.format("%fx%f", c.x,c.y);
				if (reqd.containsKey(address))
					reqd.put(address, reqd.get(address)-c.c);
				else
					System.out.printf("********FAIL no customer at %s\n",address);
			}
		}
		for(String address:reqd.keySet())
			if (reqd.get(address)!=0){
				System.out.printf("********FAIL Customer at %s has %d left over\n",address,reqd.get(address));
				okSoFar = false;
			}
		return okSoFar;
	}

	public void readIn(String filename) throws Exception{
		BufferedReader br = new BufferedReader(new FileReader(filename));
		String s;
		this.soln = new ArrayList<Route>();
		while((s=br.readLine())!=null){
			Route route = new Route();
			String [] xycTriple = s.split(",");
			for(int i=0;i<xycTriple.length;i+=3)
				route.add(new Customer(
						(int)Double.parseDouble(xycTriple[i]),
						(int)Double.parseDouble(xycTriple[i+1]),
						(int)Double.parseDouble(xycTriple[i+2])));
			soln.add(route);
		}
		br.close();
	}

	public void writeSVG(String probFilename,String solnFilename) throws Exception{
		String[] colors = "chocolate cornflowerblue crimson cyan darkblue darkcyan darkgoldenrod".split(" ");
		int colIndex = 0;
		String hdr =
				"<?xml version='1.0'?>\n"+
						"<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' '../../svg11-flat.dtd'>\n"+
						"<svg width='8cm' height='8cm' viewBox='0 0 500 500' xmlns='http://www.w3.org/2000/svg' version='1.1'>\n";
		String ftr = "</svg>";
		StringBuffer psb = new StringBuffer();
		StringBuffer ssb = new StringBuffer();
		psb.append(hdr);
		ssb.append(hdr);
		for(List<Customer> route:this.soln){
			ssb.append(String.format("<path d='M%s %s ",this.prob.depot.x,this.prob.depot.y));
			for(Customer c:route)
				ssb.append(String.format("L%s %s",c.x,c.y));
			ssb.append(String.format("z' stroke='%s' fill='none' stroke-width='2'/>\n",
					colors[colIndex++ % colors.length]));
		}
		for(Customer c:this.prob.customers){
			String disk = String.format(
					"<g transform='translate(%.0f,%.0f)'>"+
							"<circle cx='0' cy='0' r='%d' fill='pink' stroke='black' stroke-width='1'/>" +
							"<text text-anchor='middle' y='5'>%d</text>"+
							"</g>\n",
							c.x,c.y,10,c.c);
			psb.append(disk);
			ssb.append(disk);
		}
		String disk = String.format("<g transform='translate(%.0f,%.0f)'>"+
				"<circle cx='0' cy='0' r='%d' fill='pink' stroke='black' stroke-width='1'/>" +
				"<text text-anchor='middle' y='5'>%s</text>"+
				"</g>\n", this.prob.depot.x,this.prob.depot.y,20,"D");
		psb.append(disk);
		ssb.append(disk);
		psb.append(ftr);
		ssb.append(ftr);
		PrintStream ppw = new PrintStream(new FileOutputStream(probFilename));
		PrintStream spw = new PrintStream(new FileOutputStream(solnFilename));
		ppw.append(psb);
		spw.append(ssb);
		ppw.close();
		spw.close();
	}
	public void writeOut(String filename) throws Exception{
		PrintStream ps = new PrintStream(filename);
		for(List<Customer> route:this.soln){
			boolean firstOne = true;
			for(Customer c:route){
				if (!firstOne)
					ps.print(",");
				firstOne = false;
				ps.printf("%f,%f,%d",c.x,c.y,c.c);
			}
			ps.println();
		}
		ps.close();
	}
}
<file_sep>package com.grant.smith;

public class SavingsNode implements Comparable<SavingsNode> {

	// Saving to be made
	public final double saving;
	// Customers that make the saving
	public final Customer ci, cj;

	public SavingsNode(Customer ci, Customer cj, double saving){
		this.ci = ci;
		this.cj = cj;
		this.saving = saving;
	}

	// Comparator for sorting
	public int compareTo(SavingsNode sj) {
		return saving < sj.saving ? 1 : saving == sj.saving ? 0 : -1;
	}

}
<file_sep>package com.grant.smith;

import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class Circle extends Route{

	// stores the radius of this circle
	double radius;
	// stores the position of this circle
	Point2D.Double pos;
	// stores the stealable state (whether another circle can steal from it or not)
	boolean canBeStolenFrom = true;

	// Constructor for a circle
	Circle(double x, double y, double radius){
		this(new Point2D.Double(x,y), radius);
	}

	// Constructor for a circle
	Circle(Point2D.Double pos, double radius){
		this.pos = pos;
		this.radius = radius;
	}

	// Shrink the circle so that it just covers all of the nodes within it
	public void shrink(){
		if(size() > 0)
			radius = farthestNode().distance(pos);
	}

	// Should this circle be kept (false if it has no children)
	public boolean keepAlive(){
		if(size() == 0)
			return false;

		return true;
	}

	// Add all of the nodes from one circle to this one
	public void mergeRoutes(Circle other){
		super.mergeRoutes(other);
		// Get the midpoint between the circle's position and the farthest node's position
	    double mx = (other.pos.x + pos.x)/2;
	    double my = (other.pos.y + pos.y)/2;
	    // Set the circle's position to the calculated midpoint
		pos.setLocation(mx, my);
		// Shrink this circle so that it just covers all of the nodes within it
		shrink();
	}

	// Attempt to steal nodes from another circle until full or out of nodes to steal
	public void steal(Circle other){
		if(!other.canBeStolenFrom) return; // If the other doesn't allow stealing, return
		Iterator<Customer> it = other.iterator();
		// For each node in the other circle
		while(it.hasNext()){
			Customer c = it.next();
			// Check which circle the node is closer to
			if(c.distance(pos) < c.distance(other.pos)){
				// If the node is closer to this circle then steal it
				other.demand -= c.c;
				add(c);
				it.remove();
			}
		}
		// Shrink this circle so that it just covers all of the nodes within it
		shrink();
		// Shrink the other circle so that it just covers all of the nodes within it
		other.shrink();
	}

	// Improves the pathing between the nodes contained withing this circle
	public void improve(Point2D.Double depot){
		// Create a list of savings
		List<SavingsNode> savings = new ArrayList<SavingsNode>();
		// Loop through each node and add the relative savings to the savings list if there is a saving to be made
		for(int i = 0; i < size(); i++){
			for(int j = 0; j < size(); j++){
				if(i == j) continue;
				Customer ci = get(i);
				Customer cj = get(j);
				double saving = depot.distance(ci) + depot.distance(cj) - ci.distance(cj);
				if(saving > 0)
					savings.add(new SavingsNode(ci,cj,saving));
			}
		}

		// Sort the list into descending order
		Collections.sort(savings);

		// Create an ordered list
		List<Customer> ordered = new LinkedList<Customer>();
		// Add the highest saving nodes and remove them from the savings list
		ordered.add(savings.get(0).ci);
		ordered.add(savings.remove(0).cj);

		// Loop through the savings list
		for(SavingsNode s : savings){
			// if the first ordered node is ci and ordered doesn't contain cj then add cj
			if(ordered.get(0) == s.ci && !ordered.contains(s.cj)){
				ordered.add(0,s.cj);
			// else if the lat ordered node is ci and ordered doesn't contain cj then add cj
			}else if(ordered.get(ordered.size()-1) == s.ci && !ordered.contains(s.cj)){
				ordered.add(s.cj);
			// else add cj to the side that has the largest saving
			}else{
				Customer first = ordered.get(0);
				Customer last = ordered.get(ordered.size()-1);

				double savingF = (depot.distance(first) + depot.distance(s.cj)) - first.distance(s.cj);
				double savingL = (depot.distance(last) + depot.distance(s.cj)) - last.distance(s.cj);

				if(savingF >= savingL && !ordered.contains(s.cj))
					ordered.add(0,s.cj);
				else if(!ordered.contains(s.cj))
					ordered.add(s.cj);
			}
		}
		// clear this list
		clear();
		// set the demand to 0
		demand = 0.0f;
		// add all of the ordered nodes to this list
		addAll(ordered);
	}

	// Return the farthest node from the center of this circle that this circle owns
	public Customer farthestNode(){
		// Set far to a very low number
		double far = Double.MIN_VALUE;
		Customer farthest = null;
		// Loop through each customer
		for(Customer c : this){
			// If the distance to c is larger than far then set the farthest to c
			if(pos.distance(c) > far){
				far = pos.distance(c);
				farthest = c;
			}
		}
		// return the farthest node
		return farthest;
	}

}
<file_sep>#Wed Oct 21 10:55:45 BST 2015
org.eclipse.core.runtime=2
org.eclipse.platform=4.4.0.v20140925-0400

languages: Java INI