问:
How to pass images saved in drawable folder via CustomAdapter to NewActivity
How can I pass an array of images in RecyclerView to NewActivity.java? I don't mean images from row.xml - I want a set of new images different from row.xml to a NewActivity. I saved the images in the drawable folder.

My trials below are the relevant classes and activity.

File String.xml

<string-array name="array_titles">
    <item>"<![CDATA[[01]  general focus]]>"</item>
    <item>"<![CDATA[[02]  general view for delibration]]>"</item>
</string-array>

<string-array name="array_lyrics">
    <item>"<![CDATA[general]]>"</item>
    <item>"<![CDATA[ General ]]>"</item>
    <item>"<![CDATA[ General ]]>"</item>
    <item>"<![CDATA[ General ]]>"</item>
</string-array>

<string-array name="newbrandDesc">
    <item>"<![CDATA[ description here ]]>"</item>
    <item>"<![CDATA[ description here ]]>"</item>
    <item>"<![CDATA[ description here ]]>"</item>
    <item>"<![CDATA[ here ]]>"</item>
</string-array>```
</div>
</div>
</p>
<h3>File <em>MainActivity.xml</em></h3>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_weight="1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <View
        android:id="@+id/viewerage"
        android:background="#01312D"
        android:layout_width="match_parent"
        android:layout_height="5dp" />

        <!-- First Row-->

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="70dp"
        android:layout_below="@id/viewerage"
        style="@style/scrollbar_shape_style"
        android:id="@+id/recyclerview">

    </androidx.recyclerview.widget.RecyclerView>

</RelativeLayout></code>```

File MainActivity.java

public class MainActivity extends AppCompatActivity {

    private String TAG = "MainActivity ----- ; ";
    private static MediaPlayer player;
    String soundfile;
    TextView mDetailTv1;

    RecyclerView mRecyclerview;
    MyAdapter myAdapter;
    int [] MusicFile;
    List<String> title, newDesc, description;
    int[] icon;
    ArrayList<Model> arrayList = new ArrayList<Model>();

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

        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("Intro Songs");

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        // Listview icons for song titles in position
        icon = new int[]{R.drawable.song, R.drawable.song, R.drawable.song, };

        mRecyclerview = findViewById(R.id.recyclerview);
        mRecyclerview.setLayoutManager(new LinearLayoutManager(this));

        title = Arrays.asList(getResources().getStringArray(R.array.array_titles));

        // listview descriptions for songs in position
        description = Arrays.asList(getResources().getStringArray(R.array.array_lyrics));

        // listview NewDescriptions (NewActivity) for songs in position
        newDesc = Arrays.asList(getResources().getStringArray(R.array.newbrandDesc));

        // listview soundfile file for songs in position
        MusicFile = new int[] {R.raw.wex_1, R.raw.wex_2, R.raw.wex_3, , };

        for (int i = 0; i< title.size(); i++) {
            Model model = new Model(title.get(i), description.get(i), newDesc.get(i), icon[i], MusicFile[i]);
            // Bind all strings in an array
            arrayList.add(model);
        }

        // Pass result to listview class
        myAdapter = new MyAdapter(this, arrayList);

        // Bind the adapter to the listview class
        mRecyclerview.setAdapter(myAdapter);
    }

    @Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Are you sure you want to exit?")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        MainActivity.this.finish();
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.menu, menu);

        MenuItem item = menu.findItem(R.id.action_search);

        SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                myAdapter.getFilter().filter(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {

                myAdapter.getFilter().filter(newText);

                return false;
            }
        });

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            Toast.makeText(this, "Favorites Selected", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, FavoritesActivity.class));

            return true;

            // Do more funtionality here
        }
        return super.onOptionsItemSelected(item);
    }

}```
</div>
</div>
</p>
<h3>File <em>MyAdapter.java</em></h3>
<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>public class MyAdapter extends RecyclerView.Adapter<MyHolder> implements Filterable {

    Context mContext;
    ArrayList<Model> models, filterList;  // This array list create a list of array
                                          // which parameter define in our class
    CustomFilter filter;

    public MyAdapter(Context context, ArrayList<Model> models) {
        this.mContext = context;
        this.models = models;
        this.filterList = models;
    }

    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row, null); // This line inflate our row

        return new MyHolder(view); // This will return our view to holder class
    }

    @Override
    public void onBindViewHolder(@NonNull final MyHolder myHolder, int i) {

        myHolder.mTitle.setText(models.get(i).getTitle()); // Here is position
        myHolder.mDesc.setText(models.get(i).getDesc());
        myHolder.mImageView.setImageResource(models.get(i).getIcon()); // Here we used an image resource

        myHolder.setItemCLickListener(new ItemClickListener() {
            @Override
            public void onItemClickListener(View v, int position) {

                String gTitle = models.get(position).getTitle();
                String gDesc = models.get(position).getDesc();
                BitmapDrawable bitmapDrawable = (BitmapDrawable)myHolder.mImageView.getDrawable();
                Bitmap bitmap = bitmapDrawable.getBitmap();

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byte[] bytes = stream.toByteArray();

                //get our data with intent
                Intent intent = new Intent(mContext, NewActivity.class);
                intent.putExtra("actionBarTitle", models.get(position).getTitle());
                intent.putExtra("brandNewDesc", models.get(position).getBrandNewDesc());
                intent.putExtra("soundfile", models.get(position).getSoundfile());
                intent.putExtra("iImage", bytes);
                mContext.startActivity(intent);
                return;
            }
        });
    }

    @Override
    public int getItemCount() {
        return models.size();
    }

    @Override
    public Filter getFilter() {

        if (filter == null) {
            filter = new CustomFilter(filterList, this);
        }

        return filter;
    }
}</code>```

File MyHolder.java

public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    ImageView mImageView;
    TextView mTitle, mDesc;
    ItemClickListener itemCLickListener;

    MyHolder(@NonNull View itemView) {
        super(itemView);

        this.mImageView = itemView.findViewById(R.id.mainIcon);
        this.mTitle = itemView.findViewById(R.id.mainTitle);
        this.mDesc = itemView.findViewById(R.id.mainDesc);

        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        this.itemCLickListener.onItemClickListener(v, getLayoutPosition());
    }

    public void setItemCLickListener(ItemClickListener ic) {

        this.itemCLickListener = ic;
    }
}```
</div>
</div>
</p>
<h3>File <em>CustomFilter.java</em></h3>
<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>private ArrayList<Model> filterList;

    private MyAdapter adapter;

    public CustomFilter(ArrayList<Model> filterList, MyAdapter adapter) {
        this.filterList = filterList;
        this.adapter = adapter;
    }

    @Override
    protected FilterResults performFiltering(CharSequence constraints) {

        FilterResults filterResults = new FilterResults();

        if (constraints != null && constraints.length() > 0) {

            constraints = constraints.toString().toUpperCase();

            ArrayList<Model> filterModels = new ArrayList<>();
            for (int i = 0; i < filterList.size(); i++) {
                if (filterList.get(i).getTitle().toUpperCase().contains(constraints)) {
                    filterModels.add(filterList.get(i));
                }
            }

            filterResults.count = filterModels.size();
            filterResults.values = filterModels;
        }
        else {
            filterResults.count = filterList.size();
            filterResults.values = filterList;
        }
        return filterResults;
    }

    @Override
    protected void publishResults(CharSequence charSequence, FilterResults filterResults) {

        adapter.models = (ArrayList<Model>) filterResults.values;
        adapter.notifyDataSetChanged();
    }
}</code>```

File ItemClickListener.java - the interface

public interface ItemClickListener {

    void onItemClickListener(View v, int position);
}```
</div>
</div>
</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>public class NewActivity extends AppCompatActivity {
    private String TAG = "NewActivity ----- ; ";

    // Store instance variables
    private String title;
    private int page;
    TextView mBrandNewDesc;

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

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // Keeps Android screen on while reading through
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        ActionBar actionBar = getSupportActionBar();
        mBrandNewDesc = findViewById(R.id.textView);

        // Get data from previous activity when item of activity is clicked using intent
        Intent intent = getIntent();
        String mActionBarTitle = intent.getStringExtra("actionBarTitle");
        String newDescription = intent.getStringExtra("brandNewDesc");

        // setctionBar Title
        actionBar.setTitle(mActionBarTitle);

        // Get text in text textView
        mBrandNewDesc.setText(Html.fromHtml(newDescription));

        // OK, we are done. Let’s run the project
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

}</code>```

答:
Instead of drawable>bitmap>byteArray send the drawable resource id like this code below changed the onBindViewHolder

```<code>@Override
public void onBindViewHolder(@NonNull final MyHolder myHolder, int i) {

    myHolder.mTitle.setText(models.get(i).getTitle()); //here is position
    myHolder.mDesc.setText(models.get(i).getDesc());
    myHolder.mImageView.setImageResource(models.get(i).getIcon()); // here we used imge resource

    myHolder.setItemCLickListener(new ItemClickListener() {
        @Override
        public void onItemClickListener(View v, int position) {

            String gTitle = models.get(position).getTitle();
            String gDesc = models.get(position).getDesc();
            int imageId = models.get(position).getIcon();

            //get our data with the intent
            Intent intent = new Intent(mContext, NewActivity.class);
            intent.putExtra("actionBarTitle", models.get(position).getTitle());
            intent.putExtra("brandNewDesc", models.get(position).getBrandNewDesc());
            intent.putExtra("soundfile", models.get(position).getSoundfile());
            intent.putExtra("iImage", imageId ); // i pass the int id then you can use this id in your next activity.
            mContext.startActivity(intent);
            return;
        }
    });

}
</code>```

New Activity

```<code>    ImageView imageView;
    Intent intent = getIntent();
    if (intent != null && !intent.getExtras().isEmpty()){
        int imageResourceId = intent.getIntExtra("iImage",-1);
        imageView.setImageResource(imageResourceId);
    }
</code>```

Body:
How can I pass an array of images in RecyclerView to NewActivity.java? I don't mean images from row.xml - I want a set of new images different from row.xml to a NewActivity. I saved the images in the drawable folder.

My trials below are the relevant classes and activity.

File String.xml

<string-array name="array_titles">
    <item>"<![CDATA[[01]  general focus]]>"</item>
    <item>"<![CDATA[[02]  general view for delibration]]>"</item>
</string-array>

<string-array name="array_lyrics">
    <item>"<![CDATA[general]]>"</item>
    <item>"<![CDATA[ General ]]>"</item>
    <item>"<![CDATA[ General ]]>"</item>
    <item>"<![CDATA[ General ]]>"</item>
</string-array>

<string-array name="newbrandDesc">
    <item>"<![CDATA[ description here ]]>"</item>
    <item>"<![CDATA[ description here ]]>"</item>
    <item>"<![CDATA[ description here ]]>"</item>
    <item>"<![CDATA[ here ]]>"</item>
</string-array>

File MainActivity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_weight="1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <View
        android:id="@+id/viewerage"
        android:background="#01312D"
        android:layout_width="match_parent"
        android:layout_height="5dp" />

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="70dp"
        android:layout_below="@id/viewerage"
        style="@style/scrollbar_shape_style"
        android:id="@+id/recyclerview">

    </androidx.recyclerview.widget.RecyclerView>

</RelativeLayout>

File MainActivity.java

public class MainActivity extends AppCompatActivity {

    private String TAG = "MainActivity ----- ; ";
    private static MediaPlayer player;
    String soundfile;
    TextView mDetailTv1;

    RecyclerView mRecyclerview;
    MyAdapter myAdapter;
    int [] MusicFile;
    List<String> title, newDesc, description;
    int[] icon;
    ArrayList<Model> arrayList = new ArrayList<Model>();

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

        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("Intro Songs");

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        // Listview icons for song titles in position
        icon = new int[]{R.drawable.song, R.drawable.song, R.drawable.song, };

        mRecyclerview = findViewById(R.id.recyclerview);
        mRecyclerview.setLayoutManager(new LinearLayoutManager(this));

        title = Arrays.asList(getResources().getStringArray(R.array.array_titles));

        // listview descriptions for songs in position
        description = Arrays.asList(getResources().getStringArray(R.array.array_lyrics));

        // listview NewDescriptions (NewActivity) for songs in position
        newDesc = Arrays.asList(getResources().getStringArray(R.array.newbrandDesc));

        // listview soundfile file for songs in position
        MusicFile = new int[] {R.raw.wex_1, R.raw.wex_2, R.raw.wex_3, , };

        for (int i = 0; i< title.size(); i++) {
            Model model = new Model(title.get(i), description.get(i), newDesc.get(i), icon[i], MusicFile[i]);
            // Bind all strings in an array
            arrayList.add(model);
        }

        // Pass result to listview class
        myAdapter = new MyAdapter(this, arrayList);

        // Bind the adapter to the listview class
        mRecyclerview.setAdapter(myAdapter);
    }

    @Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Are you sure you want to exit?")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        MainActivity.this.finish();
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.menu, menu);

        MenuItem item = menu.findItem(R.id.action_search);

        SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                myAdapter.getFilter().filter(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {

                myAdapter.getFilter().filter(newText);

                return false;
            }
        });

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            Toast.makeText(this, "Favorites Selected", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, FavoritesActivity.class));

            return true;

            // Do more funtionality here
        }
        return super.onOptionsItemSelected(item);
    }

}

File MyAdapter.java

public class MyAdapter extends RecyclerView.Adapter<MyHolder> implements Filterable {

    Context mContext;
    ArrayList<Model> models, filterList;  // This array list create a list of array
                                          // which parameter define in our class
    CustomFilter filter;

    public MyAdapter(Context context, ArrayList<Model> models) {
        this.mContext = context;
        this.models = models;
        this.filterList = models;
    }

    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row, null); // This line inflate our row

        return new MyHolder(view); // This will return our view to holder class
    }

    @Override
    public void onBindViewHolder(@NonNull final MyHolder myHolder, int i) {

        myHolder.mTitle.setText(models.get(i).getTitle()); // Here is position
        myHolder.mDesc.setText(models.get(i).getDesc());
        myHolder.mImageView.setImageResource(models.get(i).getIcon()); // Here we used an image resource

        myHolder.setItemCLickListener(new ItemClickListener() {
            @Override
            public void onItemClickListener(View v, int position) {

                String gTitle = models.get(position).getTitle();
                String gDesc = models.get(position).getDesc();
                BitmapDrawable bitmapDrawable = (BitmapDrawable)myHolder.mImageView.getDrawable();
                Bitmap bitmap = bitmapDrawable.getBitmap();

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byte[] bytes = stream.toByteArray();

                //get our data with intent
                Intent intent = new Intent(mContext, NewActivity.class);
                intent.putExtra("actionBarTitle", models.get(position).getTitle());
                intent.putExtra("brandNewDesc", models.get(position).getBrandNewDesc());
                intent.putExtra("soundfile", models.get(position).getSoundfile());
                intent.putExtra("iImage", bytes);
                mContext.startActivity(intent);
                return;
            }
        });
    }

    @Override
    public int getItemCount() {
        return models.size();
    }

    @Override
    public Filter getFilter() {

        if (filter == null) {
            filter = new CustomFilter(filterList, this);
        }

        return filter;
    }
}

File MyHolder.java

public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    ImageView mImageView;
    TextView mTitle, mDesc;
    ItemClickListener itemCLickListener;

    MyHolder(@NonNull View itemView) {
        super(itemView);

        this.mImageView = itemView.findViewById(R.id.mainIcon);
        this.mTitle = itemView.findViewById(R.id.mainTitle);
        this.mDesc = itemView.findViewById(R.id.mainDesc);

        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        this.itemCLickListener.onItemClickListener(v, getLayoutPosition());
    }

    public void setItemCLickListener(ItemClickListener ic) {

        this.itemCLickListener = ic;
    }
}

File CustomFilter.java

private ArrayList<Model> filterList;

    private MyAdapter adapter;

    public CustomFilter(ArrayList<Model> filterList, MyAdapter adapter) {
        this.filterList = filterList;
        this.adapter = adapter;
    }

    @Override
    protected FilterResults performFiltering(CharSequence constraints) {

        FilterResults filterResults = new FilterResults();

        if (constraints != null && constraints.length() > 0) {

            constraints = constraints.toString().toUpperCase();

            ArrayList<Model> filterModels = new ArrayList<>();
            for (int i = 0; i < filterList.size(); i++) {
                if (filterList.get(i).getTitle().toUpperCase().contains(constraints)) {
                    filterModels.add(filterList.get(i));
                }
            }

            filterResults.count = filterModels.size();
            filterResults.values = filterModels;
        }
        else {
            filterResults.count = filterList.size();
            filterResults.values = filterList;
        }
        return filterResults;
    }

    @Override
    protected void publishResults(CharSequence charSequence, FilterResults filterResults) {

        adapter.models = (ArrayList<Model>) filterResults.values;
        adapter.notifyDataSetChanged();
    }
}

File ItemClickListener.java - the interface

public interface ItemClickListener {

    void onItemClickListener(View v, int position);
}

public class NewActivity extends AppCompatActivity {
    private String TAG = "NewActivity ----- ; ";

    // Store instance variables
    private String title;
    private int page;
    TextView mBrandNewDesc;

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

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // Keeps Android screen on while reading through
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        ActionBar actionBar = getSupportActionBar();
        mBrandNewDesc = findViewById(R.id.textView);

        // Get data from previous activity when item of activity is clicked using intent
        Intent intent = getIntent();
        String mActionBarTitle = intent.getStringExtra("actionBarTitle");
        String newDescription = intent.getStringExtra("brandNewDesc");

        // setctionBar Title
        actionBar.setTitle(mActionBarTitle);

        // Get text in text textView
        mBrandNewDesc.setText(Html.fromHtml(newDescription));

        // OK, we are done. Let’s run the project
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

}

Body:
Instead of drawable>bitmap>byteArray send the drawable resource id like this code below changed the onBindViewHolder

@Override
public void onBindViewHolder(@NonNull final MyHolder myHolder, int i) {

    myHolder.mTitle.setText(models.get(i).getTitle()); //here is position
    myHolder.mDesc.setText(models.get(i).getDesc());
    myHolder.mImageView.setImageResource(models.get(i).getIcon()); // here we used imge resource

    myHolder.setItemCLickListener(new ItemClickListener() {
        @Override
        public void onItemClickListener(View v, int position) {

            String gTitle = models.get(position).getTitle();
            String gDesc = models.get(position).getDesc();
            int imageId = models.get(position).getIcon();

            //get our data with the intent
            Intent intent = new Intent(mContext, NewActivity.class);
            intent.putExtra("actionBarTitle", models.get(position).getTitle());
            intent.putExtra("brandNewDesc", models.get(position).getBrandNewDesc());
            intent.putExtra("soundfile", models.get(position).getSoundfile());
            intent.putExtra("iImage", imageId ); // i pass the int id then you can use this id in your next activity.
            mContext.startActivity(intent);
            return;
        }
    });

}

New Activity

    ImageView imageView;
    Intent intent = getIntent();
    if (intent != null && !intent.getExtras().isEmpty()){
        int imageResourceId = intent.getIntExtra("iImage",-1);
        imageView.setImageResource(imageResourceId);
    }


来源: stackexchange

问:
iterate over array of objects and fetch only specific key to form a new array of object in react js
I have below object. I want to iterate over it and need to fetch only key's values of ability and value key.

var object = [{
    ability: "Strong",
    name: "STRENGTH",
    value: "customer has 10 properties",
    type: "MultiChoice"
  },
  {
    ability: "Good",
    name: "STRENGTH",
    value: "customer has 5 properties",
    type: "MultiChoice"
  },
  {
    ability: "average",
    name: "STRENGTH",
    value: "customer has 3 properties",
    type: "MultiChoice"
  }
]
```

<p>So my expected output should be like below. </p>

<pre class="lang-js prettyprint-override"><code>[{
    ability: "Strong"
    value: "customer has 10 properties"
  },
  {
    ability: "Good"
    value: "customer has 5 properties"
  },
  {
    ability: "average"
    value: "customer has 3 properties"
  }
]
</code>```

Then I again want to use above object to iterate over it and bind its values to dropdown. So my drop-down will display "value" to end user and DB will have "ability". I am trying below code snippet but its not giving expected output. Something I am doing wrong here.

var object = [{
    ability: "Strong",
    name: "STRENGTH",
    value: "customer has 10 properties",
    type: "MultiChoice"
  },
  {
    ability: "Good",
    name: "STRENGTH",
    value: "customer has 5 properties",
    type: "MultiChoice"
  },
  {
    ability: "average",
    name: "STRENGTH",
    value: "customer has 3 properties",
    type: "MultiChoice"
  }
]

let multiChoiceResult = [];
let ability, value
Object.entries(object).map(([key, value]) => {
  ability = value.ability;
  value = value.value;
  multiChoiceResult.push(ability, value);
});
console.log(multiChoiceResult);```

答:
The map can be vastly simplified

https://ariya.io/2013/02/es6-and-object-literal-property-value-shorthand

var object = [{ ability: "Strong", name: "STRENGTH", value: "customer has 10 properties", type: "MultiChoice" },
  { ability: "Good", name: "STRENGTH", value: "customer has 5 properties", type: "MultiChoice" },
  { ability: "average", name: "STRENGTH", value: "customer has 3 properties",  type: "MultiChoice" }]

let multiChoiceResult = Object.values(object)
  .map(({ability, value}) => ({ability, value}));

console.log(multiChoiceResult);```
</div>
</div>
</p>

<p>For a drop down you can do </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>var object = [{ ability: "Strong", name: "STRENGTH", value: "customer has 10 properties", type: "MultiChoice" },
  { ability: "Good", name: "STRENGTH", value: "customer has 5 properties", type: "MultiChoice" },
  { ability: "average", name: "STRENGTH", value: "customer has 3 properties",  type: "MultiChoice" }]

let multiChoiceResult = Object.values(object)
  .map(({ability, value}) => `<option value="${ability}">${value}</option>`);

document.getElementById("abilities").innerHTML+=multiChoiceResult.join("")</code>```

<select id="abilities" name="abilities">
  <option value="">Please select</option>
</select>```

ContentLicense: CC BY-SA 4.0

Body:
I have below object. I want to iterate over it and need to fetch only key's values of ability and value key.

var object = [{
    ability: "Strong",
    name: "STRENGTH",
    value: "customer has 10 properties",
    type: "MultiChoice"
  },
  {
    ability: "Good",
    name: "STRENGTH",
    value: "customer has 5 properties",
    type: "MultiChoice"
  },
  {
    ability: "average",
    name: "STRENGTH",
    value: "customer has 3 properties",
    type: "MultiChoice"
  }
]

So my expected output should be like below.

[{
    ability: "Strong"
    value: "customer has 10 properties"
  },
  {
    ability: "Good"
    value: "customer has 5 properties"
  },
  {
    ability: "average"
    value: "customer has 3 properties"
  }
]

Then I again want to use above object to iterate over it and bind its values to dropdown. So my drop-down will display "value" to end user and DB will have "ability". I am trying below code snippet but its not giving expected output. Something I am doing wrong here.

var object = [{
    ability: "Strong",
    name: "STRENGTH",
    value: "customer has 10 properties",
    type: "MultiChoice"
  },
  {
    ability: "Good",
    name: "STRENGTH",
    value: "customer has 5 properties",
    type: "MultiChoice"
  },
  {
    ability: "average",
    name: "STRENGTH",
    value: "customer has 3 properties",
    type: "MultiChoice"
  }
]

let multiChoiceResult = [];
let ability, value
Object.entries(object).map(([key, value]) => {
  ability = value.ability;
  value = value.value;
  multiChoiceResult.push(ability, value);
});
console.log(multiChoiceResult);

Body:
The map can be vastly simplified

https://ariya.io/2013/02/es6-and-object-literal-property-value-shorthand

var object = [{ ability: "Strong", name: "STRENGTH", value: "customer has 10 properties", type: "MultiChoice" },
  { ability: "Good", name: "STRENGTH", value: "customer has 5 properties", type: "MultiChoice" },
  { ability: "average", name: "STRENGTH", value: "customer has 3 properties",  type: "MultiChoice" }]

let multiChoiceResult = Object.values(object)
  .map(({ability, value}) => ({ability, value}));

console.log(multiChoiceResult);

For a drop down you can do

var object = [{ ability: "Strong", name: "STRENGTH", value: "customer has 10 properties", type: "MultiChoice" },
  { ability: "Good", name: "STRENGTH", value: "customer has 5 properties", type: "MultiChoice" },
  { ability: "average", name: "STRENGTH", value: "customer has 3 properties",  type: "MultiChoice" }]

let multiChoiceResult = Object.values(object)
  .map(({ability, value}) => `<option value="${ability}">${value}</option>`);

document.getElementById("abilities").innerHTML+=multiChoiceResult.join("")

<select id="abilities" name="abilities">
  <option value="">Please select</option>
</select>


问:
Blazor, how to pass event target to JavaScript
I'd like to ask:

In Blazor, how to pass event target (or this) to my JavaScript?
The thing is I'm creating inputs with @foreach so there can be a number of them.

Here is how it looks like:

```<code>@foreach (Item in ItemsList)
        {
          <input
              @onchange="ChangeColor"
              value="@Item.Value">
}
</code>```

I want to simple onchange trigger this function:

```<code>@code

{
    async Task ChangeColor()
    {
        await JsRuntime.InvokeVoidAsync("changeColor");
    }
}
</code>```

And eventually read the value in my JS:

```<code>function changeColor (el) {

   console.log(el);

}
</code>```

I tried using @ref, however I'd like to get access to the input that triggers the function. Since there may by many of them, I don't want to hardcode it using @ref to each of them.

答:
As said in the comments

@Vencovsky I hoped to get DOM elemenet

And if you want to show in the console the DOM element, you need to pass @ref to the DOM element and pass that reference to javascript

But then you say in your question

I tried using @ref, however I'd like to get access to the input that triggers the function. Since there may by many of them, I don't want to hardcode it using @ref to each of them.

So it's kind of confusing, because you need to use @ref but you say you don't want to use @ref, so what I think is happening is that you used @ref the wrong way and you think you don't need it, but actually you do.

Here is what you need

A property to hold all the refs of each element (ElementReference)

Pass to ChangeColor only the element that is clicked

Here is an example on how to do it

```<code>@for(var i = 0; i < ItemsList.Count(); i++)
{
    var ii = i;

    @* Passing only the ref that called @onchange *@
    <input @onchange="(() => ChangeColor(Refs[ii]))"
           @ref="Refs[ii]"
           value="@ItemsList[ii]">
}

@code
{
    [Inject]
    IJSRuntime JSRuntime  { get; set; }

    async Task ChangeColor(ElementReference el)
    {
        await JSRuntime.InvokeVoidAsync("changeColor", el);
    }

    // Property that will hold the refs
    ElementReference[] Refs { get; set; }

    string[] ItemsList { get; set; } = new string[]
        {
            "hey",
            "hope",
            "this",
            "works"
        };
}
</code>```

Body:
I'd like to ask:

In Blazor, how to pass event target (or this) to my JavaScript?
The thing is I'm creating inputs with @foreach so there can be a number of them.

Here is how it looks like:

@foreach (Item in ItemsList)
        {
          <input
              @onchange="ChangeColor"
              value="@Item.Value">
}

I want to simple onchange trigger this function:

@code

{
    async Task ChangeColor()
    {
        await JsRuntime.InvokeVoidAsync("changeColor");
    }
}

And eventually read the value in my JS:

function changeColor (el) {

   console.log(el);

}

I tried using @ref, however I'd like to get access to the input that triggers the function. Since there may by many of them, I don't want to hardcode it using @ref to each of them.

Body:
As said in the comments

@Vencovsky I hoped to get DOM elemenet

And if you want to show in the console the DOM element, you need to pass @ref to the DOM element and pass that reference to javascript

But then you say in your question

I tried using @ref, however I'd like to get access to the input that triggers the function. Since there may by many of them, I don't want to hardcode it using @ref to each of them.

So it's kind of confusing, because you need to use @ref but you say you don't want to use @ref, so what I think is happening is that you used @ref the wrong way and you think you don't need it, but actually you do.

Here is what you need

A property to hold all the refs of each element (ElementReference)

Pass to ChangeColor only the element that is clicked

Here is an example on how to do it

@for(var i = 0; i < ItemsList.Count(); i++)
{
    var ii = i;

    @* Passing only the ref that called @onchange *@
    <input @onchange="(() => ChangeColor(Refs[ii]))"
           @ref="Refs[ii]"
           value="@ItemsList[ii]">
}

@code
{
    [Inject]
    IJSRuntime JSRuntime  { get; set; }

    async Task ChangeColor(ElementReference el)
    {
        await JSRuntime.InvokeVoidAsync("changeColor", el);
    }

    // Property that will hold the refs
    ElementReference[] Refs { get; set; }

    string[] ItemsList { get; set; } = new string[]
        {
            "hey",
            "hope",
            "this",
            "works"
        };
}


问:
How to display first N posts in Jekyll
I'm using Jekyll 2 for my blog. I'm also using jekyll-paginate to display the first 5 posts in the home page.

Now I would like to stop using jekyll-paginate, since it's polluting the sitemap with pages I don't want.

This is how my home page looks like, after removing the pagination:

```<code>---
layout: default
---

<div class="blog-index">
  {% assign index = true %}
  {% for post in site.posts %}
  {% assign content = post.content %}
    <article>
      {% include article.html %}
    </article>
  {% endfor %}
</div>
</code>```

This displays all the posts, but I only want the first 5. In Ruby you can do .take(5) or .first(5), so I tried that, but it doesn't work.

How do I display only the 5 most recent posts?

答:
You may use the limit parameter in a for loop to do this:

```<code>
{% for post in site.posts limit:5 %}
   <article>
      {% include article.html %}
    </article>
{% end %}
</code>```

docs: https://shopify.github.io/liquid/tags/iteration/#limit

Title: How to display first N posts in Jekyll

Body:
I'm using Jekyll 2 for my blog. I'm also using jekyll-paginate to display the first 5 posts in the home page.

Now I would like to stop using jekyll-paginate, since it's polluting the sitemap with pages I don't want.

This is how my home page looks like, after removing the pagination:

---
layout: default
---

  {% assign index = true %}
  {% for post in site.posts %}
  {% assign content = post.content %}

      {% include article.html %}

  {% endfor %}

This displays all the posts, but I only want the first 5. In Ruby you can do .take(5) or .first(5), so I tried that, but it doesn't work.

How do I display only the 5 most recent posts?

Body:
You may use the limit parameter in a for loop to do this:

{% for post in site.posts limit:5 %}
   <article>
      {% include article.html %}
    </article>
{% end %}

docs: https://shopify.github.io/liquid/tags/iteration/#limit


问:
Cant explain why page wont work in IE
At the top of this page: http://andrew-muir.com/search/2/#1 - When you click on the slider it will load new results using AJAX into a div. When i chose certain prices on the slider the results look fine in IE and when i chose other prices the results come back all broken.

Any ideas? Thanks!

答:
There's a lot of invalid markup in the HTML fragment that comes back from the slider actions. You've got some unclosed tags, etc.

Example:

```<code>    <div style="background-color:#252525; padding:5px 10px; height:130px; position:relative;">

        <p class="bold" style="color:#8a96a4; margin-bottom:0.5em;">Blue Lucerne lotus jug</p>

        <p class="bold" style="color:#FFF; margin-bottom:0.5em;">£4250</p>

        <p style="margin-bottom:0.5em;"><p><strong>Superb and very rare 30cm lotus jug in the bl…</p>

        <p class="boldred" style="position:absolute; bottom:0px; left:10px;"><a href="http://andrew-muir.com/stock/528/blue-lucerne-lotus-jug/">View details ></a></p>

    </div>
</code>```

That line with the "Superb and rare" text has an unclosed  tag.

When I try to look at the broken page in the IE 8 developer tool, it won't show me the content of the main
.  That's a sure sign that the browser has just thrown up its hands in frustration.

edit — weird; it just started working ...

ContentLicense: CC BY-SA 3.0

Title: Cant explain why page wont work in IE

Body:
There's a lot of invalid markup in the HTML fragment that comes back from the slider actions. You've got some unclosed tags, etc.

Example:

    <div style="background-color:#252525; padding:5px 10px; height:130px; position:relative;">

        <p class="bold" style="color:#8a96a4; margin-bottom:0.5em;">Blue Lucerne lotus jug</p>

        <p class="bold" style="color:#FFF; margin-bottom:0.5em;">&pound;4250</p>

        <p style="margin-bottom:0.5em;"><p><strong>Superb and very rare 30cm lotus jug in the bl&hellip;</p>

        <p class="boldred" style="position:absolute; bottom:0px; left:10px;"><a href="http://andrew-muir.com/stock/528/blue-lucerne-lotus-jug/">View details &gt;</a></p>

    </div>

That line with the "Superb and rare" text has an unclosed <strong> tag.

When I try to look at the broken page in the IE 8 developer tool, it won't show me the content of the main <div>.  That's a sure sign that the browser has just thrown up its hands in frustration.

edit — weird; it just started working ...


问:
Materializecss select double click to toggle
I am using MaterializeCSS to create a select 'dropdown' menu. On a Mac laptop the dropdown is working fine (tested in Safari and FireFox, and in IE and Chrome through browserling.com). However, when I browse the website from a Windows computer (IE and Chrome) I always have to double click to toggle the dropdown. I don't understand why this issue happens. I would appreciate if anyone can point to a specific issue with the code as set out below:

```<code>  <div class="dropdown-div">
    <div class="input-field">
      <select>
        <option value="1" class="dropdown-text"><a class="dropdown-text-default" data-url="#General">General</a></option>
        <option value="2"><a class="dropdown-text" data-url="#Option1">Option1</a></option>
        <option value="3"><a class="dropdown-text" data-url="#Option2">Option2</a></option>
        <option value="4"><a class="dropdown-text" data-url="#Option3">Option3</a></option>
        <option value="5"><a class="dropdown-text" data-url="#Option4">Option4</a></option>
      </select>
    </div>
  </div>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/js/materialize.min.js"></script>
  <script type="text/javascript">
  $(document).ready(function() {
    $('select').material_select();
  });
  </script>
</code>```

Please find the documentation from MaterializeCSS here.

答:
Here's a hack, using jQuery

```<code>$('.select-dropdown').trigger("click");
</code>```

I've had the same issue on materialize selects, I couldn't find a patch anywhere.

So the theory is, If it works with a double click, then trigger another click on this instance.

Here's the context I applied it for my application

I have a select drop down like:

```<code><div class="input-field ingredient-unit">
  <select name="" id="ingredient-unit">
     <option value="gr" selected>gr</option>
     <option value="kg" >kg</option>
     <option value="cups" >cups</option>
     <option value="ml" >ml</option>
     <option value="L" >L</option>
     <option value="tsp" >tsp</option>
     <option value="Tbsp" >Tbsp</option>
     <option value="pcs" >pcs</option>
 </select>
 <label for="ingredient-unit"></label>
</div>
</code>```

To get the value of this select, I have a javascript function like:

```<code>$('.add-ingredient-button').click(function(){

    // due to a materialize css bug with chrome, take two clicks to activate the given selection
    // we hack this by triggering another click on the #ingredient-unit instance here
    $('.select-dropdown').trigger("click");

    //then we get the dropdown instance, everything else can be done with jQuery
    const ingredientUnit = M.FormSelect.getInstance($('#ingredient-unit'));

    // we need to grab information from all those boxes
    const name  = $('#ingredient-name').val();
    const value = $('#ingredient-value').val();
    const unit  = ingredientUnit.getSelectedValues();
    console.log(name,value,unit);
});
</code>```

When the button with class .add-ingredient-button is pressed, we want to get the ingredient name, value and unit. The unit is in a materialize select instance.

So the function is triggered when we click on .add-ingredient-button, and we 'manually' trigger another click on the select instance, which effectively picks the unit that the user had already selected.

I'm not sure why this error occurred, and I can't really tell you why this is working.
But it works.

I hope it helps!

Body:
I am using MaterializeCSS to create a select 'dropdown' menu. On a Mac laptop the dropdown is working fine (tested in Safari and FireFox, and in IE and Chrome through browserling.com). However, when I browse the website from a Windows computer (IE and Chrome) I always have to double click to toggle the dropdown. I don't understand why this issue happens. I would appreciate if anyone can point to a specific issue with the code as set out below:

      <select>
        <option value="1" class="dropdown-text">General</option>
        <option value="2">Option1</option>
        <option value="3">Option2</option>
        <option value="4">Option3</option>
        <option value="5">Option4</option>
      </select>

Please find the documentation from MaterializeCSS here.

Body:
Here's a hack, using jQuery

$('.select-dropdown').trigger("click");

I've had the same issue on materialize selects, I couldn't find a patch anywhere.

So the theory is, If it works with a double click, then trigger another click on this instance.

Here's the context I applied it for my application

I have a select drop down like:

<div class="input-field ingredient-unit">
  <select name="" id="ingredient-unit">
     <option value="gr" selected>gr</option>
     <option value="kg" >kg</option>
     <option value="cups" >cups</option>
     <option value="ml" >ml</option>
     <option value="L" >L</option>
     <option value="tsp" >tsp</option>
     <option value="Tbsp" >Tbsp</option>
     <option value="pcs" >pcs</option>
 </select>
 <label for="ingredient-unit"></label>
</div>

To get the value of this select, I have a javascript function like:

$('.add-ingredient-button').click(function(){

    // due to a materialize css bug with chrome, take two clicks to activate the given selection
    // we hack this by triggering another click on the #ingredient-unit instance here
    $('.select-dropdown').trigger("click");

    //then we get the dropdown instance, everything else can be done with jQuery
    const ingredientUnit = M.FormSelect.getInstance($('#ingredient-unit'));

    // we need to grab information from all those boxes
    const name  = $('#ingredient-name').val();
    const value = $('#ingredient-value').val();
    const unit  = ingredientUnit.getSelectedValues();
    console.log(name,value,unit);
});

When the button with class .add-ingredient-button is pressed, we want to get the ingredient name, value and unit. The unit is in a materialize select instance.

So the function is triggered when we click on .add-ingredient-button, and we 'manually' trigger another click on the select instance, which effectively picks the unit that the user had already selected.

I'm not sure why this error occurred, and I can't really tell you why this is working.
But it works.

I hope it helps!


问:
How can I calculate the area of a circle which I detected with cv2.HoughCircles()?
guys,

I have written a program where I recognize circles with cv2.HoughCircles(). The code works too. Unfortunately I need the area of the circles for my project. But I don't know how to calculate this and my search on the internet was unsuccessful.

Thank you.

答:
https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghcircles/py_houghcircles.html

```<code>import cv2
import numpy as np

img = cv2.imread('opencv_logo.png',0)
img = cv2.medianBlur(img,5)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)

circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,20,
                            param1=50,param2=30,minRadius=0,maxRadius=0)

circles = np.uint16(np.around(circles))
for i in circles[0,:]:
    # draw the outer circle
    cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
    # draw the center of the circle
    cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)

cv2.imshow('detected circles',cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

i[0] is the x position

i[1] is the y position

i[2] is the radius

Area is calculated with the formula pi * r²

So the area of each detected circle would be:

```<code>for i in circles[0,:]:
  area = 3.14159 * i[2] * i[2]
</code>```

Body:
https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghcircles/py_houghcircles.html

import cv2
import numpy as np

img = cv2.imread('opencv_logo.png',0)
img = cv2.medianBlur(img,5)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)

circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,20,
                            param1=50,param2=30,minRadius=0,maxRadius=0)

circles = np.uint16(np.around(circles))
for i in circles[0,:]:
    # draw the outer circle
    cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
    # draw the center of the circle
    cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)

cv2.imshow('detected circles',cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()

i[0] is the x position

i[1] is the y position

i[2] is the radius

Area is calculated with the formula pi * r²

So the area of each detected circle would be:

for i in circles[0,:]:
  area = 3.14159 * i[2] * i[2]


问:
Can you override the NODE_ENV env variable in create-react-app@3.x?
I'd like to manually change the value of the NODE_ENV environment variable when I build my React app in development node (yarn run start).

答:
No, as per create-react-app@3.4.1 at least, this is not possible. Excerpt from the docs:

There is also a built-in environment variable called NODE_ENV. You can read it from process.env.NODE_ENV. When you run npm start, it is always equal to 'development', when you run npm test it is always equal to 'test', and when you run npm run build to make a production bundle, it is always equal to 'production'. You cannot override NODE_ENV manually. This prevents developers from accidentally deploying a slow development build to production.


问:
Type inference changes in Scala 3
What changes in type inference will Scala 3 bring? <s>Currently documentation simply states TODO</s>. For example,

Weak conformance

Scala 2.13

```<code>scala> val i: Int = 42
val i: Int = 42

scala> val c: Char = 'a'
val c: Char = a

scala> List(i,c)
val res0: List[Int] = List(42, 97)
</code>```

Scala 3 (dotty 0.24.0-RC1)

```<code>scala> val i: Int = 42
val i: Int = 42

scala> val c: Char = 'a'
val c: Char = a

scala> List(i,c)
val res0: List[AnyVal] = List(42, a)
</code>```

Equality

Scala 2.13

```<code>scala> 42 == Some(42)
          ^
       warning: comparing values of types Int and Some[Int] using `==` will always yield false
val res2: Boolean = false
</code>```

Scala 3

```<code>scala> 42 == Some(42)
1 |42 == Some(42)
  |^^^^^^^^^^^^^^
  |Values of types Int and Some[Int] cannot be compared with == or !=
</code>```

答:
So as for your Equality example it is actually caused by the new Multiversal Equality which pretty much means that if you have an Eql[A, B] where A is B then type A can only be compared to things it has an Eql instance for them (of the form Eql[A, C] or Eql[C, A]).

In terms of general type inference for scala 3, the main things are:

Union Types: We can now represent union types and expressions like

 if (condition) 1 else "1"
```

<p>should be of inferred as of type <code>Int | String</code>.</p></li>
<li><p>Explicit Nulls: One of the new uses for union types is a way to describe nullable types, so for example we could write such a code in Java:</p>

<pre class="lang-java prettyprint-override"><code> public String getUser(int id) {
     if (id == 0) {
         return "Admin";
     }
     return null;
 }
</code>```

And also in scala 2 we could write:

def getUser(id: Int): String = if (id == 0) return "Admin" else null
```

<p>But in scala 3 such a method will also have to be declared as of type <code>String | Null</code> to represent its nullability, and will not compile by default in newer versions of scala 3.</p>

<p>When working with Java it gets more complicated so if you want to know more about it I suggest reading in the link.</p></li>
<li><p>GADT: Similar to how <code>@functionalInterface</code> works in java we know have GADTs.
That means that if you were to have a trait with one unimplemented method:</p>

<pre class="lang-scala prettyprint-override"><code>trait Fooable {
    def foo(): Unit
}
</code>```

You could create an instance of it by passing a lambda with that signature, so in this example:

val fooable: Fooable = () => print("Fooing")
```

There are a few more, including Context Functions, Implicit Conversions and Parameter untupling but those are the main ones.

Title: Type inference changes in Scala 3

Body:
What changes in type inference will Scala 3 bring? <s>Currently documentation simply states TODO</s>. For example,

Weak conformance

Scala 2.13

scala> val i: Int = 42
val i: Int = 42

scala> val c: Char = 'a'
val c: Char = a

scala> List(i,c)
val res0: List[Int] = List(42, 97)

Scala 3 (dotty 0.24.0-RC1)

scala> val i: Int = 42
val i: Int = 42

scala> val c: Char = 'a'
val c: Char = a

scala> List(i,c)
val res0: List[AnyVal] = List(42, a)

Equality

Scala 2.13

scala> 42 == Some(42)
          ^
       warning: comparing values of types Int and Some[Int] using `==` will always yield false
val res2: Boolean = false

Scala 3

scala> 42 == Some(42)
1 |42 == Some(42)
  |^^^^^^^^^^^^^^
  |Values of types Int and Some[Int] cannot be compared with == or !=

Body:
So as for your Equality example it is actually caused by the new Multiversal Equality which pretty much means that if you have an Eql[A, B] where A is B then type A can only be compared to things it has an Eql instance for them (of the form Eql[A, C] or Eql[C, A]).

In terms of general type inference for scala 3, the main things are:

Union Types: We can now represent union types and expressions like

 if (condition) 1 else "1"

should be of inferred as of type Int | String.

Explicit Nulls: One of the new uses for union types is a way to describe nullable types, so for example we could write such a code in Java:

 public String getUser(int id) {
     if (id == 0) {
         return "Admin";
     }
     return null;
 }

And also in scala 2 we could write:

def getUser(id: Int): String = if (id == 0) return "Admin" else null

But in scala 3 such a method will also have to be declared as of type String | Null to represent its nullability, and will not compile by default in newer versions of scala 3.

When working with Java it gets more complicated so if you want to know more about it I suggest reading in the link.

GADT: Similar to how @functionalInterface works in java we know have GADTs.
That means that if you were to have a trait with one unimplemented method:

trait Fooable {
    def foo(): Unit
}

You could create an instance of it by passing a lambda with that signature, so in this example:

val fooable: Fooable = () => print("Fooing")

There are a few more, including Context Functions, Implicit Conversions and Parameter untupling but those are the main ones.


问:
How to make rounded corner bars with angular-google-charts
I'm using angular-google-charts for one of my applications and I have a requirement to develop column chart with a rounded corner.

Is there a way to implement this with angular-google-charts

.ts file

```<code>export class ColumnChartComponent implements OnInit {

  title = 'Population (in millions)';
  type = 'ColumnChart';
  data = [
    ["2012", 900, 390],
    ["2013", 1000, 400],
    ["2014", 1170, 440],
    ["2015", 1250, 480],
    ["2016", 1530, 540]
  ];
  columnNames = ['Year', 'Asia', 'Europe'];
  options = {
    hAxis: {
      title: 'Year'
    },
    vAxis: {
      minValue: 0
    },
    isStacked: true
  }

  width = 550;
  height = 400;

  constructor() { }

  ngOnInit(): void {
  }

}
</code>```

.HTML file (template file)

```<code><google-chart #chart
   [title]="title"
   [type]="type"
   [data]="data"
   [options]="options"
   [width]="width"
   [height]="height">
</google-chart>
</code>```

答:
Use below code... and check jsfiddle http://jsfiddle.net/0dzp3jxw/</p>

```<code> <canvas id="myChart" height="300" width="800"></canvas>

 Chart.types.Bar.extend({
 name: "BarAlt",
 initialize: function (data) {
    Chart.types.Bar.prototype.initialize.apply(this, arguments);

    if (this.options.curvature !== undefined && this.options.curvature <= 1) {
        var rectangleDraw = this.datasets[0].bars[0].draw;
        var self = this;
        var radius = this.datasets[0].bars[0].width * this.options.curvature * 0.5;

        // override the rectangle draw with ours
        this.datasets.forEach(function (dataset) {
            dataset.bars.forEach(function (bar) {
                bar.draw = function () {
                    // draw the original bar a little down (so that our curve brings it to its original position)
                    var y = bar.y;
                    // the min is required so animation does not start from below the axes
                    bar.y = Math.min(bar.y + radius, self.scale.endPoint - 1);
                    // adjust the bar radius depending on how much of a curve we can draw
                    var barRadius = (bar.y - y);
                    rectangleDraw.apply(bar, arguments);

                    // draw a rounded rectangle on top
                    Chart.helpers.drawRoundedRectangle(self.chart.ctx, bar.x - bar.width / 2, bar.y - barRadius + 1, bar.width, bar.height, barRadius);
                    ctx.fill();

                    // restore the y value
                    bar.y = y;
                }
            })
        })
    }
    }
 });

 var lineChartData = {
 labels: ["January", "February", "March", "April", "May", "June"],
 datasets: [
     {
        fillColor: "#79D1CF",
        strokeColor: "#79D1CF",
        data: [60, 80, 81, 56, 55, 40]
    },
    {
        fillColor: "#D1CF79",
        strokeColor: "#D1CF79",
        data: [4, 5, 10, 1, 2, 3]
    }
   ]
 };

 var ctx = document.getElementById("myChart").getContext("2d");
 var myLine = new Chart(ctx).BarAlt(lineChartData, {
 // 0 (flat) to 1 (more curvy)
 curvature: 1
 });
</code>```

Body:
I'm using angular-google-charts for one of my applications and I have a requirement to develop column chart with a rounded corner.

Is there a way to implement this with angular-google-charts

.ts file

export class ColumnChartComponent implements OnInit {

  title = 'Population (in millions)';
  type = 'ColumnChart';
  data = [
    ["2012", 900, 390],
    ["2013", 1000, 400],
    ["2014", 1170, 440],
    ["2015", 1250, 480],
    ["2016", 1530, 540]
  ];
  columnNames = ['Year', 'Asia', 'Europe'];
  options = {
    hAxis: {
      title: 'Year'
    },
    vAxis: {
      minValue: 0
    },
    isStacked: true
  }

  width = 550;
  height = 400;

  constructor() { }

  ngOnInit(): void {
  }

}

.HTML file (template file)

<google-chart #chart
   [title]="title"
   [type]="type"
   [data]="data"
   [options]="options"
   [width]="width"
   [height]="height">
</google-chart>

Body:
Use below code... and check jsfiddle http://jsfiddle.net/0dzp3jxw/

 <canvas id="myChart" height="300" width="800"></canvas>

 Chart.types.Bar.extend({
 name: "BarAlt",
 initialize: function (data) {
    Chart.types.Bar.prototype.initialize.apply(this, arguments);

    if (this.options.curvature !== undefined && this.options.curvature <= 1) {
        var rectangleDraw = this.datasets[0].bars[0].draw;
        var self = this;
        var radius = this.datasets[0].bars[0].width * this.options.curvature * 0.5;

        // override the rectangle draw with ours
        this.datasets.forEach(function (dataset) {
            dataset.bars.forEach(function (bar) {
                bar.draw = function () {
                    // draw the original bar a little down (so that our curve brings it to its original position)
                    var y = bar.y;
                    // the min is required so animation does not start from below the axes
                    bar.y = Math.min(bar.y + radius, self.scale.endPoint - 1);
                    // adjust the bar radius depending on how much of a curve we can draw
                    var barRadius = (bar.y - y);
                    rectangleDraw.apply(bar, arguments);

                    // draw a rounded rectangle on top
                    Chart.helpers.drawRoundedRectangle(self.chart.ctx, bar.x - bar.width / 2, bar.y - barRadius + 1, bar.width, bar.height, barRadius);
                    ctx.fill();

                    // restore the y value
                    bar.y = y;
                }
            })
        })
    }
    }
 });

 var lineChartData = {
 labels: ["January", "February", "March", "April", "May", "June"],
 datasets: [
     {
        fillColor: "#79D1CF",
        strokeColor: "#79D1CF",
        data: [60, 80, 81, 56, 55, 40]
    },
    {
        fillColor: "#D1CF79",
        strokeColor: "#D1CF79",
        data: [4, 5, 10, 1, 2, 3]
    }
   ]
 };

 var ctx = document.getElementById("myChart").getContext("2d");
 var myLine = new Chart(ctx).BarAlt(lineChartData, {
 // 0 (flat) to 1 (more curvy)
 curvature: 1
 });


问:
Can I get the first day of the week based on locale data?
Different countries begin a work week on different days (Sunday vs. Monday, etc.)

Go has the text/language package, and the time package has support for locations, but I can't find anything in the core libraries that mention the start of the week.

Is there a way to get the first day of the week, given a locale?

答: No. There is no std library that can do this</p>


答:
From HoughCircles() you get a list of 'circles' which contains x, y, r of the circle. x, y are coordinates of the center and r is the radius.
From the radius you can calculate the area of the circle with:

A = PI * r^2

Title: How can I calculate the area of a circle which I detected with cv2.HoughCircles()?

Body:
guys,

I have written a program where I recognize circles with cv2.HoughCircles(). The code works too. Unfortunately I need the area of the circles for my project. But I don't know how to calculate this and my search on the internet was unsuccessful.

Thank you.


问:
Migrating from .net core 3.0 to 3.1 causes missing System.Data.SqlClient assembly error
I have a .net core project that references a .net framework library. The framework library uses System.Data.SqlClient to access a database. When the core project was running on dotnet core 3.0 everything was working fine. However, I just migrated to 3.1 and now I am getting the following exception:

```<code>FileNotFoundException: Could not load file or assembly 'System.Data.SqlClient, Version=4.6.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.
</code>```

I tried explicitly installing System.Data.SqlClient v. 4.6.0 via Nuget in the framework library, but I still get the same exception.

答:
tl;dr: install the Microsoft.Windows.Compatibility metapackage into your Core/Standard project to fix this.

The version you are seeing in the error message is the assembly version that the .NET Framework project is expecting. This corresponds to the version that is shipped with the .NET Framework version that said project is compiled against.

Since .NET Core (and Standard) is far less tightly coupled than Framework, many namespaces that were previously part of the Framework have been broken out into their own NuGet packages. System.Data.SqlClient is one of these, so the answer is to install the appropriate version of that package into your .NET Core/Standard project... right?

Yes, but it's not the best answer.

Because SqlClient was developed independently of its NuGet package, the assembly version of that library is not the same as the version of its package, and in fact these versions cannot be related simply by inspecting them. The only way to figure out which version corresponds to which package is to manually inspect the NuGet package versions and compare them to the assembly version of the DLLs contained in those packages - I've done that hard work in the below table so you don't have to. Other namespaces and packages will likely have similar insanity going on.

However!

Microsoft has made the above pain completely unnecessary with the Microsoft.Windows.Compatibility metapackage. If you install it into your Core/Standard project, the correct versions of all packages that your Framework projects depend on will be pulled in. Not only that, if you change the version in your Framework projects, the corresponding updated versions of the dependent packages will be pulled in the next time you do a build!

This is far better than manually referencing the specific packages you need (such as System.Data.SqlClient), because if you install specific versions of those packages and changed your Framework version, things would again break at runtime. It's just unnecessary pain for pain's sake.

So, install Microsoft.Windows.Compatibility, and say goodbye to versioning hell!

Reference list of System.Data.SqlClient versions

```
| NuGet package version | Assembly version | File version   |
|-----------------------|------------------|----------------|
|                 4.8.1 |          4.6.1.1 | 4.700.20.6702  |
|                 4.8.0 |          4.6.1.0 | 4.700.19.56404 |
|                 4.7.0 |          4.6.0.0 | 4.700.19.46214 |
|                 4.6.1 |          4.5.0.1 | 4.6.27618.01   |
|                 4.6.0 |          4.5.0.0 | 4.6.27110.04   |
|                 4.5.3 |          4.4.0.1 | 4.6.28516.10   |
|                 4.5.1 |          4.4.0.0 | 4.6.26606.05   |
|                 4.5.0 |          4.4.0.0 | 4.6.26515.06   |
|                 4.4.3 |          4.2.0.2 | 4.6.26212.01   |
|                 4.4.2 |          4.2.0.1 | 4.6.25921.02   |
|                 4.4.1 |          4.2.0.1 | 4.6.25706.01   |
|                 4.4.0 |          4.2.0.0 | 4.6.25519.03   |
|                 4.3.1 |          4.1.1.1 | 4.6.25220.01   |
|                 4.3.0 |          4.1.1.0 | 4.6.24705.01   |
|                 4.1.0 |          4.1.0.0 | 1.0.24212.01   |
```

Body:
I have a .net core project that references a .net framework library. The framework library uses System.Data.SqlClient to access a database. When the core project was running on dotnet core 3.0 everything was working fine. However, I just migrated to 3.1 and now I am getting the following exception:

FileNotFoundException: Could not load file or assembly 'System.Data.SqlClient, Version=4.6.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.

I tried explicitly installing System.Data.SqlClient v. 4.6.0 via Nuget in the framework library, but I still get the same exception.

Body:
tl;dr: install the Microsoft.Windows.Compatibility metapackage into your Core/Standard project to fix this.

The version you are seeing in the error message is the assembly version that the .NET Framework project is expecting. This corresponds to the version that is shipped with the .NET Framework version that said project is compiled against.

Since .NET Core (and Standard) is far less tightly coupled than Framework, many namespaces that were previously part of the Framework have been broken out into their own NuGet packages. System.Data.SqlClient is one of these, so the answer is to install the appropriate version of that package into your .NET Core/Standard project... right?

Yes, but it's not the best answer.

Because SqlClient was developed independently of its NuGet package, the assembly version of that library is not the same as the version of its package, and in fact these versions cannot be related simply by inspecting them. The only way to figure out which version corresponds to which package is to manually inspect the NuGet package versions and compare them to the assembly version of the DLLs contained in those packages - I've done that hard work in the below table so you don't have to. Other namespaces and packages will likely have similar insanity going on.

However!

Microsoft has made the above pain completely unnecessary with the Microsoft.Windows.Compatibility metapackage. If you install it into your Core/Standard project, the correct versions of all packages that your Framework projects depend on will be pulled in. Not only that, if you change the version in your Framework projects, the corresponding updated versions of the dependent packages will be pulled in the next time you do a build!

This is far better than manually referencing the specific packages you need (such as System.Data.SqlClient), because if you install specific versions of those packages and changed your Framework version, things would again break at runtime. It's just unnecessary pain for pain's sake.

So, install Microsoft.Windows.Compatibility, and say goodbye to versioning hell!

Reference list of System.Data.SqlClient versions

| NuGet package version | Assembly version | File version   |
|-----------------------|------------------|----------------|
|                 4.8.1 |          4.6.1.1 | 4.700.20.6702  |
|                 4.8.0 |          4.6.1.0 | 4.700.19.56404 |
|                 4.7.0 |          4.6.0.0 | 4.700.19.46214 |
|                 4.6.1 |          4.5.0.1 | 4.6.27618.01   |
|                 4.6.0 |          4.5.0.0 | 4.6.27110.04   |
|                 4.5.3 |          4.4.0.1 | 4.6.28516.10   |
|                 4.5.1 |          4.4.0.0 | 4.6.26606.05   |
|                 4.5.0 |          4.4.0.0 | 4.6.26515.06   |
|                 4.4.3 |          4.2.0.2 | 4.6.26212.01   |
|                 4.4.2 |          4.2.0.1 | 4.6.25921.02   |
|                 4.4.1 |          4.2.0.1 | 4.6.25706.01   |
|                 4.4.0 |          4.2.0.0 | 4.6.25519.03   |
|                 4.3.1 |          4.1.1.1 | 4.6.25220.01   |
|                 4.3.0 |          4.1.1.0 | 4.6.24705.01   |
|                 4.1.0 |          4.1.0.0 | 1.0.24212.01   |


问:
Play mp3 on iPad Safari
Is it possible to play embedded MP3 on iPad Safari (the way you do on normal desktop browsers) ?

If yes, do we need to code separately for iPad Safari ?

The reason I am asking is bcoz in my app, the desktop code for mp3 is not working on iPad..
The code for desktop is

```<code><EMBED src="'+audioUrl+'" autostart=true loop=false volume=100 hidden=true>
</code>```

答:
Why don't you just use the <audio> tag, that's what it's there for.

To answer your question, yes it is possible.

Title: Play mp3 on iPad Safari

Body:
Is it possible to play embedded MP3 on iPad Safari (the way you do on normal desktop browsers) ?

If yes, do we need to code separately for iPad Safari ?

The reason I am asking is bcoz in my app, the desktop code for mp3 is not working on iPad..
The code for desktop is

<EMBED src="'+audioUrl+'" autostart=true loop=false volume=100 hidden=true>


问:
Adding data labels (annotations?) to Google Charts (Visualizations API) drawn from a query
I'm creating a line chart by querying data entered into a Google Sheet, and I need to add data labels, i.e. the little numbers next to the points on the chart. I found plenty of documentation on how to do this with charts drawn from a manually entered data-table, but not from a query to a Google Sheet. Please help.</p>

```<code>google.charts.load('current', {'packages':['corechart', 'line']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
var query = new google.visualization.Query(
  'URL'
);
query.setQuery('SELECT A, B OFFSET 0'); //select specific cells from the table
query.send(handleQueryResponse);
}

function handleQueryResponse(response) {
if (response.isError()) {
  alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
  return;
}

var data = response.getDataTable();
var options = {
  title: '',
  height : 250,
  width : '100%',

    }
 var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</code>```

答:
correct, you want to add annotations.

this can be done using an annotation column role.

the annotation column role, should directly follow the series column it represents in the data table.

in this case, since you are getting the data from a query,

we can use a DataView to add the annotation using a calculated column.

first, we create the data view.

```<code>  var view = new google.visualization.DataView(data);
</code>```

then we use the setColumns method,

to add the column indexes from the query,

and our calculated column for the annotation.

```<code>  view.setColumns([0, 1, {
    calc: 'stringify',
    sourceColumn: 1,
    type: 'string',
    role: 'annotation'
  }]);
</code>```

finally, we need to use the view to draw the chart.

```<code>chart.draw(view, options);
</code>```

see following snippet...

```<code>google.charts.load('current', {
  packages: ['corechart']
}).then(drawChart);

function drawChart() {
  var query = new google.visualization.Query(
    'URL'
  );
  query.setQuery('SELECT A, B OFFSET 0'); //select specific cells from the table
  query.send(handleQueryResponse);
}

function handleQueryResponse(response) {
  if (response.isError()) {
    alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
    return;
  }

  var data = response.getDataTable();
  var options = {
    title: '',
    height : 250,
    width : '100%',
  };

  // create data view with calculated annotation column
  var view = new google.visualization.DataView(data);
  view.setColumns([0, 1, {
    calc: 'stringify',
    sourceColumn: 1,
    type: 'string',
    role: 'annotation'
  }]);

  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
  chart.draw(view, options);  // <-- use view to draw the chart
}
</code>```

Note: when using google.visualization.LineChart, you only need the 'corechart' package.

the 'line' package is for their material line chart --> google.charts.Line

Body:
I'm creating a line chart by querying data entered into a Google Sheet, and I need to add data labels, i.e. the little numbers next to the points on the chart. I found plenty of documentation on how to do this with charts drawn from a manually entered data-table, but not from a query to a Google Sheet. Please help.

google.charts.load('current', {'packages':['corechart', 'line']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
var query = new google.visualization.Query(
  'URL'
);
query.setQuery('SELECT A, B OFFSET 0'); //select specific cells from the table
query.send(handleQueryResponse);
}

function handleQueryResponse(response) {
if (response.isError()) {
  alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
  return;
}

var data = response.getDataTable();
var options = {
  title: '',
  height : 250,
  width : '100%',

    }
 var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}

Body:
correct, you want to add annotations.

this can be done using an annotation column role.

the annotation column role, should directly follow the series column it represents in the data table.

in this case, since you are getting the data from a query,

we can use a DataView to add the annotation using a calculated column.

first, we create the data view.

  var view = new google.visualization.DataView(data);

then we use the setColumns method,

to add the column indexes from the query,

and our calculated column for the annotation.

  view.setColumns([0, 1, {
    calc: 'stringify',
    sourceColumn: 1,
    type: 'string',
    role: 'annotation'
  }]);

finally, we need to use the view to draw the chart.

chart.draw(view, options);

see following snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(drawChart);

function drawChart() {
  var query = new google.visualization.Query(
    'URL'
  );
  query.setQuery('SELECT A, B OFFSET 0'); //select specific cells from the table
  query.send(handleQueryResponse);
}

function handleQueryResponse(response) {
  if (response.isError()) {
    alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
    return;
  }

  var data = response.getDataTable();
  var options = {
    title: '',
    height : 250,
    width : '100%',
  };

  // create data view with calculated annotation column
  var view = new google.visualization.DataView(data);
  view.setColumns([0, 1, {
    calc: 'stringify',
    sourceColumn: 1,
    type: 'string',
    role: 'annotation'
  }]);

  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
  chart.draw(view, options);  // <-- use view to draw the chart
}

Note: when using google.visualization.LineChart, you only need the 'corechart' package.

the 'line' package is for their material line chart --> google.charts.Line


问:
Where does npm install packages on Windows? Node version 10.x
Can someone tell where can I find local npm modules installed using npm?
I am referring to NodeJS version 10

I do not see "npm" folder under C:\Users\MyUser\AppData\Roaming

答:
When you install npm all of the NodeJS related dependencies are stored inside this directory

"C:\Program Files\nodejs\node_modules\npm\node_modules".


问:
Looking for a simpler Objective-C solution
Maybe simpler isn't the proper word; terse might do as well. I'm well-aware that Objective-C is a verbose language; I'm just wondering if it has to be as verbose as it is in the solution I'm showing below. I'm relatively new to the language.

This piece of code counts the number of each type of field in a record, pursuant to generating a  variable-height UITableViewCell containing one label per field. My question isn't about how to do this -- I've already figured that out -- I'm just wondering: isn't there a simpler or less verbose way of doing this in Objective-C, using an NSDictionary object? Is this as terse as it gets using an NSDictionary? Solutions using other collection-type objects are also welcome.

Here's my -PartsRecord.countFields method. I've simplified the code slightly.

```<code>-(NSDictionary*) countFields {
NSDictionary* dict = [[NSDictionary alloc] initWithObjectAndKeys:
     @"s", [NSNumber numberWithUnsignedInt: [self.struts count]],
     @"h", [NSNumber numberWithUnsignedInt: [self.headAssemblies count]],
     @"l", (self.leftVent == nil) ?   [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     @"r", (self.rightVent == nil) ?  [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     nil ];
return dict;
</code>```

}

Any errors in the above code are errors in transcription , not actual errors in the code.

TIA,

Howard

答:
Unless you're intending to key on the numbers, your object ordering is wrong. It should be object then key.

```<code>dict = [NSDictionary dictionaryWithObjectsAndKeys:
   [NSNumber numberWithUnsignedInt: [self.struts count]], @"s",
   [NSNumber numberWithUnsignedInt: [self.headAssemblies count]], @"h",
   [NSNumber numberWithUnsignedInt: self.leftVent  ? 1 : 0], @"l",
   [NSNumber numberWithUnsignedInt: self.rightVent ? 1 : 0], @"r",
   nil ];
</code>```

This way, calling [dict objectForKey:@"s"] would return the [self.struts count] number object.

ContentLicense: CC BY-SA 2.5

Body:
Maybe simpler isn't the proper word; terse might do as well. I'm well-aware that Objective-C is a verbose language; I'm just wondering if it has to be as verbose as it is in the solution I'm showing below. I'm relatively new to the language.

This piece of code counts the number of each type of field in a record, pursuant to generating a  variable-height UITableViewCell containing one label per field. My question isn't about how to do this -- I've already figured that out -- I'm just wondering: isn't there a simpler or less verbose way of doing this in Objective-C, using an NSDictionary object? Is this as terse as it gets using an NSDictionary? Solutions using other collection-type objects are also welcome.

Here's my -PartsRecord.countFields method. I've simplified the code slightly.

-(NSDictionary*) countFields {
NSDictionary* dict = [[NSDictionary alloc] initWithObjectAndKeys:
     @"s", [NSNumber numberWithUnsignedInt: [self.struts count]],
     @"h", [NSNumber numberWithUnsignedInt: [self.headAssemblies count]],
     @"l", (self.leftVent == nil) ?   [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     @"r", (self.rightVent == nil) ?  [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     nil ];
return dict;

}

Any errors in the above code are errors in transcription , not actual errors in the code.

TIA,

Howard

Body:
Unless you're intending to key on the numbers, your object ordering is wrong. It should be object then key.

dict = [NSDictionary dictionaryWithObjectsAndKeys:
   [NSNumber numberWithUnsignedInt: [self.struts count]], @"s",
   [NSNumber numberWithUnsignedInt: [self.headAssemblies count]], @"h",
   [NSNumber numberWithUnsignedInt: self.leftVent  ? 1 : 0], @"l",
   [NSNumber numberWithUnsignedInt: self.rightVent ? 1 : 0], @"r",
   nil ];

This way, calling [dict objectForKey:@"s"] would return the [self.struts count] number object.

OwnerDisplayName: Ashley Clark


问:
How to scroll Right on a button click.?
So I made a horizontal slider of some cards and i am able to make them scroll left on click of a button but how do I get a button, which on clicked scrolls right?

Hello

Hello

Hello

Hello

Hello

Hello

Hello

Hello

Hello

Hello

Hello

```

```const buttonleft = document.getElementById('scrollLeft');

buttonleft.onclick = function(){
       document.getElementById('content').scrollLeft +=100;
}
```

I have  #content with overflow-x: scroll and white-space: nowrap;

I want the Icon "chevron-left" for scrolling back (right).

答:
You should always use the id of the div element which element you want to scroll either in left or right on a button click.

HTML veiw

```<code><span  (click)="clicked()">scroll horizontal</span>
<ul type="none"id="content" >
</code>```

ts code

```<code>clicked() {
document.getElementById('content').scrollBy(30, 0); // for right scroll
document.getElementById('content').scrollBy(-30, 0); // for left scroll
}

</code>```

Title: How to scroll Right on a button click.?

Body:
So I made a horizontal slider of some cards and i am able to make them scroll left on click of a button but how do I get a button, which on clicked scrolls right?

Hello

Hello

Hello

Hello

Hello

Hello

Hello

Hello

Hello

Hello

Hello

const buttonleft = document.getElementById('scrollLeft');

buttonleft.onclick = function(){
       document.getElementById('content').scrollLeft +=100;
}

I have  #content with overflow-x: scroll and white-space: nowrap;

I want the Icon "chevron-left" for scrolling back (right).

Body:
You should always use the id of the div element which element you want to scroll either in left or right on a button click.

HTML veiw

<span  (click)="clicked()">scroll horizontal</span>
<ul type="none"id="content" >

ts code

clicked() {
document.getElementById('content').scrollBy(30, 0); // for right scroll
document.getElementById('content').scrollBy(-30, 0); // for left scroll
}


问:
In VBA, how to extract the string before a number from the text
From ActiveWorkbook.name, I would like to extract the strings that are before (left side of ) the numbers. Since I want to use the same code in multiple workbooks, the file names would be variable, but every file name has date info in the middle  (yyyymmdd).

In case of excel file, I can use the below formula, but can I apply the same kind of method in VBA?

```<code>=LEFT(A1,MIN(FIND({0,1,2,3,4,5,6,7,8,9},ASC(A1)&1234567890))-1)
</code>```

Example: MyExcelWorkbook_Management_20200602_MyName.xlsm

In above case, I want to extract "MyExcelWorkbook_Management_".

答:
So basically you want to use the Midfunction to look for the first numerical character in your input string, and then cut your input string to that position.
That means we need to loop through the string from left to right, look at one character at a time and see if it is a digit or not.
This code does exactly that:

```<code>Option Explicit

Sub extratLeftText()

Dim someString As String
Dim result As String
someString = "Hello World1234"

Dim i As Long
Dim c As String 'one character of your string

For i = 1 To Len(someString)
    c = Mid(someString, i, 1)
    If IsNumeric(c) = True Then 'should write  "If IsNumeric(c) = True AND i>1 Then" to avoid an "out of bounds" error
        result = Left(someString, i - 1)
        Exit For
    End If
Next i

MsgBox result
End Sub
</code>```

Last thing you need to do is to load in some workbook name into your VBA function. Generally this is done with the .Name method of the workbookobject:

```<code>Sub workbookName()

Dim wb As Workbook
Set wb = ActiveWorkbook

MsgBox wb.Name

End Sub
</code>```

Of course you would need to find some way to replace the Set wb = ActiveWorkbook line with code that suits your purpose.

Body:
From ActiveWorkbook.name, I would like to extract the strings that are before (left side of ) the numbers. Since I want to use the same code in multiple workbooks, the file names would be variable, but every file name has date info in the middle  (yyyymmdd).

In case of excel file, I can use the below formula, but can I apply the same kind of method in VBA?

=LEFT(A1,MIN(FIND({0,1,2,3,4,5,6,7,8,9},ASC(A1)&1234567890))-1)

Example: MyExcelWorkbook_Management_20200602_MyName.xlsm

In above case, I want to extract "MyExcelWorkbook_Management_".

Body:
So basically you want to use the Midfunction to look for the first numerical character in your input string, and then cut your input string to that position.
That means we need to loop through the string from left to right, look at one character at a time and see if it is a digit or not.
This code does exactly that:

Option Explicit

Sub extratLeftText()

Dim someString As String
Dim result As String
someString = "Hello World1234"

Dim i As Long
Dim c As String 'one character of your string

For i = 1 To Len(someString)
    c = Mid(someString, i, 1)
    If IsNumeric(c) = True Then 'should write  "If IsNumeric(c) = True AND i>1 Then" to avoid an "out of bounds" error
        result = Left(someString, i - 1)
        Exit For
    End If
Next i

MsgBox result
End Sub

Last thing you need to do is to load in some workbook name into your VBA function. Generally this is done with the .Name method of the workbookobject:

Sub workbookName()

Dim wb As Workbook
Set wb = ActiveWorkbook

MsgBox wb.Name

End Sub

Of course you would need to find some way to replace the Set wb = ActiveWorkbook line with code that suits your purpose.