问:
How to change the text background of ListView item
I'm implementing a ListView with ArrayAdapter. Whenever any ListView item is clicked, I'd like the text color of the item to be changed and also saved in SharedPreference. I'm a beginner I don't know how to implement it.

Please help me to achieve this goal. I tried many sources but the problem couldn't be solved.

Here is my code.

```<code>public class ALLVERSE extends AppCompatActivity  implements NavigationView.OnNavigationItemSelectedListener {
    private ListView mylistview;
    private ArrayList<String>versenumber;
    private ArrayList<String>verselist;
    private ArrayList<String>id;
    private  ArrayList<String>refernce;
    private DatabaseHelper mDBHelper;
    private SQLiteDatabase mDb;
    private int booknumber;
    private  int chapternumber;
    private  String bookname;
    private TextView booknametitle;
    private  FullverseAdopter fullverseAdopter;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        booknametitle=findViewById(R.id.bookname);

        Intent mIntent = getIntent();
        booknumber = mIntent.getIntExtra("Boooknumber",0);
        chapternumber= mIntent.getIntExtra("Chapternumber", 0);
        bookname=mIntent.getStringExtra("Bookname");

        booknametitle.setText(bookname.toString() +"   "+  chapternumber);

        //Toast.makeText(this, ""+bookname, Toast.LENGTH_SHORT).show();
        setSupportActionBar(toolbar);
        toolbar.setTitle("ALL VERSE");

        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        setData();

        mylistview=findViewById(R.id.mylistview);

        fullverseAdopter=new FullverseAdopter(ALLVERSE.this,R.layout.versedisplayrow,versenumber,verselist,refernce,id);

        mylistview.setAdapter(fullverseAdopter);

        mylistview.setOnItemClickListener(new AdapterView.OnItemClickListener(){

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

                Toast.makeText(ALLVERSE.this, "i am cliked", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // handle arrow click here
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }

    private void setData() {
        versenumber=new ArrayList<>();
        verselist=new ArrayList<>();
        refernce=new ArrayList<>();
        id=new ArrayList<>();

        mDBHelper = new DatabaseHelper(this);
        mDb = mDBHelper.getReadableDatabase();
        Cursor cursor = mDb.rawQuery("SELECT id, v, t from t_kjv where b="+booknumber+" AND c="+chapternumber+";", new String[]{});
        if(cursor!=null && cursor.getCount() > 0)
        { if (cursor.moveToFirst())
        {
            do {
                id.add(cursor.getString(0));
                versenumber.add(cursor.getString(1));
                verselist.add(cursor.getString(2));
                refernce.add(bookname+" "+chapternumber);
            }
            while (cursor.moveToNext());
        }
        }
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        Fragment fragment;
        int id = item.getItemId();
        if (id == R.id.home) {
            Intent intent=new Intent(this,MainActivity.class);
            startActivity(intent);

        } else if (id == R.id.favoruite)
        { Intent intent=new Intent(this,Favourite.class);
            startActivity(intent);
        }  else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}
</code>```

My adapter class

```<code>public class FullverseAdopter extends ArrayAdapter<String> {
    private ALLVERSE activity;
    private List<String> versenumber;
    private List<String>verseid;
    private List<String> verselist;
    private List<String> refernce;
    TextToSpeech textToSpeech;
    private DatabaseHelper mDBHelper;
    private SQLiteDatabase mDb;
    private  boolean ischeckd;
    String My_PREF="MY_PREF";

    public  String ex="switch";

    //check for availabe language
    int result;

    public FullverseAdopter(ALLVERSE context, int resource, List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid) {
        super(context, resource, versenumber);
        this.activity = context;
        this.versenumber = versenumber;
        this.verselist = verselist;
        this.refernce = refernce;
        this.verseid=verseid;
    }

    @Override
    public int getCount() {
        return versenumber.size();
    }

    @Override
    public String getItem(int position) {
        return versenumber.get(position);
    }

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

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        final ViewHolder holder;

        LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        // If holder not exist then locate all view from UI file.
        if (convertView == null) {
            // inflate UI from XML file
            convertView = inflater.inflate(R.layout.versedisplayrow, parent, false);
            // get all UI view
            holder = new ViewHolder(convertView);
            // set tag for holder
            holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
            holder.verselist = (TextView) convertView.findViewById(R.id.verse);
            holder.addfavoruite=(ToggleButton)convertView.findViewById(R.id.adbookmark);

            convertView.setTag(holder);
        } else {
            // if holder created, get tag from view
            holder = (ViewHolder) convertView.getTag();
        }
        holder.versenumber.setText(versenumber.get(position));
        holder.verselist.setText(verselist.get(position));

        //verselist highlight
    /*holder.verselist.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        }
    });*/

        //share verse
        holder.share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n'   + verselist.get(position));
                sendIntent.setType("text/plain");
                activity.startActivity(sendIntent);
            }
        });

        //add in favourite
        holder.addfavoruite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if(isChecked){
                    mDBHelper = new DatabaseHelper(activity);
                    mDb = mDBHelper.getWritableDatabase();
                    ContentValues contentValues=new ContentValues();
                    contentValues.put("id",verseid.get(position));
                    contentValues.put("bookname",refernce.get(position));
                    contentValues.put("versenumber",versenumber.get(position));
                    contentValues.put("verse",verselist.get(position));
                    long check=mDb.insert("favourite",null,contentValues);
                    Log.d("MY_TAG","DB IS NOW "+check);

                    Toasty.success(activity, "Added in favouite", Toast.LENGTH_SHORT, true).show();
                }else {
                    mDBHelper = new DatabaseHelper(activity);
                    mDb = mDBHelper.getWritableDatabase();
                    long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
                    Toasty.error(activity, "Remove in favouite", Toast.LENGTH_SHORT, true).show();
                }
            }
        });

           /* textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
                @Override
                public void onInit(int status) {

                    if (status == TextToSpeech.SUCCESS) {
                        result = textToSpeech.setLanguage(Locale.ENGLISH);
                    } else {

                        Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
                    }
                }
            });
    */

        //My toggle button
           /* holder.speakverse.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();

                    if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {

                        Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();

                    } else {

                        textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);
                    }
                }
            });*/
        return convertView;
    }

    static class ViewHolder {
        private TextView versenumber;
        private TextView verselist;
        private ImageView share;
        private  ToggleButton addfavoruite;
        private ImageView speakverse;

        public ViewHolder(View v) {
            versenumber = (TextView) v.findViewById(R.id.versenumber);
            verselist = (TextView) v.findViewById(R.id.verse);
            share = (ImageView) v.findViewById(R.id.share);
            /*speakverse = (ImageView) v.findViewById(R.id.speakverse);*/
            addfavoruite=(ToggleButton)v.findViewById(R.id.adbookmark);
        }
    }

    public boolean CheckIsDataAlreadyInDBorNot(String TableName,  String dbfield, String fieldValue) {

        mDBHelper = new DatabaseHelper(activity);
        mDb = mDBHelper.getReadableDatabase();
        String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
        Cursor cursor = mDb.rawQuery(Query, null);
        if(cursor.getCount() <= 0){
            cursor.close();

            Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
            return false;
        }else {

            Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();
        }
        cursor.close();
        return true;
    }

    public  void opecolorpicker(){
        ColorPicker colorPicker = new ColorPicker(activity);
        ArrayList<String>colors=new ArrayList<>();
        colors.add("#FF0000");
        colors.add("#FFEC33");
        colors.add("#3C33FF");
        colors.add("#DA33FF");
        colors.add("#33FF99");
        colors.add("#90FF33");
        colors.add("#DD33FF");
        colors.add("#F0B27A");
        colors.add("#DAF7A6");
        colors.add("#34495E");

        colorPicker.setColors(colors).setTitle("HIGHLIGHT VERSE").setRoundColorButton(true).setOnChooseColorListener(new ColorPicker.OnChooseColorListener() {
            @Override
            public void onChooseColor(int position, int color) {

                Toast.makeText(activity, ""+color, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {
            }
        }).show();
    }
}
</code>```

答:
You Can set drawable files as background as backgroundselector_list.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@android:color/holo_blue_light"/>
    <item android:state_enabled="true" android:state_pressed="true" android:drawable="@android:color/holo_blue_light" />
    <item android:state_enabled="true" android:state_focused="true" android:drawable="@android:color/holo_blue_bright" />
    <item android:state_enabled="true" android:state_selected="true" android:drawable="@android:color/holo_blue_light" />
    <item android:state_activated="true" android:drawable="@android:color/holo_blue_light" />
    <item android:drawable="@android:color/transparent"/>
</selector>
</code>```

And set this as

```<code> android:background="@drawable/backgroundselector_list"
</code>```

to your TextView item in versedisplayrow.xml

Body:
I'm implementing a ListView with ArrayAdapter. Whenever any ListView item is clicked, I'd like the text color of the item to be changed and also saved in SharedPreference. I'm a beginner I don't know how to implement it.

Please help me to achieve this goal. I tried many sources but the problem couldn't be solved.

Here is my code.

public class ALLVERSE extends AppCompatActivity  implements NavigationView.OnNavigationItemSelectedListener {
    private ListView mylistview;
    private ArrayList<String>versenumber;
    private ArrayList<String>verselist;
    private ArrayList<String>id;
    private  ArrayList<String>refernce;
    private DatabaseHelper mDBHelper;
    private SQLiteDatabase mDb;
    private int booknumber;
    private  int chapternumber;
    private  String bookname;
    private TextView booknametitle;
    private  FullverseAdopter fullverseAdopter;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        booknametitle=findViewById(R.id.bookname);

        Intent mIntent = getIntent();
        booknumber = mIntent.getIntExtra("Boooknumber",0);
        chapternumber= mIntent.getIntExtra("Chapternumber", 0);
        bookname=mIntent.getStringExtra("Bookname");

        booknametitle.setText(bookname.toString() +"   "+  chapternumber);

        //Toast.makeText(this, ""+bookname, Toast.LENGTH_SHORT).show();
        setSupportActionBar(toolbar);
        toolbar.setTitle("ALL VERSE");

        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        setData();

        mylistview=findViewById(R.id.mylistview);

        fullverseAdopter=new FullverseAdopter(ALLVERSE.this,R.layout.versedisplayrow,versenumber,verselist,refernce,id);

        mylistview.setAdapter(fullverseAdopter);

        mylistview.setOnItemClickListener(new AdapterView.OnItemClickListener(){

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

                Toast.makeText(ALLVERSE.this, "i am cliked", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // handle arrow click here
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }

    private void setData() {
        versenumber=new ArrayList<>();
        verselist=new ArrayList<>();
        refernce=new ArrayList<>();
        id=new ArrayList<>();

        mDBHelper = new DatabaseHelper(this);
        mDb = mDBHelper.getReadableDatabase();
        Cursor cursor = mDb.rawQuery("SELECT id, v, t from t_kjv where b="+booknumber+" AND c="+chapternumber+";", new String[]{});
        if(cursor!=null && cursor.getCount() > 0)
        { if (cursor.moveToFirst())
        {
            do {
                id.add(cursor.getString(0));
                versenumber.add(cursor.getString(1));
                verselist.add(cursor.getString(2));
                refernce.add(bookname+" "+chapternumber);
            }
            while (cursor.moveToNext());
        }
        }
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        Fragment fragment;
        int id = item.getItemId();
        if (id == R.id.home) {
            Intent intent=new Intent(this,MainActivity.class);
            startActivity(intent);

        } else if (id == R.id.favoruite)
        { Intent intent=new Intent(this,Favourite.class);
            startActivity(intent);
        }  else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

My adapter class

public class FullverseAdopter extends ArrayAdapter<String> {
    private ALLVERSE activity;
    private List<String> versenumber;
    private List<String>verseid;
    private List<String> verselist;
    private List<String> refernce;
    TextToSpeech textToSpeech;
    private DatabaseHelper mDBHelper;
    private SQLiteDatabase mDb;
    private  boolean ischeckd;
    String My_PREF="MY_PREF";

    public  String ex="switch";

    //check for availabe language
    int result;

    public FullverseAdopter(ALLVERSE context, int resource, List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid) {
        super(context, resource, versenumber);
        this.activity = context;
        this.versenumber = versenumber;
        this.verselist = verselist;
        this.refernce = refernce;
        this.verseid=verseid;
    }

    @Override
    public int getCount() {
        return versenumber.size();
    }

    @Override
    public String getItem(int position) {
        return versenumber.get(position);
    }

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

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        final ViewHolder holder;

        LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        // If holder not exist then locate all view from UI file.
        if (convertView == null) {
            // inflate UI from XML file
            convertView = inflater.inflate(R.layout.versedisplayrow, parent, false);
            // get all UI view
            holder = new ViewHolder(convertView);
            // set tag for holder
            holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
            holder.verselist = (TextView) convertView.findViewById(R.id.verse);
            holder.addfavoruite=(ToggleButton)convertView.findViewById(R.id.adbookmark);

            convertView.setTag(holder);
        } else {
            // if holder created, get tag from view
            holder = (ViewHolder) convertView.getTag();
        }
        holder.versenumber.setText(versenumber.get(position));
        holder.verselist.setText(verselist.get(position));

        //verselist highlight
    /*holder.verselist.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        }
    });*/

        //share verse
        holder.share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n'   + verselist.get(position));
                sendIntent.setType("text/plain");
                activity.startActivity(sendIntent);
            }
        });

        //add in favourite
        holder.addfavoruite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if(isChecked){
                    mDBHelper = new DatabaseHelper(activity);
                    mDb = mDBHelper.getWritableDatabase();
                    ContentValues contentValues=new ContentValues();
                    contentValues.put("id",verseid.get(position));
                    contentValues.put("bookname",refernce.get(position));
                    contentValues.put("versenumber",versenumber.get(position));
                    contentValues.put("verse",verselist.get(position));
                    long check=mDb.insert("favourite",null,contentValues);
                    Log.d("MY_TAG","DB IS NOW "+check);

                    Toasty.success(activity, "Added in favouite", Toast.LENGTH_SHORT, true).show();
                }else {
                    mDBHelper = new DatabaseHelper(activity);
                    mDb = mDBHelper.getWritableDatabase();
                    long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
                    Toasty.error(activity, "Remove in favouite", Toast.LENGTH_SHORT, true).show();
                }
            }
        });

           /* textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
                @Override
                public void onInit(int status) {

                    if (status == TextToSpeech.SUCCESS) {
                        result = textToSpeech.setLanguage(Locale.ENGLISH);
                    } else {

                        Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
                    }
                }
            });
    */

        //My toggle button
           /* holder.speakverse.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();

                    if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {

                        Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();

                    } else {

                        textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);
                    }
                }
            });*/
        return convertView;
    }

    static class ViewHolder {
        private TextView versenumber;
        private TextView verselist;
        private ImageView share;
        private  ToggleButton addfavoruite;
        private ImageView speakverse;

        public ViewHolder(View v) {
            versenumber = (TextView) v.findViewById(R.id.versenumber);
            verselist = (TextView) v.findViewById(R.id.verse);
            share = (ImageView) v.findViewById(R.id.share);
            /*speakverse = (ImageView) v.findViewById(R.id.speakverse);*/
            addfavoruite=(ToggleButton)v.findViewById(R.id.adbookmark);
        }
    }

    public boolean CheckIsDataAlreadyInDBorNot(String TableName,  String dbfield, String fieldValue) {

        mDBHelper = new DatabaseHelper(activity);
        mDb = mDBHelper.getReadableDatabase();
        String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
        Cursor cursor = mDb.rawQuery(Query, null);
        if(cursor.getCount() <= 0){
            cursor.close();

            Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
            return false;
        }else {

            Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();
        }
        cursor.close();
        return true;
    }

    public  void opecolorpicker(){
        ColorPicker colorPicker = new ColorPicker(activity);
        ArrayList<String>colors=new ArrayList<>();
        colors.add("#FF0000");
        colors.add("#FFEC33");
        colors.add("#3C33FF");
        colors.add("#DA33FF");
        colors.add("#33FF99");
        colors.add("#90FF33");
        colors.add("#DD33FF");
        colors.add("#F0B27A");
        colors.add("#DAF7A6");
        colors.add("#34495E");

        colorPicker.setColors(colors).setTitle("HIGHLIGHT VERSE").setRoundColorButton(true).setOnChooseColorListener(new ColorPicker.OnChooseColorListener() {
            @Override
            public void onChooseColor(int position, int color) {

                Toast.makeText(activity, ""+color, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {
            }
        }).show();
    }
}

Body:
You Can set drawable files as background as backgroundselector_list.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@android:color/holo_blue_light"/>
    <item android:state_enabled="true" android:state_pressed="true" android:drawable="@android:color/holo_blue_light" />
    <item android:state_enabled="true" android:state_focused="true" android:drawable="@android:color/holo_blue_bright" />
    <item android:state_enabled="true" android:state_selected="true" android:drawable="@android:color/holo_blue_light" />
    <item android:state_activated="true" android:drawable="@android:color/holo_blue_light" />
    <item android:drawable="@android:color/transparent"/>
</selector>

And set this as

 android:background="@drawable/backgroundselector_list"

to your TextView item in versedisplayrow.xml


来源: stackexchange

问:
android Seekbar show progress value along the seekbar
I have a listview with seekbar, each seekbar represents 100% of a value of product. By moving the seekbar the % value can be changed, I want to show the change in value along the seekbar while the user is dragging the seekbar. I do not wish to add another text box where the value is updated.

I am more looking at options to show a small view on top of the seekbar pointer, which appears onStartTracking and disappears onStopTracking event.

Is there a way to achieve this?

答:
The accepted answer is probably good enough for most situations. However, if you want precision so that the text is exactly in the middle of your seek bar thumb, you have to a little more calculations. This is because the width of the text is different. Say, you want to show numbers from 0 to 150. Width of 188 will be different from 111. Because of this, the text you are showing will always tilt to some side.

The way to solve it is to measure the width of the text, remove that from the width of the seekbar thumb, divide it by 2, and add that to the result that was given in the accepted answer.  Now you would not care about how large the number range. Here is the code:

```<code> override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                    val value = progress * (seekBar.width - 2 * seekBar.thumbOffset) / seekBar.max
                    label.text = progress.toString()
                    label.measure(0, 0)
                    val textWidth =  label.measuredWidth
                    val firstRemainder = seekThumbWidth - textWidth
                    val result = firstRemainder / 2
                    label.x = (seekBar.x + value + result)
                }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The accepted answer is probably good enough for most situations. However, if you want precision so that the text is exactly in the middle of your seek bar thumb, you have to a little more calculations. This is because the width of the text is different. Say, you want to show numbers from 0 to 150. Width of 188 will be different from 111. Because of this, the text you are showing will always tilt to some side.

The way to solve it is to measure the width of the text, remove that from the width of the seekbar thumb, divide it by 2, and add that to the result that was given in the accepted answer.  Now you would not care about how large the number range. Here is the code:

 override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                    val value = progress * (seekBar.width - 2 * seekBar.thumbOffset) / seekBar.max
                    label.text = progress.toString()
                    label.measure(0, 0)
                    val textWidth =  label.measuredWidth
                    val firstRemainder = seekThumbWidth - textWidth
                    val result = firstRemainder / 2
                    label.x = (seekBar.x + value + result)
                }

ContentLicense: CC BY-SA 4.0


问:
Jmeter random function is not working from java application
I want to make use of Jmeter Random function (${__RandomString(10,0123456789,Value)}) in my java application for load testing.

Below is maven dependency

```<code><dependency>
    <groupId>org.apache.jmeter</groupId>
    <artifactId>ApacheJMeter_functions</artifactId>
    <version>4.0</version>
</dependency>
</code>```

It is working properly If I add ApacheJMeter_functions jar to class path but the same is not working if I use Maven dependency.

Note : Works fine if I add jar to classpath without version name.

pom :

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <artifactId>performance-api</artifactId>
    <version>0.1</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.jmeter</groupId>
            <artifactId>ApacheJMeter_core</artifactId>
            <version>4.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.jmeter</groupId>
            <artifactId>ApacheJMeter_http</artifactId>
            <version>4.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.jmeter</groupId>
            <artifactId>ApacheJMeter_functions</artifactId>
            <version>4.0</version>
            </dependency>
    </dependencies>
    <build>
        <plugins>

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                        </execution>
                </executions>
            </plugin>

        </plugins>
    </build>
</project>
</code>```

Response when added ApacheJMeter_functions jar to class path without version name

Response when added ApacheJMeter_functions dependency jar into pom

答:
Below solution helped me in resolving issue

When Jmeter functions are used in the Java code, Jmeter tries to compare the function related classes from java class path with classes from the 'search_path' (Reads classes from the jars). So Jmeter function works only if required function class is present in both the path (Jmeter has seperate class for each function).

This is why we need to make sure the 'ApacheJMeter_functions' jar added in the pom (which will be added in class path ) and the path to jmeter functions jar is set to 'search_path'.Both should have same version.

But in case of spring boot application, along adding dependency to pom we also need to append the path to jmeter functions jar explicitly to the class path like below

```<code>System.setProperty("java.class.path", System.getProperty("java.class.path") + PathToJmeterFunctionJars );
</code>```

Body:
I want to make use of Jmeter Random function (${__RandomString(10,0123456789,Value)}) in my java application for load testing.

Below is maven dependency

<dependency>
    <groupId>org.apache.jmeter</groupId>
    <artifactId>ApacheJMeter_functions</artifactId>
    <version>4.0</version>
</dependency>

It is working properly If I add ApacheJMeter_functions jar to class path but the same is not working if I use Maven dependency.

Note : Works fine if I add jar to classpath without version name.

pom :

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <artifactId>performance-api</artifactId>
    <version>0.1</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.jmeter</groupId>
            <artifactId>ApacheJMeter_core</artifactId>
            <version>4.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.jmeter</groupId>
            <artifactId>ApacheJMeter_http</artifactId>
            <version>4.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.jmeter</groupId>
            <artifactId>ApacheJMeter_functions</artifactId>
            <version>4.0</version>
            </dependency>
    </dependencies>
    <build>
        <plugins>

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                        </execution>
                </executions>
            </plugin>

        </plugins>
    </build>
</project>

Response when added ApacheJMeter_functions jar to class path without version name

Response when added ApacheJMeter_functions dependency jar into pom

Body:
Below solution helped me in resolving issue

When Jmeter functions are used in the Java code, Jmeter tries to compare the function related classes from java class path with classes from the 'search_path' (Reads classes from the jars). So Jmeter function works only if required function class is present in both the path (Jmeter has seperate class for each function).

This is why we need to make sure the 'ApacheJMeter_functions' jar added in the pom (which will be added in class path ) and the path to jmeter functions jar is set to 'search_path'.Both should have same version.

But in case of spring boot application, along adding dependency to pom we also need to append the path to jmeter functions jar explicitly to the class path like below

System.setProperty("java.class.path", System.getProperty("java.class.path") + PathToJmeterFunctionJars );


问:
How to check if the stored procedure is scheduled to run at specific time
In my SQL Server 2008, a stored procedure P_ABC is scheduled to run everyday at 2 a.m.

But how can I verify that this procedure P_ABC is scheduled to run everyday at 2 a.m. or not and it is always running at 2 a.m.? Is there any query to get the lists of procedures that are scheduled to run at specific time?

答:
It's too old question but still I am posting this. You can try -

```<code>CREATE PROCEDURE MyTask
 AS
BEGIN
    SET NOCOUNT ON;
    --  For executing the stored procedure at 11:00 P.M
    declare @delayTime nvarchar(50)
    set @delayTime = '23:00'

    while 1 = 1
    begin
        waitfor time @delayTime
        begin
            --Name for the stored proceduce you want to call on regular bases
            execute [DatabaseName].[dbo].[StoredProcedureName];
        end
    end
END
</code>```

Then,

```<code>-- Sets stored procedure for automatic execution.
sp_procoption    @ProcName = 'MyTask',
                @OptionName = 'startup',
                @OptionValue = 'on'
</code>```

Body:
It's too old question but still I am posting this. You can try -

CREATE PROCEDURE MyTask
 AS
BEGIN
    SET NOCOUNT ON;
    --  For executing the stored procedure at 11:00 P.M
    declare @delayTime nvarchar(50)
    set @delayTime = '23:00'

    while 1 = 1
    begin
        waitfor time @delayTime
        begin
            --Name for the stored proceduce you want to call on regular bases
            execute [DatabaseName].[dbo].[StoredProcedureName];
        end
    end
END

Then,

-- Sets stored procedure for automatic execution.
sp_procoption    @ProcName = 'MyTask',
                @OptionName = 'startup',
                @OptionValue = 'on'


问:
why my Runnable Interface Looping my Queue Continue here
here i want to running my all List a with the limited size of Queue b if an element b.poll()(remove from queue and take it for use) it again add a. element from List a and so on....

i already tried multiple way to stop looping.

```<code>public class BroadcastThreadInitializerProcessor implements Runnable {
@Autowired
private NetworkInterfaceServiceInterface networkInterfaceServiceInterface;

private volatile boolean running = true;
private volatile boolean paused = false;

private VoiceBroadcast voiceBroadcast =null;

List<ExcelDatas> a = null;

public BroadcastThreadInitializerProcessor(VoiceBroadcast voiceBroadcast, UploadExcel uploadExcel ) {
    this.voiceBroadcast=voiceBroadcast;
            this.a = uploadExcel.getExcelDatas();
}

@Override
public void run() {
     while (running){
        synchronized (a) {
            if (!running) {
                break;
            }
            if (paused) {
                try {
                    a.wait();
                } catch (InterruptedException ex) {
                     break;
                }
                if (!running) { // running might have changed since we paused
                    break;
                }
            }
        }//syncronized stop

     // Broadcasting code START here...
        int channels = Integer.parseInt(voiceBroadcast.getChannel());
        try {
         Queue<ExcelDatas> b = null;
         int aIndex  = 0;
         if(a.size()> channels){  //load elements in Queue
             b = new LinkedList<>();
             for (int i = 0; i < channels ; i++) {
                 b.add(a.get(aIndex));
                 aIndex++;
             }
         }else {
             b = new LinkedList<>(a); //load all elements
         }
          Client client = new Client();
            client.connect("",  , "", 10);
            client.setEventSubscriptions( "", "" );
            boolean looping = true;

    while (looping) {   //looping while

        if (paused) {
          a.wait();
        }
    if (!running) { looping=false; break;} // break when all call are completed
    if (b.isEmpty()) { running=false; break;} // break when all call are completed
    EslMessage chan = client.sendSyncApiCommand("show channels count","");
            int usedChannel = Integer.parseInt(Arrays.asList(chan.getBodyLines().toString().replaceAll("[^0-9]+"," ").trim().split(" ")).get(0));
         if(usedChannel<(channels-1)) {
             System.err.println("Used Channels "+usedChannel +" <--Total Channels"+channels);
                ExcelDatas frontValue = b.poll(); // get queue's first element and remove it
            String uuid = UUID.randomUUID().toString();

            if(frontValue.getContact().length()>=10) {
                  client.sendSyncApiCommand("",""); //for calling
                  System.err.println("Callling on "+frontValue.getContact()+" By clip number:-"+voiceBroadcast.getClip()+" with UUID:-"+uuid);
                }//if for Contact number

         //call Processs    Stop
           if(a.size()> channels){
            if (aIndex  < a.size()) {
                b.add(a.get(aIndex++)); //Add of New Node in Queue
            }//inner if node set
           }//if upper
        //for close all loops if b is empty
    if(b.isEmpty()) {
      System.err.println("b is empty");
      running = false;
      looping=false;
      break;
    }//if

            Thread.sleep(700);
     }//upper if   ports check

    }//Stop looping while loop

      looping=false;
      running = false;
      client.close();
     }catch (Exception e) {

    }

 // Broadcasting code STOP here...
  }//while loop

 }//run() method STOP

// Actions methods Start
public void terminate() {
    running = false;
}

public void pause() {
   paused = true;
}

public void resume() {
    synchronized (a) {
        paused = false;
        a.notifyAll(); // Unblocks thread
    }
}
//Action Methods STOP
}
</code>```

But my Code react as First Queue size is running repeatedly again and again with only these element (if a.size()>channel where channel is b.size()) and its not going to next elements NOR Exit the while(looping).

can any one solve/explain/describe it ? Thanks ...

答:
here i changed just,

```<code>private static  BlockingQueue<ExcelDatas> queue = null;
......
......
 queue = new ArrayBlockingQueue<>(channels);
.......
.......
ExcelDatas frontValue = queue.take();
</code>```

and it solve my problem thanks @AntoineMarques.

Body:
here i want to running my all List a with the limited size of Queue b if an element b.poll()(remove from queue and take it for use) it again add a. element from List a and so on....

i already tried multiple way to stop looping.

public class BroadcastThreadInitializerProcessor implements Runnable {
@Autowired
private NetworkInterfaceServiceInterface networkInterfaceServiceInterface;

private volatile boolean running = true;
private volatile boolean paused = false;

private VoiceBroadcast voiceBroadcast =null;

List<ExcelDatas> a = null;

public BroadcastThreadInitializerProcessor(VoiceBroadcast voiceBroadcast, UploadExcel uploadExcel ) {
    this.voiceBroadcast=voiceBroadcast;
            this.a = uploadExcel.getExcelDatas();
}

@Override
public void run() {
     while (running){
        synchronized (a) {
            if (!running) {
                break;
            }
            if (paused) {
                try {
                    a.wait();
                } catch (InterruptedException ex) {
                     break;
                }
                if (!running) { // running might have changed since we paused
                    break;
                }
            }
        }//syncronized stop

     // Broadcasting code START here...
        int channels = Integer.parseInt(voiceBroadcast.getChannel());
        try {
         Queue<ExcelDatas> b = null;
         int aIndex  = 0;
         if(a.size()> channels){  //load elements in Queue
             b = new LinkedList<>();
             for (int i = 0; i < channels ; i++) {
                 b.add(a.get(aIndex));
                 aIndex++;
             }
         }else {
             b = new LinkedList<>(a); //load all elements
         }
          Client client = new Client();
            client.connect("",  , "", 10);
            client.setEventSubscriptions( "", "" );
            boolean looping = true;

    while (looping) {   //looping while

        if (paused) {
          a.wait();
        }
    if (!running) { looping=false; break;} // break when all call are completed
    if (b.isEmpty()) { running=false; break;} // break when all call are completed
    EslMessage chan = client.sendSyncApiCommand("show channels count","");
            int usedChannel = Integer.parseInt(Arrays.asList(chan.getBodyLines().toString().replaceAll("[^0-9]+"," ").trim().split(" ")).get(0));
         if(usedChannel<(channels-1)) {
             System.err.println("Used Channels "+usedChannel +" <--Total Channels"+channels);
                ExcelDatas frontValue = b.poll(); // get queue's first element and remove it
            String uuid = UUID.randomUUID().toString();

            if(frontValue.getContact().length()>=10) {
                  client.sendSyncApiCommand("",""); //for calling
                  System.err.println("Callling on "+frontValue.getContact()+" By clip number:-"+voiceBroadcast.getClip()+" with UUID:-"+uuid);
                }//if for Contact number

         //call Processs    Stop
           if(a.size()> channels){
            if (aIndex  < a.size()) {
                b.add(a.get(aIndex++)); //Add of New Node in Queue
            }//inner if node set
           }//if upper
        //for close all loops if b is empty
    if(b.isEmpty()) {
      System.err.println("b is empty");
      running = false;
      looping=false;
      break;
    }//if

            Thread.sleep(700);
     }//upper if   ports check

    }//Stop looping while loop

      looping=false;
      running = false;
      client.close();
     }catch (Exception e) {

    }

 // Broadcasting code STOP here...
  }//while loop

 }//run() method STOP

// Actions methods Start
public void terminate() {
    running = false;
}

public void pause() {
   paused = true;
}

public void resume() {
    synchronized (a) {
        paused = false;
        a.notifyAll(); // Unblocks thread
    }
}
//Action Methods STOP
}

But my Code react as First Queue size is running repeatedly again and again with only these element (if a.size()>channel where channel is b.size()) and its not going to next elements NOR Exit the while(looping).

can any one solve/explain/describe it ? Thanks ...

Body:
here i changed just,

private static  BlockingQueue<ExcelDatas> queue = null;
......
......
 queue = new ArrayBlockingQueue<>(channels);
.......
.......
ExcelDatas frontValue = queue.take();

and it solve my problem thanks @AntoineMarques.


问:
Passing properties from native to React Native when using Wix React Native Navigation (RNN)
Passing properties from native to React Native is described here. Here's a summary:

NSArray *imageList = @[@"http://foo.com/bar1.png",
                       @"http://foo.com/bar2.png"];

NSDictionary *props = @{@"images" : imageList};

RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                 moduleName:@"ImageBrowserApp"
                                          initialProperties:props];
```

<p>However, when using Wix React Native Navigation, there is no <code>rootView</code>. According to the docs, this is what a minimal RNN setup looks like on iOS:</p>

<pre class="lang-c prettyprint-override"><code> #import "AppDelegate.h"

 #import <React/RCTBundleURLProvider.h>
 #import <React/RCTRootView.h>
 #import <ReactNativeNavigation/ReactNativeNavigation.h>

 @implementation AppDelegate

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {
     NSURL *jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
     [ReactNativeNavigation bootstrap:jsCodeLocation launchOptions:launchOptions];

     return YES;
 }

 @end
</code>```

How do we go about passing props from native?

答:
As I passing property from React Native to native iOS you need to check for native iOS to React Native property passing. Here is my code

In iOS

Appdelegate.h

```<code>#import <UIKit/UIKit.h>
#import "React/RCTBridgeModule.h"

@import Firebase;
@interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeModule>

@property (strong, nonatomic) UIWindow *window;

@end
</code>```

Appdelegate.m

```<code>#import "RCTBundleURLProvider.h"
#import <React/RCTLog.h>

@implementation AppDelegate

RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(addEvent:(NSString *)propertyName)
{
    //Here you get your property value
    var property = propertyName;
    RCTLogInfo(@"Pretending to create an event %@ at %@", areaId);
}
</code>```

In React Native

MyComponent.js

```<code>import { NativeModules } from 'react-native';

var AppDelegate = NativeModules.AppDelegate;
AppDelegate.addEvent(value);
</code>```

Body:
Passing properties from native to React Native is described here. Here's a summary:

NSArray *imageList = @[@"http://foo.com/bar1.png",
                       @"http://foo.com/bar2.png"];

NSDictionary *props = @{@"images" : imageList};

RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                 moduleName:@"ImageBrowserApp"
                                          initialProperties:props];

However, when using Wix React Native Navigation, there is no rootView. According to the docs, this is what a minimal RNN setup looks like on iOS:

 #import "AppDelegate.h"

 #import <React/RCTBundleURLProvider.h>
 #import <React/RCTRootView.h>
 #import <ReactNativeNavigation/ReactNativeNavigation.h>

 @implementation AppDelegate

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {
     NSURL *jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
     [ReactNativeNavigation bootstrap:jsCodeLocation launchOptions:launchOptions];

     return YES;
 }

 @end

How do we go about passing props from native?

Body:
As I passing property from React Native to native iOS you need to check for native iOS to React Native property passing. Here is my code

In iOS

Appdelegate.h

#import <UIKit/UIKit.h>
#import "React/RCTBridgeModule.h"

@import Firebase;
@interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeModule>

@property (strong, nonatomic) UIWindow *window;

@end

Appdelegate.m

#import "RCTBundleURLProvider.h"
#import <React/RCTLog.h>

@implementation AppDelegate

RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(addEvent:(NSString *)propertyName)
{
    //Here you get your property value
    var property = propertyName;
    RCTLogInfo(@"Pretending to create an event %@ at %@", areaId);
}

In React Native

MyComponent.js

import { NativeModules } from 'react-native';

var AppDelegate = NativeModules.AppDelegate;
AppDelegate.addEvent(value);


问:
How to dynamically set an image or use default
I am mapping through objects and would like to dynamically add the image source, but if there is not an image, id like to load the default image. Ideally this take as little computational power as can be because there are lots of images that will change often..

I already have the dynamic image src setup, but i dont have the loop to check if it exists. Just wondering what the fastest way to do this is.

```<code>...
render() {
    const images = require.context("../../../../../public/images", true);
...

return {
{this.props.items.map...

<img src={images(`./${item.item}`)} />

....)}
</code>```

答:
If you mean that item.item might be null or nonexistent, you could simply OR it with the default: item.item || default.png.

If you mean item.item is present but may fail to load, you could set an onError handler on the image and set the arc to the default if it errors.

An alternate way to do the onError approach would be to set the src to the default image initially for all the  elements and instantiate an Image object to load item.item. If it succeeds, update the  accordingly. If it fails you’ve already got the fallback image.

Here's a fiddle showing how you could load a default image initially, load the real image, and display an error image if loading fails:

https://jsfiddle.net/rayhatfield/ouqyav7p/22/

Body:
I am mapping through objects and would like to dynamically add the image source, but if there is not an image, id like to load the default image. Ideally this take as little computational power as can be because there are lots of images that will change often..

I already have the dynamic image src setup, but i dont have the loop to check if it exists. Just wondering what the fastest way to do this is.

...
render() {
    const images = require.context("../../../../../public/images", true);
...

return {
{this.props.items.map...

<img src={images(`./${item.item}`)} />

....)}

Body:
If you mean that item.item might be null or nonexistent, you could simply OR it with the default: item.item || default.png.

If you mean item.item is present but may fail to load, you could set an onError handler on the image and set the arc to the default if it errors.

An alternate way to do the onError approach would be to set the src to the default image initially for all the <img> elements and instantiate an Image object to load item.item. If it succeeds, update the <img> accordingly. If it fails you’ve already got the fallback image.

Here's a fiddle showing how you could load a default image initially, load the real image, and display an error image if loading fails:

https://jsfiddle.net/rayhatfield/ouqyav7p/22/


问:
In Java when one interface extends another, why would one redeclare a method in a subinterface?
I've been looking at the JMS API from J2EE and found a strange behavior where certain methods that are declared in an interface (e.g., createQueue in Session) are declared again in the subinterfaces such as QueueSession, and with identical documentation.

Since an subinterface "inherits" all the method declarations of the interface it inherits, and since the JavaDoc tool has no problem sorting out the JavaDocs of the subinterface and creating an "inherited operations" list, I can't figure out what this achieves.

The only think of is that initially the call was in Session, and then moved to QueueSession when the specific subclass was created, though then I would have expected to see something in the documentation of the upperclass. But this is just conjecture.

So the question is:
Is there a convincing reason to redeclare a method in a subinterface?

答:
Having seen this happen on occasion while working for Sun, I can tell you how it usually happens.  Someone defines an interface, let's say Alice, with some methods; many developers implement that interface.

Some time later, it's realized that they need some other interface, call it Bob, that has a subset of the methods of Alice, in order to allow it to serve as a base interface for another interface, Clara.

If you move the methods of Alice into Bob, you break all the code that implements Alice; you have to go back and at least recompile a whole bunch of code, some of which you may not own, and for political reasons can't break.

So you don't.

OwnerDisplayName: Uri

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Charlie Martin


问:
OpenGL on Mac operation
This is really architecture question or 'how does it work' question than a problem to solve.

Apple documentation claims that CGL is lowest level api for managing OpenGL contexts, yet is lacks functionality that allows to connect a context to a window.
AGL and Cocoa can bind a context to a window without a problem though, so the question is - how do they do that if they are built upon CGL?

The obvious way appears to be that they use CGL to render to offscreen memory and are then capable of compositing this somehow. If this is so, how does that happen?

答: There is a private function CGLSetSurface that connects a surface that is part of a window to a GL context created with CGLCreateContext. Both AGL and Cocoa use this function internally.</p>

Title: OpenGL on Mac operation


问:
Database wont update with PHP when there's multiple radios selected? Only the lastest radio selected will get updated
Let's say I have a form with 2 numbers and 4 radio buttons on each and only 1 option can be selected on each number.

When I submit, only the question 2's database will be updated. But if I leave #2 blank, question 1's database works or can be updated.

They only won't work if I submit them together.

The HTML Code

1. <?php echo $question1 ?>

<?php echo $q1option1 ?>
<input type="radio" name="q1" value="c1">

<?php echo $q1option2 ?>
<input type="radio" name="q1" value="c2">

2. <?php echo $question2 ?>

<?php echo $q2option1 ?>
<input type="radio" name="q2" value="c1">

<?php echo $q2option2 ?>
<input type="radio" name="q2" value="c2">

```

<p>The PHP Code</p>

<pre class="lang-php prettyprint-override"><code>$q1 = $_POST['q1'];

    if ($q1 == "c1" ) {

        $query = "UPDATE `question1` SET score = score + 1 WHERE choices = 'choice1'";
    }
    if ($q1 == "c2" ) {

        $query = "UPDATE `question1` SET score = score + 1 WHERE choices = 'choice2'";
    }

$q2 = $_POST['q2'];

    if ($q2 == "c1" ) {

        $query = "UPDATE `question2` SET score = score + 1 WHERE choices = 'choice1'";
    }
    if ($q2 == "c2" ) {

        $query = "UPDATE `question2` SET score = score + 1 WHERE choices = 'choice2'";
    }
</code>```

They should be updating the score +1 everytime someone choices the option when submitted. How do I fix this? Please check my code.

答:
You are using same variable for both questions so if both question submitted but last query will work as you defined same variable

```<code>$q1 = $_POST['q1'];
$query="";
$query2="";
if ($q1 == "c1" ) {

    $query = "UPDATE `question1` SET score = score + 1 WHERE choices = 'choice1'";
}
if ($q1 == "c2" ) {

    $query = "UPDATE `question1` SET score = score + 1 WHERE choices = 'choice2'";
}
if($query){
//execute first query here
}

$q2 = $_POST['q2'];

if ($q2 == "c1" ) {

    $query2 = "UPDATE `question2` SET score = score + 1 WHERE choices = 'choice1'";
}
if ($q2 == "c2" ) {

    $query2 = "UPDATE `question2` SET score = score + 1 WHERE choices = 'choice2'";
}
if($query2){
//execute second query here
}
</code>```

Hope this helps you

Body:
Let's say I have a form with 2 numbers and 4 radio buttons on each and only 1 option can be selected on each number.

When I submit, only the question 2's database will be updated. But if I leave #2 blank, question 1's database works or can be updated.

They only won't work if I submit them together.

The HTML Code

1. <?php echo $question1 ?>

<?php echo $q1option1 ?>
<input type="radio" name="q1" value="c1">

<?php echo $q1option2 ?>
<input type="radio" name="q1" value="c2">

2. <?php echo $question2 ?>

<?php echo $q2option1 ?>
<input type="radio" name="q2" value="c1">

<?php echo $q2option2 ?>
<input type="radio" name="q2" value="c2">

The PHP Code

$q1 = $_POST['q1'];

    if ($q1 == "c1" ) {

        $query = "UPDATE `question1` SET score = score + 1 WHERE choices = 'choice1'";
    }
    if ($q1 == "c2" ) {

        $query = "UPDATE `question1` SET score = score + 1 WHERE choices = 'choice2'";
    }

$q2 = $_POST['q2'];

    if ($q2 == "c1" ) {

        $query = "UPDATE `question2` SET score = score + 1 WHERE choices = 'choice1'";
    }
    if ($q2 == "c2" ) {

        $query = "UPDATE `question2` SET score = score + 1 WHERE choices = 'choice2'";
    }

They should be updating the score +1 everytime someone choices the option when submitted. How do I fix this? Please check my code.

Body:
You are using same variable for both questions so if both question submitted but last query will work as you defined same variable

$q1 = $_POST['q1'];
$query="";
$query2="";
if ($q1 == "c1" ) {

    $query = "UPDATE `question1` SET score = score + 1 WHERE choices = 'choice1'";
}
if ($q1 == "c2" ) {

    $query = "UPDATE `question1` SET score = score + 1 WHERE choices = 'choice2'";
}
if($query){
//execute first query here
}

$q2 = $_POST['q2'];

if ($q2 == "c1" ) {

    $query2 = "UPDATE `question2` SET score = score + 1 WHERE choices = 'choice1'";
}
if ($q2 == "c2" ) {

    $query2 = "UPDATE `question2` SET score = score + 1 WHERE choices = 'choice2'";
}
if($query2){
//execute second query here
}

Hope this helps you


问:
How to map each item from observable to another one that comes from async function?
I want to

1.map item from observable to another one if it has already saved in database.

2.otherwise, use it as it is.

and keep their order in result.

Saved item has some property like tag, and item from observable is 'raw', it doesn't have any property.

I wrote code like this and run testMethod.

    class Item {
      final String key;
      String tag;
      Item(this.key);
      @override
      String toString() {
        return ('key:$key,tag:$tag');
      }
    }

    class Sample {
    ///this will generate observable with 'raw' items.
    static Observable<Item> getItems() {
        return Observable.range(1, 5).map((index) => Item(index.toString()));
    }

    ///this will find saved item from repository if it exists.
    static Future<Item> findItemByKey(String key) async {
        //simulate database search
        await Future.delayed(Duration(seconds: 1));
        if (key == '1' || key == '4') {
            final item = Item(key)..tag = 'saved';
            return item;
        } else
            return null;
    }

    static void testMethod() {
        getItems().map((item) async {
            final savedItem = await findItemByKey(item.key);
            if (savedItem == null) {
                print('not saved:$item');
                return item;
            } else {
                print('saved:$savedItem');
                return savedItem;
            }
        }).listen((item) {});
    }
```

<p>The result is not expected one.</p>

<p>expected:</p>

```saved:key:1,tag:saved
not saved:key:2,tag:null
not saved:key:3,tag:null
saved:key:4,tag:saved
not saved:key:5,tag:null
```

<p>actual:</p>

```not saved:key:2,tag:null
not saved:key:3,tag:null
not saved:key:5,tag:null
saved:key:1,tag:saved
saved:key:4,tag:saved
```

How to keep their order in result?

答:
I answer myself to close this question.

According to pskink's comment, use asyncMap or concatMap solve my problem. Thanks!!

below is new implementation of testMethod.

asyncMap version:

getItems().asyncMap((item) {
  final savedItem = findItemByKey(item.key);
  if (savedItem != null)
    return savedItem;
  else
    return Future.value(item);
}).listen(print);
```

<p>concatMap version:</p>

<pre class="lang-dart prettyprint-override"><code>getItems().concatMap((item) {
  final savedItem = findItemByKey(item.key);
  if (savedItem != null)
    return Observable.fromFuture(savedItem);
  else
    return Observable.just(item);
}).listen(print);
</code>```

Body:
I want to

1.map item from observable to another one if it has already saved in database.

2.otherwise, use it as it is.

and keep their order in result.

Saved item has some property like tag, and item from observable is 'raw', it doesn't have any property.

I wrote code like this and run testMethod.

    class Item {
      final String key;
      String tag;
      Item(this.key);
      @override
      String toString() {
        return ('key:$key,tag:$tag');
      }
    }

    class Sample {
    ///this will generate observable with 'raw' items.
    static Observable<Item> getItems() {
        return Observable.range(1, 5).map((index) => Item(index.toString()));
    }

    ///this will find saved item from repository if it exists.
    static Future<Item> findItemByKey(String key) async {
        //simulate database search
        await Future.delayed(Duration(seconds: 1));
        if (key == '1' || key == '4') {
            final item = Item(key)..tag = 'saved';
            return item;
        } else
            return null;
    }

    static void testMethod() {
        getItems().map((item) async {
            final savedItem = await findItemByKey(item.key);
            if (savedItem == null) {
                print('not saved:$item');
                return item;
            } else {
                print('saved:$savedItem');
                return savedItem;
            }
        }).listen((item) {});
    }

The result is not expected one.

expected:

saved:key:1,tag:saved
not saved:key:2,tag:null
not saved:key:3,tag:null
saved:key:4,tag:saved
not saved:key:5,tag:null

actual:

not saved:key:2,tag:null
not saved:key:3,tag:null
not saved:key:5,tag:null
saved:key:1,tag:saved
saved:key:4,tag:saved

How to keep their order in result?

Body:
I answer myself to close this question.

According to pskink's comment, use asyncMap or concatMap solve my problem. Thanks!!

below is new implementation of testMethod.

asyncMap version:

getItems().asyncMap((item) {
  final savedItem = findItemByKey(item.key);
  if (savedItem != null)
    return savedItem;
  else
    return Future.value(item);
}).listen(print);

concatMap version:

getItems().concatMap((item) {
  final savedItem = findItemByKey(item.key);
  if (savedItem != null)
    return Observable.fromFuture(savedItem);
  else
    return Observable.just(item);
}).listen(print);


问:
Error: Can't set headers after they are sent. in nodejs
I am running into the error show below on my app,line 413 points to “res.json(stat); // return in JSON format.” in below code, I looked at other posts with similar error but none helped me, why am I hitting this error ?appreciate any guidance on how to fix it?

```<code>app.post('/api/botjobs.json', function(req, res) {
    // console.log(req.body)
    data = req.body;
    var temp = {};
    temp.radar = data.radar;
    temp.request = data.request;
    if(temp.request == 'cloneradar'){
        temp['params.clonetype'] = data.params.clonetype;
    }
    now = new Date();
    data["updated"] = now;
    // console.log('DATA:')
    // console.log(data)
    // console.log('TEMP:')
    // console.log(temp)
    botjobs.findOne(temp, {}, { sort:{'_id': -1}}, function(err, findstat){
        // console.log(findstat)
        // console.log(err)
        // console.log("inside botjobs findOne");
        if(findstat != null){
            // console.log('updating entry')
            //console.log(findstat);
            data['numupdated'] = findstat['numupdated']+1;
            // console.log(data);
            botjobs.update({'_id':findstat['_id']},data,{ upsert : true, multi: true },function(err,stat){
                if (err)
                    res.send(err);

                res.json(stat); // return in JSON format
            });

        }
        else{
            // console.log('creating new entry')
            data["created"] = now;
            data['numupdated'] = 0;
            botjobs.create(data,function(err, stat) {
                // console.log(stat);
                // if there is an error retrieving, send the error. nothing after res.send(err) will execute
                if (err)
                    res.send(err);

                res.json(stat); // return in JSON format. —> line 413 in route.js
            });
        }

    });

});
</code>```

Error:-

```<code>Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:350:11)
    at ServerResponse.res.setHeader (/app/node_modules/express/node_modules/connect/lib/patch.js:134:22)
    at ServerResponse.res.set.res.header (/app/node_modules/express/lib/response.js:595:10)
    at ServerResponse.res.send (/app/node_modules/express/lib/response.js:151:12)
    at ServerResponse.res.json (/app/node_modules/express/lib/response.js:237:15)
    at /app/app/routes.js:413:10
</code>```

答: try return res.send(err); in place of res.send(err); for each res.send()

Body:
I am running into the error show below on my app,line 413 points to “res.json(stat); // return in JSON format.” in below code, I looked at other posts with similar error but none helped me, why am I hitting this error ?appreciate any guidance on how to fix it?

app.post('/api/botjobs.json', function(req, res) {
    // console.log(req.body)
    data = req.body;
    var temp = {};
    temp.radar = data.radar;
    temp.request = data.request;
    if(temp.request == 'cloneradar'){
        temp['params.clonetype'] = data.params.clonetype;
    }
    now = new Date();
    data["updated"] = now;
    // console.log('DATA:')
    // console.log(data)
    // console.log('TEMP:')
    // console.log(temp)
    botjobs.findOne(temp, {}, { sort:{'_id': -1}}, function(err, findstat){
        // console.log(findstat)
        // console.log(err)
        // console.log("inside botjobs findOne");
        if(findstat != null){
            // console.log('updating entry')
            //console.log(findstat);
            data['numupdated'] = findstat['numupdated']+1;
            // console.log(data);
            botjobs.update({'_id':findstat['_id']},data,{ upsert : true, multi: true },function(err,stat){
                if (err)
                    res.send(err);

                res.json(stat); // return in JSON format
            });

        }
        else{
            // console.log('creating new entry')
            data["created"] = now;
            data['numupdated'] = 0;
            botjobs.create(data,function(err, stat) {
                // console.log(stat);
                // if there is an error retrieving, send the error. nothing after res.send(err) will execute
                if (err)
                    res.send(err);

                res.json(stat); // return in JSON format. —> line 413 in route.js
            });
        }

    });

});

Error:-

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:350:11)
    at ServerResponse.res.setHeader (/app/node_modules/express/node_modules/connect/lib/patch.js:134:22)
    at ServerResponse.res.set.res.header (/app/node_modules/express/lib/response.js:595:10)
    at ServerResponse.res.send (/app/node_modules/express/lib/response.js:151:12)
    at ServerResponse.res.json (/app/node_modules/express/lib/response.js:237:15)
    at /app/app/routes.js:413:10


问:
Python 3 won't run from the Git Bash command line
Basically, I type python into Git Bash command line and I get back a blank line as if the command line is thinking...

I've done plenty of research but I can't seem to run python on Git Bash by typing in python into the command line.

I was looking at the question: Python not working in the command line of git bash
and someone recommended to type:

winpty c:/Python34/python.exe
```

into the command line and it worked! However, I don't want to have to keep typing that entire command into the command line.

答:
"One caveat if using Git Bash with MinTTY: python doesn't go into
  interactive mode so a solution is to force it to start that way: echo
  alias python=\"python -i\" >> ~/.bash_profile"]

For more details

I had the same issue and using "python -i" solved it.

Body:
Basically, I type python into Git Bash command line and I get back a blank line as if the command line is thinking...

I've done plenty of research but I can't seem to run python on Git Bash by typing in python into the command line.

I was looking at the question: Python not working in the command line of git bash
and someone recommended to type:

winpty c:/Python34/python.exe

into the command line and it worked! However, I don't want to have to keep typing that entire command into the command line.


问:
Python age calculator based on DOB
I am practicing by creating an age calculator which calculates age in years based on given date of birth.

However it doesn't work the way I intend it to function. I want to show age in year e.g 19 to the user when their age is 19 and month is less than 6 and if the month is more than 6 then I want to add 1 to the age in this case 19+1.

Can anyone create the same program with the same concept in a better way?  Please add some explanation so that it is easy for me to understand.

I am python beginner, so please excuse my bad code as well as my bad English. Thanks in advance for the help.

from datetime import date

Doby,Dobm,Dobd =input("enter your DOB : i.e year,month,days  1999,02,08   : ").split(",")
born = date(year = int(Doby) , month= int(Dobm) , day= int(Dobd))
today = date.today()
age = today.year - born.year
condition = today.month - born.month
if condition >= 6 :
    age += 1
elif condition <= -6 :
    age -= 1
print(age)
```

答:
You can just divide with no of days in a year and do rounding (round half up) to get the desired result. The below code should work.

```<code>from datetime import date

# Doby,Dobm,Dobd =input("enter your DOB : i.e year,month,days  1999,02,08   : ").split(",")
Doby, Dobm, Dobd = 1999, 11, 1
born = date(year=int(Doby), month=int(Dobm), day=int(Dobd))
today = date.today()

print(round((today-born).days/365.25))

</code>```

Output:

```<code>20
</code>```

Title: Python age calculator based on DOB

Body:
You can just divide with no of days in a year and do rounding (round half up) to get the desired result. The below code should work.

from datetime import date

# Doby,Dobm,Dobd =input("enter your DOB : i.e year,month,days  1999,02,08   : ").split(",")
Doby, Dobm, Dobd = 1999, 11, 1
born = date(year=int(Doby), month=int(Dobm), day=int(Dobd))
today = date.today()

print(round((today-born).days/365.25))

Output:

20


问:
Add dynamic text over Android SeekBar thumb
I'm trying to make this custom SeekBar in Android 2.2 and everything I do seems to be wrong! I'm trying to display the value of the seekbar over the thumb image of the SeekBar. Does anybody have some experiences with this?</p>

答:
Add a TextView to your layout. Add onSeekBarChangeListener.

You will want precision so that the text is exactly in the middle of your seek bar thumb, you have to a little calculation. This is because the width of the text is different. Say, you want to show numbers from 0 to 150. Width of 188 will be different from 111. Because of this, the text you are showing will always tilt to some side.

The way to solve it is to measure the width of the text, remove that from the width of the seekbar thumb, divide it by 2, and add that to the result that was given in the accepted answer.  Now you would not care about how large the number range. Here is the code:

```<code> override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                    val value = progress * (seekBar.width - 2 * seekBar.thumbOffset) / seekBar.max
                    label.text = progress.toString()
                    label.measure(0, 0)
                    val textWidth =  label.measuredWidth
                    val firstRemainder = seekThumbWidth - textWidth
                    val result = firstRemainder / 2
                    label.x = (seekBar.x + value + result)
                }
</code>```

Body:
Add a TextView to your layout. Add onSeekBarChangeListener.

You will want precision so that the text is exactly in the middle of your seek bar thumb, you have to a little calculation. This is because the width of the text is different. Say, you want to show numbers from 0 to 150. Width of 188 will be different from 111. Because of this, the text you are showing will always tilt to some side.

The way to solve it is to measure the width of the text, remove that from the width of the seekbar thumb, divide it by 2, and add that to the result that was given in the accepted answer.  Now you would not care about how large the number range. Here is the code:

 override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                    val value = progress * (seekBar.width - 2 * seekBar.thumbOffset) / seekBar.max
                    label.text = progress.toString()
                    label.measure(0, 0)
                    val textWidth =  label.measuredWidth
                    val firstRemainder = seekThumbWidth - textWidth
                    val result = firstRemainder / 2
                    label.x = (seekBar.x + value + result)
                }


问:
Calling array values based on DOM return
Return a string based on pulled dom elements

I have an object storing months and their index (not dates) monthList = {"jan" : "1", "feb" : "2". etc: etc}

The user can type something like jan or jan,feb,march and I want a string returned as 1 or 1,2,3 (which I use for a get call elsewhere) but haven't been able to do this, ive tried using all sorts of crazy loops to no avail, from incorrect reading to always reading last index, if the user inputs 1,2,3 that should also work.

The input values as simply called using ${document.getElementById('monthInput').value}

```<code>User Input Example #1: jan,feb,dec
User Input Output #1: 1,2,12
</code>```

```<code>User Input Example #2: 1,2,5
User Input Output #2: 1,2,5
</code>```

How can I do this?

答:
You can do this a few ways:

Using a simple for..of loop

Using .replace() (keeps the formatting of original string)

Using a mapping method (using: .map)

Going overboard with recursion + ternaries...

Using Loops:

const months = {jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"};

const input = "jan,dec,feb";
const dates = input.split(','); // turn your input into an array

let converted = "";
for(let month of dates) { // loop through each month in dates
  if(month in months) { // check if the month is a key in months
    converted += months[month] +','; // add number version to converted sring
  } else { // if the month isn't in the converted month object, then no need to convert it
    converted += month+','; // add month to (ie the number) to the converted output
  }
}

console.log(converted.slice(0, -1)); // using slice(0, -1) to remove trailing comma```
</div>
</div>
</p>

<ol start="2">
<li>Using <code>.replace()</code> to keep original formatting:</li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const months = {jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"};

let input = "jan,   dec,  feb, 5";
const dates = input.split(','); // turn your input into an array

for(let month of dates) {
  month = month.trim();
  if(month in months) {
    input = input.replace(month, months[month]);
  }
}

console.log(input);</code>```

Using map. Here the inner arrow function is called for each month, and then converted to its associated value in the months object. We then use .join(',') to join the array of values:

const months = {jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"};
const input = "jan,dec,feb";

const converted = input.split(',')
                       .map((month) => months[month] || month)
                       .join(',');
console.log(converted);```
</div>
</div>
</p>

<ol start="4">
<li>Using recursion with the ternary operator: </li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const months={jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"};
const input = "jan,dec,feb";

const res = (f = ([m, ...rest]) => m && m in months ? months[m]+','+f(rest) : m ? m+','+f(rest) : '')(input.split(',')).slice(0,-1);
console.log(res);</code>```

Body:
Return a string based on pulled dom elements

I have an object storing months and their index (not dates) monthList = {"jan" : "1", "feb" : "2". etc: etc}

The user can type something like jan or jan,feb,march and I want a string returned as 1 or 1,2,3 (which I use for a get call elsewhere) but haven't been able to do this, ive tried using all sorts of crazy loops to no avail, from incorrect reading to always reading last index, if the user inputs 1,2,3 that should also work.

The input values as simply called using ${document.getElementById('monthInput').value}

User Input Example #1: jan,feb,dec
User Input Output #1: 1,2,12

User Input Example #2: 1,2,5
User Input Output #2: 1,2,5

How can I do this?

Body:
You can do this a few ways:

Using a simple for..of loop

Using .replace() (keeps the formatting of original string)

Using a mapping method (using: .map)

Going overboard with recursion + ternaries...

Using Loops:

const months = {jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"};

const input = "jan,dec,feb";
const dates = input.split(','); // turn your input into an array

let converted = "";
for(let month of dates) { // loop through each month in dates
  if(month in months) { // check if the month is a key in months
    converted += months[month] +','; // add number version to converted sring
  } else { // if the month isn't in the converted month object, then no need to convert it
    converted += month+','; // add month to (ie the number) to the converted output
  }
}

console.log(converted.slice(0, -1)); // using slice(0, -1) to remove trailing comma

Using .replace() to keep original formatting:

const months = {jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"};

let input = "jan,   dec,  feb, 5";
const dates = input.split(','); // turn your input into an array

for(let month of dates) {
  month = month.trim();
  if(month in months) {
    input = input.replace(month, months[month]);
  }
}

console.log(input);

Using map. Here the inner arrow function is called for each month, and then converted to its associated value in the months object. We then use .join(',') to join the array of values:

const months = {jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"};
const input = "jan,dec,feb";

const converted = input.split(',')
                       .map((month) => months[month] || month)
                       .join(',');
console.log(converted);

Using recursion with the ternary operator:

const months={jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"};
const input = "jan,dec,feb";

const res = (f = ([m, ...rest]) => m && m in months ? months[m]+','+f(rest) : m ? m+','+f(rest) : '')(input.split(',')).slice(0,-1);
console.log(res);


问:
Is try {} without catch {} possible in JavaScript?
I have a number of functions which either return something or throw an error. In a main function, I call each of these, and would like to return the value returned by each function, or go on to the second function if the first functions throws an error.

So basically what I currently have is:

```<code>function testAll() {
    try { return func1(); } catch(e) {}
    try { return func2(); } catch(e) {} // If func1 throws error, try func2
    try { return func3(); } catch(e) {} // If func2 throws error, try func3
}
</code>```

But actually I'd like to only try to return it (i.e. if it doesn't throw an error). I do not need the catch block. However, code like try {} fails because it is missing an (unused) catch {} block.

I put an example on jsFiddle.

So, is there any way to have those catch blocks removed whilst achieving the same effect?

答:
It's possible to have an empty catch block, without an error variable, starting with ES2019. This is called optional catch binding and was implemented in V8 v6.6, released in June 2018. The feature has been available since Node 10, Chrome 66, Firefox 58, Opera 53 and Safari 11.1.

The syntax is shown below:

try {
  throw new Error("This won't show anything");
} catch { };```
</div>
</div>
</p>

<p>You still need a <code>catch</code> block, but it can be empty and you don't need to pass any variable. If you don't want a catch block at all, you can use the <code>try</code>/<code>finally</code>, but note that it won't swallow errors as an empty catch does.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>try {
  throw new Error("This WILL get logged");
} finally {
  console.log("This syntax does not swallow errors");
}</code>```

Body:
I have a number of functions which either return something or throw an error. In a main function, I call each of these, and would like to return the value returned by each function, or go on to the second function if the first functions throws an error.

So basically what I currently have is:

function testAll() {
    try { return func1(); } catch(e) {}
    try { return func2(); } catch(e) {} // If func1 throws error, try func2
    try { return func3(); } catch(e) {} // If func2 throws error, try func3
}

But actually I'd like to only try to return it (i.e. if it doesn't throw an error). I do not need the catch block. However, code like try {} fails because it is missing an (unused) catch {} block.

I put an example on jsFiddle.

So, is there any way to have those catch blocks removed whilst achieving the same effect?

Body:
It's possible to have an empty catch block, without an error variable, starting with ES2019. This is called optional catch binding and was implemented in V8 v6.6, released in June 2018. The feature has been available since Node 10, Chrome 66, Firefox 58, Opera 53 and Safari 11.1.

The syntax is shown below:

try {
  throw new Error("This won't show anything");
} catch { };

You still need a catch block, but it can be empty and you don't need to pass any variable. If you don't want a catch block at all, you can use the try/finally, but note that it won't swallow errors as an empty catch does.

try {
  throw new Error("This WILL get logged");
} finally {
  console.log("This syntax does not swallow errors");
}


问:
How to call methods in laravel
I have been studying Laravel now for one month or more and by brain hurts.
After making my own practice web-app this is what buggers me:

I see 2 ways (at least) to call methods / functions. Sometimes they work, sometimes they don't. Why? And what's the difference?

```<code>return ClubTypes::find($id);
return $this->hasMany()->...
</code>```

And when dealing with sql, sometimes I need to put ->get() and sometimes putting the ->get() will give error of not defined.. what's up with that?

Thank you!

答:
1 ) ClubTypes::find() This is know as facades. Facades provide static interface for class.Laravel have many predefine facades like, Route,Session,DB etc.

ClubType is a class
:: scope resolution operator used for calling static and constants.
find() is a static method.

2)$this-> It is a refrence of current class and -> (arrow / object operator) is used to call the methods and properties of object.

Title: How to call methods in laravel

Body:
I have been studying Laravel now for one month or more and by brain hurts.
After making my own practice web-app this is what buggers me:

I see 2 ways (at least) to call methods / functions. Sometimes they work, sometimes they don't. Why? And what's the difference?

return ClubTypes::find($id);
return $this->hasMany()->...

And when dealing with sql, sometimes I need to put ->get() and sometimes putting the ->get() will give error of not defined.. what's up with that?

Thank you!


问:
What's going on in this for loop?
This loop is from a solution for a freeCodeCamp challenge. I don't understand how it works -- what does decrementing i do? I'm totally clueless. Any help understanding would be greatly appreciated.

```<code>for (var i = arr[0]; i >= arr[1]; i--) {
  newArr.push(i);
}
</code>```

Here's the full solution the for loop is from:

```<code>function smallestCommons(arr) {
  // Sort array from greater to lowest
  // This line of code was from Adam Doyle (http://github.com/Adoyle2014)
  arr.sort(function(a, b) {
    return b - a;
  });

  // Create new array and add all values from greater to smaller from the
  // original array.
  var newArr = [];
  for (var i = arr[0]; i >= arr[1]; i--) {
    newArr.push(i);
  }

  // Variables needed declared outside the loops.
  var quot = 0;
  var loop = 1;
  var n;

  // Run code while n is not the same as the array length.
  do {
    quot = newArr[0] * loop * newArr[1];
    for (n = 2; n < newArr.length; n++) {
      if (quot % newArr[n] !== 0) {
        break;
      }
    }

    loop++;
  } while (n !== newArr.length);

  return quot;
}

// test here
smallestCommons([1,5]);
</code>```

答:
I don't understand how it works -- what does decrementing i do ?

Here you're passing two values to your function as an array [1,5]

```<code>smallestCommons([1,5]);
</code>```

Inside function smallestCommons first thing we are doing is sorting array in descending order

```<code>arr.sort(function(a, b) {
    return b - a;
});                       // arr = [5,1]
</code>```

Now we are creating a newArray

```<code>let newArr = [];
  for (let i = arr[0]; i >= arr[1]; i--) {
    newArr.push(i);
}
</code>```

Here arr[0] = 5 and arr[1] = 1

So initial value of i is 5 and your condition is i >= arr[1]

We keep decreasing value of i untill it is less than arr[1] which is 1

So newArray will have value [5, 4, 3, 2, 1]

Title: What's going on in this for loop?

Body:
This loop is from a solution for a freeCodeCamp challenge. I don't understand how it works -- what does decrementing i do? I'm totally clueless. Any help understanding would be greatly appreciated.

for (var i = arr[0]; i >= arr[1]; i--) {
  newArr.push(i);
}

Here's the full solution the for loop is from:

function smallestCommons(arr) {
  // Sort array from greater to lowest
  // This line of code was from Adam Doyle (http://github.com/Adoyle2014)
  arr.sort(function(a, b) {
    return b - a;
  });

  // Create new array and add all values from greater to smaller from the
  // original array.
  var newArr = [];
  for (var i = arr[0]; i >= arr[1]; i--) {
    newArr.push(i);
  }

  // Variables needed declared outside the loops.
  var quot = 0;
  var loop = 1;
  var n;

  // Run code while n is not the same as the array length.
  do {
    quot = newArr[0] * loop * newArr[1];
    for (n = 2; n < newArr.length; n++) {
      if (quot % newArr[n] !== 0) {
        break;
      }
    }

    loop++;
  } while (n !== newArr.length);

  return quot;
}

// test here
smallestCommons([1,5]);

Body:
I don't understand how it works -- what does decrementing i do ?

Here you're passing two values to your function as an array [1,5]

smallestCommons([1,5]);

Inside function smallestCommons first thing we are doing is sorting array in descending order

arr.sort(function(a, b) {
    return b - a;
});                       // arr = [5,1]

Now we are creating a newArray

let newArr = [];
  for (let i = arr[0]; i >= arr[1]; i--) {
    newArr.push(i);
}

Here arr[0] = 5 and arr[1] = 1

So initial value of i is 5 and your condition is i >= arr[1]

We keep decreasing value of i untill it is less than arr[1] which is 1

So newArray will have value [5, 4, 3, 2, 1]


问:
What does it mean to have a valid record when the record contains nothing, not even a single space
I was browsing the data for a particular column which looked like it had spaces because it did not say null

Upon trying to find what it was, I discovered the data does not have a single space but it is also not blank.

What is it then?  -- something between two single quotations '' which is not space.

Tried to run this query with no results:

```<code>select column1 from table1 where column1 like '% %'
-- Single space
</code>```

-> No records found

The second query I tried (see below) has no spaces mentioned. And that gave a result saying that there exist records which are like ->''

```<code>select column1 from table1 where column1 like '% %'

select column1 from table1 where column1= ''
</code>```

I am trying to understand what is that record and what does it mean to be nothing?

答:
What is it then? -- something between two single quotations '' which is not space.

It's a string of zero length. You're right, it's not a space - a space is ' ' - it has a length of one character. A string of length 0 is nothing like a string of length 1, no matter what character is in the string.

In any computer system we arbitrarily decide on the meaning of everything. Suppose you have a question that has an answer A, B, or C. You might also have situations where the person doesn't know, or knows but doesn't want to say. You might arbitrarily decide to have NULL means "don't know" and 0 length string as "don't want to say" in addition to all the people who do answer with a letter

This is an arbitrary decision, maybe you decide to store a space for "don't want to say", maybe an exclamation mark- whatever. Some database vendors think it is important to provide support for having strings of zero length, others (oracle) do not (oracle treats null and '' as the same)

Ultimately if your db supports zero length strings you have to understand what they are and in the context of your application you have to understand what they mean. What they are is like a glass with no water in it, or a bag of sweets with no sweets in it.. The statement of "there is no data" is different to "we don't know if there is any data or not" - the uncertainty here is more often associated with NULL

I am trying to understand what is that record and what does it mean to be nothing?

That record is a record with a zero length string in that column. However, we cannot tell you what it means because the decision to store a zero length string in it was taken by you or one of the other developers at your company, or a previous developer who quit. It could be that he wanted to record a difference between null and zero data. It could be that he couldn't be bothered checking if the data was null and wanted to avoid a typical null reference crash on the front end app. It could be that he wanted to count the data even though there was no data to put there

We cannot answer this part of your question

We can only tell you that zero length strings are possible, you can attach as much meaning to them as any other string, and they will never be equal to a string of non zero length so like '% %' will never find them. Do not assume that something you cannot see must be a space..

Body:
I was browsing the data for a particular column which looked like it had spaces because it did not say null

Upon trying to find what it was, I discovered the data does not have a single space but it is also not blank.

What is it then?  -- something between two single quotations '' which is not space.

Tried to run this query with no results:

select column1 from table1 where column1 like '% %'
-- Single space

-> No records found

The second query I tried (see below) has no spaces mentioned. And that gave a result saying that there exist records which are like ->''

select column1 from table1 where column1 like '% %'

select column1 from table1 where column1= ''

I am trying to understand what is that record and what does it mean to be nothing?