问:
Loading video and image from local storage into Google ChromeCast android
How to set local video URI/Path/File to MediaInfo.Builder() of chromecast ? Also, anyone could please help me with a code snippet on how to load image and video locally from android storage and cast it to the google chrome cast ?
Read other questions too but over there it has been mentioned to create a local server on app. If really we need to do this then how to implement this ? I am using code available on https://github.com/googlecast/CastVideos-android but over there video is fetched and played from url. I want to load video from local storage also i want to show images also.

Updated:
Now I have a created a local server using "NanoHttpD" but is unable to get the url of selected local file. Below is my Acitivities code snippet:

```<code>public class VideoBrowserFragment extends Fragment implements VideoListAdapter.ItemClickListener,
        LoaderManager.LoaderCallbacks<List<MediaInfo>> {

    private static final String TAG = "zz VideoBrowserFragment";
    private static final int REQUEST_TAKE_GALLERY_VIDEO = 123;
    private static final String CATALOG_URL =
            "http://commondatastorage.googleapis.com/gtv-videos-bucket/CastVideos/f.json";
    private RecyclerView mRecyclerView;
    private VideoListAdapter mAdapter;
    private View mEmptyView;
    private View mLoadingView;
    private VideoCastManager mCastManager;
    private VideoCastConsumerImpl mCastConsumer;
    private View btnLocalVideo;
    LocalServer server;
    String chosenExt = "";
    String localFileName = "";
    String localFilePath = "";
    String formatedIpAddress = "";
    Uri selectedImageUri;

    public VideoBrowserFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        Toast.makeText(getActivity(), "VideoBrowserFragment onCreateView", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "VideoBrowserFragment onCreateView");
        return inflater.inflate(R.layout.video_browser_fragment, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Toast.makeText(getActivity(), "VideoBrowserFragment onViewCreated", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "VideoBrowserFragment onViewCreated");

        mRecyclerView = (RecyclerView) getView().findViewById(R.id.list);
        mEmptyView = getView().findViewById(R.id.empty_view);
        mLoadingView = getView().findViewById(R.id.progress_indicator);
        btnLocalVideo = getView().findViewById(R.id.btnLocalVideo);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new VideoListAdapter(this);
        mRecyclerView.setAdapter(mAdapter);
        getLoaderManager().initLoader(0, null, this);
        mCastManager = VideoCastManager.getInstance();
        mCastConsumer = new VideoCastConsumerImpl() {
            @Override
            public void onConnected() {
                super.onConnected();
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onDisconnected() {
                super.onDisconnected();
                mAdapter.notifyDataSetChanged();
            }
        };
        mCastManager.addVideoCastConsumer(mCastConsumer);

//fetch local video
        btnLocalVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent();
                intent.setType("video/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Video"), REQUEST_TAKE_GALLERY_VIDEO);

            }
        });
    }

    //get data of locally fetched videos....
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == REQUEST_TAKE_GALLERY_VIDEO) {
                 selectedImageUri = data.getData();

                Toast.makeText(getActivity(), "Sending local video data", Toast.LENGTH_SHORT).show();
                MediaMetadata movieMetadata = new MediaMetadata(MediaMetadata.MEDIA_TYPE_MOVIE);

                movieMetadata.putString(MediaMetadata.KEY_SUBTITLE, "Local Subtitle");
                movieMetadata.putString(MediaMetadata.KEY_TITLE, "Local Video is playing");

                JSONObject jsonObj = null;
                try {
                    jsonObj = new JSONObject();
                    jsonObj.put("description", "Sample Descrioption over here");
                } catch (JSONException e) {
                    Log.e(TAG, "Failed to add description to the json object", e);
                }
                String filePath = getPath(selectedImageUri);
                chosenExt = filePath.substring(filePath.lastIndexOf(".") + 1);
                startLocalServer();
                String localUrl = formatedIpAddress + localFilePath;
                Log.d(TAG, "MediaInfo urlLocal: " + localUrl);
                MediaInfo item = new MediaInfo.Builder(localUrl)
                        .setStreamType(MediaInfo.STREAM_TYPE_BUFFERED)
                        .setContentType("video/mp4")
                        .setMetadata(movieMetadata)
                        .setStreamDuration(333 * 1000)
                        .build();
                Log.d(TAG, "VideoBrowserFragment itemClicked media :" + Utils.mediaInfoToBundle(item));

                Intent intent = new Intent(getActivity(), LocalPlayerActivity.class);
                intent.putExtra("media", Utils.mediaInfoToBundle(item));
                intent.putExtra("shouldStart", false);
                intent.putExtra("isLocal", true);
                intent.putExtra("videoUri", selectedImageUri.toString());
               /* Pair<View, String> imagePair = Pair
                        .create((View) viewHolder.getImageView(), transitionName);*/
                ActivityOptionsCompat options = ActivityOptionsCompat
                        .makeSceneTransitionAnimation(getActivity());
                ActivityCompat.startActivity(getActivity(), intent, options.toBundle());

            }
        }
    }

    //get path of video fetched...
    public String getPath(Uri uri) {
        Log.d(TAG, "uri is " + uri);
        String[] proj = {MediaStore.Images.Media.DATA};
        CursorLoader loader = new CursorLoader(getActivity(), uri, proj, null, null, null);
        Cursor cursor = loader.loadInBackground();
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();

        if (cursor.moveToFirst()) {
            //int column_index1 = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);//Instead of "MediaStore.Images.Media.DATA" can be used "_data"
            Uri filePathUri = Uri.parse(cursor.getString(column_index));
            String file_name = filePathUri.getLastPathSegment().toString();
            String file_path = filePathUri.getPath();
            localFileName = file_name;
            localFilePath = file_path;
            Toast.makeText(getActivity(), "File Name & PATH are:" + file_name + "\n" + file_path, Toast.LENGTH_LONG).show();
            Log.d("zz fileData: ", "fp: " + file_path + " :and: fn: " + file_name);
        }
        String result = cursor.getString(column_index);
        cursor.close();
        return result;
    }

    @Override
    public void onDetach() {
        Toast.makeText(getActivity(), "VideoBrowserFragment onDetach", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "VideoBrowserFragment onDetach");
        mCastManager.removeVideoCastConsumer(mCastConsumer);
        super.onDetach();
    }

    @Override
    public void itemClicked(View view, MediaInfo item, int position) {
        Toast.makeText(getActivity(), "VideoBrowserFragment itemClicked", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "VideoBrowserFragment itemClicked");

        if (view instanceof ImageButton) {
            Log.d(TAG, "menu was clicked");
            com.scriptlanes.cast2.utils.Utils.showQueuePopup(getActivity(), view, item);
        } else {
            String transitionName = getString(R.string.transition_image);
            VideoListAdapter.ViewHolder viewHolder =
                    (VideoListAdapter.ViewHolder) mRecyclerView.findViewHolderForPosition(position);
            Pair<View, String> imagePair = Pair
                    .create((View) viewHolder.getImageView(), transitionName);
            ActivityOptionsCompat options = ActivityOptionsCompat
                    .makeSceneTransitionAnimation(getActivity(), imagePair);

            Intent intent = new Intent(getActivity(), LocalPlayerActivity.class);
            Log.d(TAG, "VideoBrowserFragment itemClicked media :" + Utils.mediaInfoToBundle(item));

            intent.putExtra("media", Utils.mediaInfoToBundle(item));
            intent.putExtra("shouldStart", false);
            //isUrl=true, isLocal=false
            intent.putExtra("isLocal", false);
            ActivityCompat.startActivity(getActivity(), intent, options.toBundle());
        }
    }

    @Override
    public Loader<List<MediaInfo>> onCreateLoader(int id, Bundle args) {
        Toast.makeText(getActivity(), "VideoBrowserFragment onCreateLoader", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "VideoBrowserFragment onCreateLoader");

        return new VideoItemLoader(getActivity(), CATALOG_URL);
    }

    @Override
    public void onLoadFinished(Loader<List<MediaInfo>> loader, List<MediaInfo> data) {
        Toast.makeText(getActivity(), "VideoBrowserFragment onLoadFinished", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "VideoBrowserFragment onLoadFinished");
        mAdapter.setData(data);
        mLoadingView.setVisibility(View.GONE);
        mEmptyView.setVisibility(null == data || data.isEmpty() ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onLoaderReset(Loader<List<MediaInfo>> loader) {
        Toast.makeText(getActivity(), "VideoBrowserFragment onLoaderReset", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "VideoBrowserFragment onLoaderReset");
        mAdapter.setData(null);
    }

    /*temp code nanohttpd*/

    public class LocalServer extends NanoHTTPD {

        private  final Logger LOG = Logger.getLogger(LocalServer.class.getName());

        public  void main(String[] args) {
            ServerRunner.run(LocalServer.class);
        }
        public LocalServer() {
            super(3000);
            Log.d("zz nanaHttpd: ", "STARTED");

        }

       @Override
        public Response serve(String uri, Method method, Map<String, String> header, Map<String, String> parameters, Map<String, String> files) {
            //String mediasend = getExtension(chosenFile);

           Log.d("zz nanaHttpd:  ", "uri:  " + uri+" , method: "+method);
           FileInputStream fis = null;
           File file = new File(localFilePath);
           Log.e("Creando imputStream", "Size: ");
           try {
               fis = new FileInputStream(file);
           } catch (FileNotFoundException e) {
               e.printStackTrace();
           }

            return new NanoHTTPD.Response(Response.Status.OK, "video/mp4", fis);
        }

    }

    private void startLocalServer() {
        server = new LocalServer();
        try {
            server.start();
        } catch (IOException ioe) {
            Log.d("zz Httpd", "The server could not start.");
        }
        Log.d("zz Httpd", "Web server initialized.");
        WifiManager wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
        int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
        Log.d("zz Httpd IP U: ", ipAddress + "");
        String formatedIpAddress1 = String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff),
                (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
        formatedIpAddress = "http://" + formatedIpAddress1 + ":" + server.getListeningPort();
        Log.d("zz Httpd IP: ", "Please access! " + formatedIpAddress);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //server.stop();
    }
}
</code>```

答:
Your are doing it right, Just put the selected url like this:</p>
```<code>mediaMetadata.addImage(new WebImage(Uri.parse(http://192.168.0.XX:8080/video.mp4));
</code>```

Body:
How to set local video URI/Path/File to MediaInfo.Builder() of chromecast ? Also, anyone could please help me with a code snippet on how to load image and video locally from android storage and cast it to the google chrome cast ?
Read other questions too but over there it has been mentioned to create a local server on app. If really we need to do this then how to implement this ? I am using code available on https://github.com/googlecast/CastVideos-android but over there video is fetched and played from url. I want to load video from local storage also i want to show images also.

Updated:
Now I have a created a local server using "NanoHttpD" but is unable to get the url of selected local file. Below is my Acitivities code snippet:

public class VideoBrowserFragment extends Fragment implements VideoListAdapter.ItemClickListener,
        LoaderManager.LoaderCallbacks<List<MediaInfo>> {

    private static final String TAG = "zz VideoBrowserFragment";
    private static final int REQUEST_TAKE_GALLERY_VIDEO = 123;
    private static final String CATALOG_URL =
            "http://commondatastorage.googleapis.com/gtv-videos-bucket/CastVideos/f.json";
    private RecyclerView mRecyclerView;
    private VideoListAdapter mAdapter;
    private View mEmptyView;
    private View mLoadingView;
    private VideoCastManager mCastManager;
    private VideoCastConsumerImpl mCastConsumer;
    private View btnLocalVideo;
    LocalServer server;
    String chosenExt = "";
    String localFileName = "";
    String localFilePath = "";
    String formatedIpAddress = "";
    Uri selectedImageUri;

    public VideoBrowserFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        Toast.makeText(getActivity(), "VideoBrowserFragment onCreateView", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "VideoBrowserFragment onCreateView");
        return inflater.inflate(R.layout.video_browser_fragment, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Toast.makeText(getActivity(), "VideoBrowserFragment onViewCreated", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "VideoBrowserFragment onViewCreated");

        mRecyclerView = (RecyclerView) getView().findViewById(R.id.list);
        mEmptyView = getView().findViewById(R.id.empty_view);
        mLoadingView = getView().findViewById(R.id.progress_indicator);
        btnLocalVideo = getView().findViewById(R.id.btnLocalVideo);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new VideoListAdapter(this);
        mRecyclerView.setAdapter(mAdapter);
        getLoaderManager().initLoader(0, null, this);
        mCastManager = VideoCastManager.getInstance();
        mCastConsumer = new VideoCastConsumerImpl() {
            @Override
            public void onConnected() {
                super.onConnected();
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onDisconnected() {
                super.onDisconnected();
                mAdapter.notifyDataSetChanged();
            }
        };
        mCastManager.addVideoCastConsumer(mCastConsumer);

//fetch local video
        btnLocalVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent();
                intent.setType("video/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Video"), REQUEST_TAKE_GALLERY_VIDEO);

            }
        });
    }

    //get data of locally fetched videos....
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == REQUEST_TAKE_GALLERY_VIDEO) {
                 selectedImageUri = data.getData();

                Toast.makeText(getActivity(), "Sending local video data", Toast.LENGTH_SHORT).show();
                MediaMetadata movieMetadata = new MediaMetadata(MediaMetadata.MEDIA_TYPE_MOVIE);

                movieMetadata.putString(MediaMetadata.KEY_SUBTITLE, "Local Subtitle");
                movieMetadata.putString(MediaMetadata.KEY_TITLE, "Local Video is playing");

                JSONObject jsonObj = null;
                try {
                    jsonObj = new JSONObject();
                    jsonObj.put("description", "Sample Descrioption over here");
                } catch (JSONException e) {
                    Log.e(TAG, "Failed to add description to the json object", e);
                }
                String filePath = getPath(selectedImageUri);
                chosenExt = filePath.substring(filePath.lastIndexOf(".") + 1);
                startLocalServer();
                String localUrl = formatedIpAddress + localFilePath;
                Log.d(TAG, "MediaInfo urlLocal: " + localUrl);
                MediaInfo item = new MediaInfo.Builder(localUrl)
                        .setStreamType(MediaInfo.STREAM_TYPE_BUFFERED)
                        .setContentType("video/mp4")
                        .setMetadata(movieMetadata)
                        .setStreamDuration(333 * 1000)
                        .build();
                Log.d(TAG, "VideoBrowserFragment itemClicked media :" + Utils.mediaInfoToBundle(item));

                Intent intent = new Intent(getActivity(), LocalPlayerActivity.class);
                intent.putExtra("media", Utils.mediaInfoToBundle(item));
                intent.putExtra("shouldStart", false);
                intent.putExtra("isLocal", true);
                intent.putExtra("videoUri", selectedImageUri.toString());
               /* Pair<View, String> imagePair = Pair
                        .create((View) viewHolder.getImageView(), transitionName);*/
                ActivityOptionsCompat options = ActivityOptionsCompat
                        .makeSceneTransitionAnimation(getActivity());
                ActivityCompat.startActivity(getActivity(), intent, options.toBundle());

            }
        }
    }

    //get path of video fetched...
    public String getPath(Uri uri) {
        Log.d(TAG, "uri is " + uri);
        String[] proj = {MediaStore.Images.Media.DATA};
        CursorLoader loader = new CursorLoader(getActivity(), uri, proj, null, null, null);
        Cursor cursor = loader.loadInBackground();
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();

        if (cursor.moveToFirst()) {
            //int column_index1 = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);//Instead of "MediaStore.Images.Media.DATA" can be used "_data"
            Uri filePathUri = Uri.parse(cursor.getString(column_index));
            String file_name = filePathUri.getLastPathSegment().toString();
            String file_path = filePathUri.getPath();
            localFileName = file_name;
            localFilePath = file_path;
            Toast.makeText(getActivity(), "File Name & PATH are:" + file_name + "\n" + file_path, Toast.LENGTH_LONG).show();
            Log.d("zz fileData: ", "fp: " + file_path + " :and: fn: " + file_name);
        }
        String result = cursor.getString(column_index);
        cursor.close();
        return result;
    }

    @Override
    public void onDetach() {
        Toast.makeText(getActivity(), "VideoBrowserFragment onDetach", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "VideoBrowserFragment onDetach");
        mCastManager.removeVideoCastConsumer(mCastConsumer);
        super.onDetach();
    }

    @Override
    public void itemClicked(View view, MediaInfo item, int position) {
        Toast.makeText(getActivity(), "VideoBrowserFragment itemClicked", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "VideoBrowserFragment itemClicked");

        if (view instanceof ImageButton) {
            Log.d(TAG, "menu was clicked");
            com.scriptlanes.cast2.utils.Utils.showQueuePopup(getActivity(), view, item);
        } else {
            String transitionName = getString(R.string.transition_image);
            VideoListAdapter.ViewHolder viewHolder =
                    (VideoListAdapter.ViewHolder) mRecyclerView.findViewHolderForPosition(position);
            Pair<View, String> imagePair = Pair
                    .create((View) viewHolder.getImageView(), transitionName);
            ActivityOptionsCompat options = ActivityOptionsCompat
                    .makeSceneTransitionAnimation(getActivity(), imagePair);

            Intent intent = new Intent(getActivity(), LocalPlayerActivity.class);
            Log.d(TAG, "VideoBrowserFragment itemClicked media :" + Utils.mediaInfoToBundle(item));

            intent.putExtra("media", Utils.mediaInfoToBundle(item));
            intent.putExtra("shouldStart", false);
            //isUrl=true, isLocal=false
            intent.putExtra("isLocal", false);
            ActivityCompat.startActivity(getActivity(), intent, options.toBundle());
        }
    }

    @Override
    public Loader<List<MediaInfo>> onCreateLoader(int id, Bundle args) {
        Toast.makeText(getActivity(), "VideoBrowserFragment onCreateLoader", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "VideoBrowserFragment onCreateLoader");

        return new VideoItemLoader(getActivity(), CATALOG_URL);
    }

    @Override
    public void onLoadFinished(Loader<List<MediaInfo>> loader, List<MediaInfo> data) {
        Toast.makeText(getActivity(), "VideoBrowserFragment onLoadFinished", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "VideoBrowserFragment onLoadFinished");
        mAdapter.setData(data);
        mLoadingView.setVisibility(View.GONE);
        mEmptyView.setVisibility(null == data || data.isEmpty() ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onLoaderReset(Loader<List<MediaInfo>> loader) {
        Toast.makeText(getActivity(), "VideoBrowserFragment onLoaderReset", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "VideoBrowserFragment onLoaderReset");
        mAdapter.setData(null);
    }

    /*temp code nanohttpd*/

    public class LocalServer extends NanoHTTPD {

        private  final Logger LOG = Logger.getLogger(LocalServer.class.getName());

        public  void main(String[] args) {
            ServerRunner.run(LocalServer.class);
        }
        public LocalServer() {
            super(3000);
            Log.d("zz nanaHttpd: ", "STARTED");

        }

       @Override
        public Response serve(String uri, Method method, Map<String, String> header, Map<String, String> parameters, Map<String, String> files) {
            //String mediasend = getExtension(chosenFile);

           Log.d("zz nanaHttpd:  ", "uri:  " + uri+" , method: "+method);
           FileInputStream fis = null;
           File file = new File(localFilePath);
           Log.e("Creando imputStream", "Size: ");
           try {
               fis = new FileInputStream(file);
           } catch (FileNotFoundException e) {
               e.printStackTrace();
           }

            return new NanoHTTPD.Response(Response.Status.OK, "video/mp4", fis);
        }

    }

    private void startLocalServer() {
        server = new LocalServer();
        try {
            server.start();
        } catch (IOException ioe) {
            Log.d("zz Httpd", "The server could not start.");
        }
        Log.d("zz Httpd", "Web server initialized.");
        WifiManager wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
        int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
        Log.d("zz Httpd IP U: ", ipAddress + "");
        String formatedIpAddress1 = String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff),
                (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
        formatedIpAddress = "http://" + formatedIpAddress1 + ":" + server.getListeningPort();
        Log.d("zz Httpd IP: ", "Please access! " + formatedIpAddress);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //server.stop();
    }
}

Body:
Your are doing it right, Just put the selected url like this:

mediaMetadata.addImage(new WebImage(Uri.parse(http://192.168.0.XX:8080/video.mp4));


来源: stackexchange

问:
Qt Designer: How to lock window size?
So Qt Designer has this feature where you can resize the window you're working on. And that's fine and dandy, but every now and then, I accidentally drag it, and the window gets larger or smaller than I wanted it to be. The undo action doesn't undo the resizing, so that's a bummer. Also setting max and min sizes for the central widget doesn't do anything to fix this issue.

Is there a way I can have the window size locked?

Here's a demo:

答: Use QWidget::setFixedSize(w, h) for explicitly set width and height or QLayout::setSizeConstraint(QLayout::SetFixedSize) if you want the fixed size to be determined automatically based on content.

ContentLicense: CC BY-SA 4.0

Title: Qt Designer: How to lock window size?


问:
"Forbidden You don't have permission to access this resource." on phpMyAdmin in Mac Os
I tried to install phpMyadmin in MacOs. But When I go to localhost/phpmyadmin it says Forbidden You don't have permission to access this resource. My phpMyAdmin folder is in
/usr/local folder in Finder. I configured the phpmyadmin.conf file with sudo nano /etc/apache2/other/phpmyadmin.conf with the following codes:

```<code><Directory /usr/local/phpmyadmin>
        Options Indexes
        Order allow,deny
        Allow from all
        allow from 127.0.0.1
        allow from 192.168.1.0/15
</Directory>
</code>```

What should I do to get rid of this error?

答: Find file httpd-xammp.conf, change 'Require local' to 'Require all granted', save file and restart apache

Body:
I tried to install phpMyadmin in MacOs. But When I go to localhost/phpmyadmin it says Forbidden You don't have permission to access this resource. My phpMyAdmin folder is in
/usr/local folder in Finder. I configured the phpmyadmin.conf file with sudo nano /etc/apache2/other/phpmyadmin.conf with the following codes:

<Directory /usr/local/phpmyadmin>
        Options Indexes
        Order allow,deny
        Allow from all
        allow from 127.0.0.1
        allow from 192.168.1.0/15
</Directory>

What should I do to get rid of this error?


问:
Laravel Eloquent - bulk update with whereIn array
I'm working on a project where I need to update many rows at once per coin Id.

in order to update all coins values, Im getting them all from the API, so for example I have back:

```<code>    $coinsList= [[id="bitcoin", symbol="btc", name="Bintcoin"],[id="etherium", symbol="eth", name="Etherium"]];
</code>```

and the database table columns is the following:

```<code>**| id | coin_id | symbol | name |**
</code>```

now, I want to update all values to the database, according to the id only, so this is what I did:

```<code>    // first get ids from my table
    $exist_ids = Coinlist::all('coin_id')->pluck('coin_id')->toArray();

    //get all ids to update (to ignore other ids):
    $updatable_ids = array_values(array_intersect($exist_ids, $allCoinIds));//result for example is: array("bitcoin","etherium");

//and now, update the database:
    Coinlist::whereIn('coin_id', $updatable_ids)
                ->update([
                    'symbol' => $coinsList[$key]['symbol'],
                    'name' => $coinsList[$key]['name'],
                    'updated_at' => now()
                ]);
</code>```

the problem is, I don't have the "$key" in order to update the right row, what am I missing here?

Thanks!

答:
Here is a good way to solve it:
in the beginning, I used this library: https://github.com/mavinoo/laravelBatch
to update many dynamic rows, but it was really slow, then thanks to Yasin, I moved to: https://github.com/iksaku/laravel-mass-update and now it works way better.

the implementation is simple, add a simple code to the Model class, then add:

```<code>User::massUpdate(
    values: [
        ['username' => 'iksaku', 'name' => 'Jorge González'],
        ['username' => 'gm_mtz', 'name' => 'Gladys Martínez'],
    ],
    uniqueBy: 'username'
);
</code>```

while uniqueBy is the key for the row, and add other columns values to change them dynamically.

Body:
I'm working on a project where I need to update many rows at once per coin Id.

in order to update all coins values, Im getting them all from the API, so for example I have back:

    $coinsList= [[id="bitcoin", symbol="btc", name="Bintcoin"],[id="etherium", symbol="eth", name="Etherium"]];

and the database table columns is the following:

**| id | coin_id | symbol | name |**

now, I want to update all values to the database, according to the id only, so this is what I did:

    // first get ids from my table
    $exist_ids = Coinlist::all('coin_id')->pluck('coin_id')->toArray();

    //get all ids to update (to ignore other ids):
    $updatable_ids = array_values(array_intersect($exist_ids, $allCoinIds));//result for example is: array("bitcoin","etherium");

//and now, update the database:
    Coinlist::whereIn('coin_id', $updatable_ids)
                ->update([
                    'symbol' => $coinsList[$key]['symbol'],
                    'name' => $coinsList[$key]['name'],
                    'updated_at' => now()
                ]);

the problem is, I don't have the "$key" in order to update the right row, what am I missing here?

Thanks!

Body:
Here is a good way to solve it:
in the beginning, I used this library: https://github.com/mavinoo/laravelBatch
to update many dynamic rows, but it was really slow, then thanks to Yasin, I moved to: https://github.com/iksaku/laravel-mass-update and now it works way better.

the implementation is simple, add a simple code to the Model class, then add:

User::massUpdate(
    values: [
        ['username' => 'iksaku', 'name' => 'Jorge González'],
        ['username' => 'gm_mtz', 'name' => 'Gladys Martínez'],
    ],
    uniqueBy: 'username'
);

while uniqueBy is the key for the row, and add other columns values to change them dynamically.


问:
Google Sheets api. Add values to empty cells in named range
I have 3 values that I have generated in array, that I want to append to a named range in the empty cells, at the beginning of the named range. I want it to fill in those empty cells, not add the values at the end of the range, which it is doing now. Here is an example of the code. The Named range is called BSNID. Screenshots included as well. Thank you.

```<code>const pushDataUpdates = async (inData, pushRange) => {
    return new Promise((resolve, reject) => {
        sheets.spreadsheets.values.append({
            spreadsheetId,
            range: pushRange,
            valueInputOption: 'RAW',
            insertDataOption: 'OVERWRITE',
            includeValuesInResponse: true,
            resource: {
                majorDimension: 'COLUMNS',
                values: [inData]
            }
        }, (err,res) => {
            if (err) {
                reject(err)
            } else {
                console.log('Updating idList')
                //console.log(res);
                resolve();
            }
        })
    })
}
pushDataUpdates([1,2,3], 'BSNID')
</code>```

Named Range

Column with empty cells at beginning

答:
I believe your goal is as follows.

You want to add [1,2,3] from the top cell in the named range of "BSNID" using googleapis for Node.js.

You have already been able to get and put values for Google Spreadsheet using Sheets API.

In this case, how about the following modification?

Modified script:

From:

```<code>sheets.spreadsheets.values.append({
    spreadsheetId,
    range: pushRange,
    valueInputOption: 'RAW',
    insertDataOption: 'OVERWRITE',
    includeValuesInResponse: true,
    resource: {
        majorDimension: 'COLUMNS',
        values: [inData]
    }
}, (err,res) => {
</code>```

To:

```<code>sheets.spreadsheets.values.update(
  {
    spreadsheetId,
    range: pushRange,
    valueInputOption: "RAW",
    resource: {
      majorDimension: "COLUMNS",
      values: [inData],
    },
  }, (err, res) => {
</code>```

By this modification, when your sample image is used, the values of [1,2,3] are put to the top 3 cells, respectively.

Reference:

Method: spreadsheets.values.update

Body:
I have 3 values that I have generated in array, that I want to append to a named range in the empty cells, at the beginning of the named range. I want it to fill in those empty cells, not add the values at the end of the range, which it is doing now. Here is an example of the code. The Named range is called BSNID. Screenshots included as well. Thank you.

const pushDataUpdates = async (inData, pushRange) => {
    return new Promise((resolve, reject) => {
        sheets.spreadsheets.values.append({
            spreadsheetId,
            range: pushRange,
            valueInputOption: 'RAW',
            insertDataOption: 'OVERWRITE',
            includeValuesInResponse: true,
            resource: {
                majorDimension: 'COLUMNS',
                values: [inData]
            }
        }, (err,res) => {
            if (err) {
                reject(err)
            } else {
                console.log('Updating idList')
                //console.log(res);
                resolve();
            }
        })
    })
}
pushDataUpdates([1,2,3], 'BSNID')

Named Range

Column with empty cells at beginning

Body:
I believe your goal is as follows.

You want to add [1,2,3] from the top cell in the named range of "BSNID" using googleapis for Node.js.

You have already been able to get and put values for Google Spreadsheet using Sheets API.

In this case, how about the following modification?

Modified script:

From:

sheets.spreadsheets.values.append({
    spreadsheetId,
    range: pushRange,
    valueInputOption: 'RAW',
    insertDataOption: 'OVERWRITE',
    includeValuesInResponse: true,
    resource: {
        majorDimension: 'COLUMNS',
        values: [inData]
    }
}, (err,res) => {

To:

sheets.spreadsheets.values.update(
  {
    spreadsheetId,
    range: pushRange,
    valueInputOption: "RAW",
    resource: {
      majorDimension: "COLUMNS",
      values: [inData],
    },
  }, (err, res) => {

By this modification, when your sample image is used, the values of [1,2,3] are put to the top 3 cells, respectively.

Reference:

Method: spreadsheets.values.update


问:
React: How to print object from state as a table?
I'm new in js and react. So I have solutionData object in state and when it gets data from axios it looks like this
data can be different everytime. i have a modal to show results and it looks like this:
here is my modal:

```<code><Modal isOpen={this.state.isOpen} toggle={this.toggleModal.bind(this.id)}>
                    <ModalHeader toggle={this.toggleModal.bind(this)}  className="btn-primary">Query result</ModalHeader>
                    <Table className="table">
                        <tbody>
                            <tr>
                                <th>Question:</th><td>{this.state.solutionData.title}</td>
                            </tr>
                            <tr>
                                <th>Solution:</th><td>{this.state.solutionData.solution}</td>
                            </tr>
                            <tr>
                                <th>data:</th><td>{this.state.solutionData.data}</td>
                            </tr>
                        </tbody>
                    </Table>
                    <ModalFooter>
                        <Button color="secondary" onClick={this.toggleModal.bind(this)}>Cancel</Button>
                    </ModalFooter>
                </Modal>
</code>```

here in modal i want data to be printed as table but i cant access e.x 'price' like this:

```<code>this.state.solutionData.data
</code>```

Ideally i want it to look like this:

So how can I access data in

solutionData.data

答:
data is an array of objects, so you have to use the map function to create a row in your table for each object in data :

```<code><Modal isOpen={this.state.isOpen} toggle={this.toggleModal.bind(this.id)}>
  <ModalHeader toggle={this.toggleModal.bind(this)} className="btn-primary">
    Query result
  </ModalHeader>
  <Table className="table">
    <tbody>
      <tr>
        <th>Question:</th>
        <td>{this.state.solutionData.title}</td>
      </tr>
      <tr>
        <th>Solution:</th>
        <td>{this.state.solutionData.solution}</td>
      </tr>
      <tr>
        <th>data:</th>
        <td>
          <Table>
            <thead>
              <tr>
                <th>Model</th>
                <th>Speed</th>
                <th>Hd</th>
              </tr>
            </thead>
            <tbody>
              {this.state.solutionData.data.map((d) => {
                return (
                  <tr>
                    <td>{d.model}</td>
                    <td>{d.speed}</td>
                    <td>{d.hd}</td>
                  </tr>
                );
              })}
            </tbody>
          </Table>
        </td>
      </tr>
    </tbody>
  </Table>
  <ModalFooter>
    <Button color="secondary" onClick={this.toggleModal.bind(this)}>
      Cancel
    </Button>
  </ModalFooter>
</Modal>;
</code>```

Body:
I'm new in js and react. So I have solutionData object in state and when it gets data from axios it looks like this
data can be different everytime. i have a modal to show results and it looks like this:
here is my modal:

<Modal isOpen={this.state.isOpen} toggle={this.toggleModal.bind(this.id)}>
                    <ModalHeader toggle={this.toggleModal.bind(this)}  className="btn-primary">Query result</ModalHeader>

                                Question:	{this.state.solutionData.title}

                                Solution:	{this.state.solutionData.solution}

                                data:	{this.state.solutionData.data}

                    <ModalFooter>
                        <Button color="secondary" onClick={this.toggleModal.bind(this)}>Cancel</Button>
                    </ModalFooter>
                </Modal>

here in modal i want data to be printed as table but i cant access e.x 'price' like this:

this.state.solutionData.data

Ideally i want it to look like this:

So how can I access data in

solutionData.data

Body:
data is an array of objects, so you have to use the map function to create a row in your table for each object in data :

<Modal isOpen={this.state.isOpen} toggle={this.toggleModal.bind(this.id)}>
  <ModalHeader toggle={this.toggleModal.bind(this)} className="btn-primary">
    Query result
  </ModalHeader>
  <Table className="table">
    <tbody>
      <tr>
        <th>Question:</th>
        <td>{this.state.solutionData.title}</td>
      </tr>
      <tr>
        <th>Solution:</th>
        <td>{this.state.solutionData.solution}</td>
      </tr>
      <tr>
        <th>data:</th>
        <td>
          <Table>
            <thead>
              <tr>
                <th>Model</th>
                <th>Speed</th>
                <th>Hd</th>
              </tr>
            </thead>
            <tbody>
              {this.state.solutionData.data.map((d) => {
                return (
                  <tr>
                    <td>{d.model}</td>
                    <td>{d.speed}</td>
                    <td>{d.hd}</td>
                  </tr>
                );
              })}
            </tbody>
          </Table>
        </td>
      </tr>
    </tbody>
  </Table>
  <ModalFooter>
    <Button color="secondary" onClick={this.toggleModal.bind(this)}>
      Cancel
    </Button>
  </ModalFooter>
</Modal>;


问:
How to add underscore before the text in textBox TextChange?
How should I put it into the program that it will add underscore before the text that is encoded in the textbox?

Kindly see the below code.

```<code>private void textBoxP1_TextChanged(object sender, EventArgs e)
{
    this.textBoxP1 = "_" + textBoxP1.Text;

}
</code>```

No error came out from this code but this does not automatically add the underscore before the text.

Thank you.

答:
You forgot the .Text:

```<code>this.textBoxP1.Text = "_" + this.textBoxP1.Text;
</code>```

If this actually is the changed handler for the text box as the naming suggests, you need a break condition. Otherwise, changing the text to have an underscore in front will trigger the change handler again... and again... and again...

As you only want a single underscore, you may want to check that and not add any underscores if your text already starts with one.

Body:
How should I put it into the program that it will add underscore before the text that is encoded in the textbox?

Kindly see the below code.

private void textBoxP1_TextChanged(object sender, EventArgs e)
{
    this.textBoxP1 = "_" + textBoxP1.Text;

}

No error came out from this code but this does not automatically add the underscore before the text.

Thank you.

Body:
You forgot the .Text:

this.textBoxP1.Text = "_" + this.textBoxP1.Text;

If this actually is the changed handler for the text box as the naming suggests, you need a break condition. Otherwise, changing the text to have an underscore in front will trigger the change handler again... and again... and again...

As you only want a single underscore, you may want to check that and not add any underscores if your text already starts with one.


问:
Unsatisfied dependency for com.google.firebase.inappmessaging.display.FirebaseInAppMessagingDisplay
In order to remove the PLAY INSTALL REFERRER API permission from my app, I've removed the com.google.firebase:firebase-core:17.2.2 dependency from Gradle, but at runtime, I get this error log:

```<code>  java.lang.RuntimeException: Unable to get provider com.google.firebase.provider.FirebaseInitProvider: com.google.firebase.components.MissingDependencyException: Unsatisfied dependency for component Component<[class com.google.firebase.inappmessaging.display.FirebaseInAppMessagingDisplay]>{2, type=0, deps=[Dependency{anInterface=class com.google.firebase.FirebaseApp, type=required, direct=true}, Dependency{anInterface=interface com.google.firebase.analytics.connector.AnalyticsConnector, type=required, direct=true}, Dependency{anInterface=class com.google.firebase.inappmessaging.FirebaseInAppMessaging, type=required, direct=true}]}: interface com.google.firebase.analytics.connector.AnalyticsConnector
        at android.app.ActivityThread.installProvider(ActivityThread.java:7209)
        at android.app.ActivityThread.installContentProviders(ActivityThread.java:6693)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6594)
        at android.app.ActivityThread.-wrap2(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:108)
        at android.os.Looper.loop(Looper.java:166)
        at android.app.ActivityThread.main(ActivityThread.java:7523)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
     Caused by: com.google.firebase.components.MissingDependencyException: Unsatisfied dependency for component Component<[class com.google.firebase.inappmessaging.display.FirebaseInAppMessagingDisplay]>{2, type=0, deps=[Dependency{anInterface=class com.google.firebase.FirebaseApp, type=required, direct=true}, Dependency{anInterface=interface com.google.firebase.analytics.connector.AnalyticsConnector, type=required, direct=true}, Dependency{anInterface=class com.google.firebase.inappmessaging.FirebaseInAppMessaging, type=required, direct=true}]}: interface com.google.firebase.analytics.connector.AnalyticsConnector
        at com.google.firebase.components.ComponentRuntime.validateDependencies(com.google.firebase:firebase-components@@16.0.0:170)
        at com.google.firebase.components.ComponentRuntime.processInstanceComponents(com.google.firebase:firebase-components@@16.0.0:89)
        at com.google.firebase.components.ComponentRuntime.<init>(com.google.firebase:firebase-components@@16.0.0:73)
        at com.google.firebase.FirebaseApp.<init>(com.google.firebase:firebase-common@@19.3.0:418)
        at com.google.firebase.FirebaseApp.initializeApp(com.google.firebase:firebase-common@@19.3.0:300)
        at com.google.firebase.FirebaseApp.initializeApp(com.google.firebase:firebase-common@@19.3.0:268)
        at com.google.firebase.FirebaseApp.initializeApp(com.google.firebase:firebase-common@@19.3.0:253)
        at com.google.firebase.provider.FirebaseInitProvider.onCreate(com.google.firebase:firebase-common@@19.3.0:51)
        at android.content.ContentProvider.attachInfo(ContentProvider.java:1921)
        at android.content.ContentProvider.attachInfo(ContentProvider.java:1896)
        at com.google.firebase.provider.FirebaseInitProvider.attachInfo(com.google.firebase:firebase-common@@19.3.0:45)
        at android.app.ActivityThread.installProvider(ActivityThread.java:7206)
        at android.app.ActivityThread.installContentProviders(ActivityThread.java:6693)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6594)
        at android.app.ActivityThread.-wrap2(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:108)
        at android.os.Looper.loop(Looper.java:166)
        at android.app.ActivityThread.main(ActivityThread.java:7523)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
</code>```

In my app I use firebase services for only the following reasons:

Push notification to the users

Write and read data from Firebase database

Display App message dialog (Inappmessaging-Display)

Gradle:

```<code>dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.exifinterface:exifinterface:1.1.0'
    implementation 'com.android.support:support-annotations:28.0.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.multidex:multidex:2.0.1'
    annotationProcessor 'androidx.annotation:annotation:1.1.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'cn.ezandroid:EZFilter:2.0.9'
    implementation 'jp.co.cyberagent.android:gpuimage:2.0.4'
    implementation 'com.daimajia.easing:library:2.1@aar'
    implementation 'com.daimajia.androidanimations:library:2.3@aar'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
    implementation 'com.github.bumptech.glide:glide:4.11.0'
    implementation 'com.github.jkwiecien:EasyImage:2.1.1'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    testImplementation 'junit:junit:4.13'
    implementation 'com.github.chrisbanes:PhotoView:2.3.0'
    implementation 'de.hdodenhof:circleimageview:3.0.2'
    implementation 'com.alexvasilkov:gesture-views:2.5.2'
    implementation('com.github.christophesmet:android_maskable_layout:v1.3.1') {
        exclude group: 'com.intellij', module: 'annotations'
    }
    implementation 'com.github.duanhong169:checkerboarddrawable:1.0.2'
    implementation 'com.github.AKiniyalocts:imgur-api:-SNAPSHOT'
    implementation 'com.mikhaellopez:circularimageview:4.1.1'
    implementation 'com.jaredrummler:material-spinner:1.3.1'
    implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.19'

    //implementation 'com.google.firebase:firebase-core:17.2.2'

    implementation 'com.google.firebase:firebase-database:19.2.0'
    implementation 'com.firebaseui:firebase-ui-database:5.0.0'
    implementation 'com.google.firebase:firebase-inappmessaging-display:19.0.3'
    implementation 'com.google.android.gms:play-services-vision:19.0.0'
    implementation 'com.google.android.gms:play-services-ads:18.3.0'
    implementation 'com.google.firebase:firebase-messaging:20.1.0'
    implementation 'org.apache.commons:commons-lang3:3.9'
    implementation 'org.apache.commons:commons-collections4:4.4'
    implementation 'com.github.nanchen2251:CompressHelper:1.0.5'
    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'uz.shift:colorpicker:0.5@aar'
    implementation 'dev.dworks.libs:volleyplus:0.1.4'
    implementation 'com.waynejo:androidndkgif:0.3.3'
    implementation 'com.yanzhenjie:mediascanner:1.0.3'
    implementation 'io.github.inflationx:viewpump:2.0.3'
    implementation 'io.github.inflationx:calligraphy3:3.1.1'
    implementation 'com.takwolf.android:aspectratio:0.3.0'
}
apply plugin: 'com.google.gms.google-services'
</code>```

Thank you for your help in advance

答:
Unpacking apk found less configuration：
add config worked for me.</p>
```<code><service android:directBootAware="true" android:exported="false" android:name="com.google.firebase.components.ComponentDiscoveryService">
        <meta-data android:name="com.google.firebase.components:com.google.firebase.messaging.FirebaseMessagingRegistrar" android:value="com.google.firebase.components.ComponentRegistrar"/>
        <meta-data android:name="com.google.firebase.components:com.google.firebase.analytics.connector.internal.AnalyticsConnectorRegistrar" android:value="com.google.firebase.components.ComponentRegistrar"/>
        <meta-data android:name="com.google.firebase.components:com.google.firebase.iid.Registrar" android:value="com.google.firebase.components.ComponentRegistrar"/>
        <meta-data android:name="com.google.firebase.components:com.google.firebase.datatransport.TransportRegistrar" android:value="com.google.firebase.components.ComponentRegistrar"/>
        <meta-data
            android:name="com.google.firebase.components:com.google.firebase.installations.FirebaseInstallationsRegistrar"
            android:value="com.google.firebase.components.ComponentRegistrar" />
    </service>
</code>```

Body:
In order to remove the PLAY INSTALL REFERRER API permission from my app, I've removed the com.google.firebase:firebase-core:17.2.2 dependency from Gradle, but at runtime, I get this error log:

  java.lang.RuntimeException: Unable to get provider com.google.firebase.provider.FirebaseInitProvider: com.google.firebase.components.MissingDependencyException: Unsatisfied dependency for component Component<[class com.google.firebase.inappmessaging.display.FirebaseInAppMessagingDisplay]>{2, type=0, deps=[Dependency{anInterface=class com.google.firebase.FirebaseApp, type=required, direct=true}, Dependency{anInterface=interface com.google.firebase.analytics.connector.AnalyticsConnector, type=required, direct=true}, Dependency{anInterface=class com.google.firebase.inappmessaging.FirebaseInAppMessaging, type=required, direct=true}]}: interface com.google.firebase.analytics.connector.AnalyticsConnector
        at android.app.ActivityThread.installProvider(ActivityThread.java:7209)
        at android.app.ActivityThread.installContentProviders(ActivityThread.java:6693)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6594)
        at android.app.ActivityThread.-wrap2(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:108)
        at android.os.Looper.loop(Looper.java:166)
        at android.app.ActivityThread.main(ActivityThread.java:7523)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
     Caused by: com.google.firebase.components.MissingDependencyException: Unsatisfied dependency for component Component<[class com.google.firebase.inappmessaging.display.FirebaseInAppMessagingDisplay]>{2, type=0, deps=[Dependency{anInterface=class com.google.firebase.FirebaseApp, type=required, direct=true}, Dependency{anInterface=interface com.google.firebase.analytics.connector.AnalyticsConnector, type=required, direct=true}, Dependency{anInterface=class com.google.firebase.inappmessaging.FirebaseInAppMessaging, type=required, direct=true}]}: interface com.google.firebase.analytics.connector.AnalyticsConnector
        at com.google.firebase.components.ComponentRuntime.validateDependencies(com.google.firebase:firebase-components@@16.0.0:170)
        at com.google.firebase.components.ComponentRuntime.processInstanceComponents(com.google.firebase:firebase-components@@16.0.0:89)
        at com.google.firebase.components.ComponentRuntime.<init>(com.google.firebase:firebase-components@@16.0.0:73)
        at com.google.firebase.FirebaseApp.<init>(com.google.firebase:firebase-common@@19.3.0:418)
        at com.google.firebase.FirebaseApp.initializeApp(com.google.firebase:firebase-common@@19.3.0:300)
        at com.google.firebase.FirebaseApp.initializeApp(com.google.firebase:firebase-common@@19.3.0:268)
        at com.google.firebase.FirebaseApp.initializeApp(com.google.firebase:firebase-common@@19.3.0:253)
        at com.google.firebase.provider.FirebaseInitProvider.onCreate(com.google.firebase:firebase-common@@19.3.0:51)
        at android.content.ContentProvider.attachInfo(ContentProvider.java:1921)
        at android.content.ContentProvider.attachInfo(ContentProvider.java:1896)
        at com.google.firebase.provider.FirebaseInitProvider.attachInfo(com.google.firebase:firebase-common@@19.3.0:45)
        at android.app.ActivityThread.installProvider(ActivityThread.java:7206)
        at android.app.ActivityThread.installContentProviders(ActivityThread.java:6693)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6594)
        at android.app.ActivityThread.-wrap2(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:108)
        at android.os.Looper.loop(Looper.java:166)
        at android.app.ActivityThread.main(ActivityThread.java:7523)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)

In my app I use firebase services for only the following reasons:

Push notification to the users

Write and read data from Firebase database

Display App message dialog (Inappmessaging-Display)

Gradle:

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.exifinterface:exifinterface:1.1.0'
    implementation 'com.android.support:support-annotations:28.0.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.multidex:multidex:2.0.1'
    annotationProcessor 'androidx.annotation:annotation:1.1.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'cn.ezandroid:EZFilter:2.0.9'
    implementation 'jp.co.cyberagent.android:gpuimage:2.0.4'
    implementation 'com.daimajia.easing:library:2.1@aar'
    implementation 'com.daimajia.androidanimations:library:2.3@aar'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
    implementation 'com.github.bumptech.glide:glide:4.11.0'
    implementation 'com.github.jkwiecien:EasyImage:2.1.1'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    testImplementation 'junit:junit:4.13'
    implementation 'com.github.chrisbanes:PhotoView:2.3.0'
    implementation 'de.hdodenhof:circleimageview:3.0.2'
    implementation 'com.alexvasilkov:gesture-views:2.5.2'
    implementation('com.github.christophesmet:android_maskable_layout:v1.3.1') {
        exclude group: 'com.intellij', module: 'annotations'
    }
    implementation 'com.github.duanhong169:checkerboarddrawable:1.0.2'
    implementation 'com.github.AKiniyalocts:imgur-api:-SNAPSHOT'
    implementation 'com.mikhaellopez:circularimageview:4.1.1'
    implementation 'com.jaredrummler:material-spinner:1.3.1'
    implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.19'

    //implementation 'com.google.firebase:firebase-core:17.2.2'

    implementation 'com.google.firebase:firebase-database:19.2.0'
    implementation 'com.firebaseui:firebase-ui-database:5.0.0'
    implementation 'com.google.firebase:firebase-inappmessaging-display:19.0.3'
    implementation 'com.google.android.gms:play-services-vision:19.0.0'
    implementation 'com.google.android.gms:play-services-ads:18.3.0'
    implementation 'com.google.firebase:firebase-messaging:20.1.0'
    implementation 'org.apache.commons:commons-lang3:3.9'
    implementation 'org.apache.commons:commons-collections4:4.4'
    implementation 'com.github.nanchen2251:CompressHelper:1.0.5'
    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'uz.shift:colorpicker:0.5@aar'
    implementation 'dev.dworks.libs:volleyplus:0.1.4'
    implementation 'com.waynejo:androidndkgif:0.3.3'
    implementation 'com.yanzhenjie:mediascanner:1.0.3'
    implementation 'io.github.inflationx:viewpump:2.0.3'
    implementation 'io.github.inflationx:calligraphy3:3.1.1'
    implementation 'com.takwolf.android:aspectratio:0.3.0'
}
apply plugin: 'com.google.gms.google-services'

Thank you for your help in advance

Body:
Unpacking apk found less configuration：
add config worked for me.

<service android:directBootAware="true" android:exported="false" android:name="com.google.firebase.components.ComponentDiscoveryService">
        <meta-data android:name="com.google.firebase.components:com.google.firebase.messaging.FirebaseMessagingRegistrar" android:value="com.google.firebase.components.ComponentRegistrar"/>
        <meta-data android:name="com.google.firebase.components:com.google.firebase.analytics.connector.internal.AnalyticsConnectorRegistrar" android:value="com.google.firebase.components.ComponentRegistrar"/>
        <meta-data android:name="com.google.firebase.components:com.google.firebase.iid.Registrar" android:value="com.google.firebase.components.ComponentRegistrar"/>
        <meta-data android:name="com.google.firebase.components:com.google.firebase.datatransport.TransportRegistrar" android:value="com.google.firebase.components.ComponentRegistrar"/>
        <meta-data
            android:name="com.google.firebase.components:com.google.firebase.installations.FirebaseInstallationsRegistrar"
            android:value="com.google.firebase.components.ComponentRegistrar" />
    </service>


问:
how to fetch local api in react.js
I'm a new one, I'm trying to fetch my own api on local,this what I do:
in "src/server.js"

```<code>const express = require("express");
const app = express();

app.get("/api", (request, response) => {
  response.sendFile("api.js", { root: __dirname });
});

app.listen(8000);
</code>```

then I use creat-react-app to create a react project, how can I call my api in App.js?
if my situation is not complete, please tell me.

Q1:with server.js, after I run "node server.js", I can can call this file in browser that means I have done an api, right?
Q2:how can I get value from my api.js in App.js without cors problem?

答:
Firstly you should add your request address into package.json file. For example if you want to send http request to https://localhost:5000/, you should add "proxy":"http://localhost:5000" line into your package.json file.

After adding this line, you can send http request without getting CORS error.

Also you can use fetch function to sending request and getting response from server side in your react code(App.js).

```<code>fetch('/api')
  .then((response) => response.json())
  .then((data) => console.log(data));
</code>```

Title: how to fetch local api in react.js

Body:
I'm a new one, I'm trying to fetch my own api on local,this what I do:
in "src/server.js"

const express = require("express");
const app = express();

app.get("/api", (request, response) => {
  response.sendFile("api.js", { root: __dirname });
});

app.listen(8000);

then I use creat-react-app to create a react project, how can I call my api in App.js?
if my situation is not complete, please tell me.

Q1:with server.js, after I run "node server.js", I can can call this file in browser that means I have done an api, right?
Q2:how can I get value from my api.js in App.js without cors problem?

Body:
Firstly you should add your request address into package.json file. For example if you want to send http request to https://localhost:5000/, you should add "proxy":"http://localhost:5000" line into your package.json file.

After adding this line, you can send http request without getting CORS error.

Also you can use fetch function to sending request and getting response from server side in your react code(App.js).

fetch('/api')
  .then((response) => response.json())
  .then((data) => console.log(data));


问:
How to add dependency to PNPM workspace?
I start using PNPM Workspaces, and I'm struggling in how to add dependencies to any specific workspace as I would do in yarn running:

```<code>yarn workspace <workspace_name> add <package_to_add>
</code>```

Or even running scripts for specific packages as I would do in yarn like:

```<code>yarn workspace <workspace_name> run <script>
</code>```

How is the PNPM community doing this? You really need to go to the workspace package.json file and add it manually?

Been a while searching for docs without success

Thanks!

答:
So I found an answer and is using the --filter option.

i.e.

# Using the exact package name
pnpm add <package_to_add> --filter <workspace_name>
# Or using a pattern
pnpm add <package_to_add> --filter <prefix>/*
```

Same for run, etc...

Body:
I start using PNPM Workspaces, and I'm struggling in how to add dependencies to any specific workspace as I would do in yarn running:

yarn workspace <workspace_name> add <package_to_add>

Or even running scripts for specific packages as I would do in yarn like:

yarn workspace <workspace_name> run

Body:
So I found an answer and is using the --filter option.

i.e.

# Using the exact package name
pnpm add <package_to_add> --filter <workspace_name>
# Or using a pattern
pnpm add <package_to_add> --filter <prefix>/*

Same for run, etc...


问:
C# Selenium Webdriver Exception | This version of ChromeDriver only supports Chrome version 85
MyChromeDriver

My Google Chrome version: 88.0.4324.150

I found some solutions but the don't worked for me.
I want to open Google Chrome throw the Selenium, but it don't work yet.

Error

System.InvalidOperationException
  HResult=0x80131509
  Message=session not created: This version of ChromeDriver only supports Chrome version 85 (SessionNotCreated)
  Source=WebDriver
  StackTrace:
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.StartSession(ICapabilities desiredCapabilities)
   at OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
   at OpenQA.Selenium.Chrome.ChromeDriver..ctor(ChromeDriverService service, ChromeOptions options, TimeSpan commandTimeout)
   at OpenQA.Selenium.Chrome.ChromeDriver..ctor(ChromeOptions options)
   at RSelenium.start_Browser() in C:\Users\ruper\source\repos\T\T\RSelenium.cs:line 30
   at T.Form1.btn_selenium_Click(Object sender, EventArgs e) in C:\Users\ruper\source\repos\T\T\Form1.cs:line 61
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at T.Program.Main() in C:\Users\ruper\source\repos\T\T\Program.cs:line 47

```
<p><strong>Code</strong></p>
```System.Environment.SetEnvironmentVariable("webdriver.chrome.driver", @"C:\Program Files\Google\Chrome\Application\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.AddArguments("start-maximized");
options.AddArguments("disable-infobars");
options.AddArguments("--disable-extensions");
options.AddArguments("--disable-gpu");
options.AddArguments("--disable-dev-shm-usage");
options.AddArguments("--no-sandbox");
IWebDriver driver = new ChromeDriver(options);
```

答:
Another way of ensuring that webdriver and Chrome (actually I am suggesting Chromium) versions are the same is to download both from the same Chromium snapshots page.
https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html

For Example, v96 Chromium Linux and the respective web driver is here:
https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html?prefix=Linux_x64/929513/

The build numbers for stable versions could be found here: https://github.com/Bugazelle/chromium-all-old-stable-versions

PDHide already described how to point to the webdriver path. To point to Chromium binary/executable, use

```<code>var options = new ChromeOptions();
options.BinaryLocation = "/full/location/including/binary";
var driver = new ChromeDriver("/folder/where/webdriver/located", options);
</code>```

Body:
MyChromeDriver

My Google Chrome version: 88.0.4324.150

I found some solutions but the don't worked for me.
I want to open Google Chrome throw the Selenium, but it don't work yet.

Error

System.InvalidOperationException
  HResult=0x80131509
  Message=session not created: This version of ChromeDriver only supports Chrome version 85 (SessionNotCreated)
  Source=WebDriver
  StackTrace:
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.StartSession(ICapabilities desiredCapabilities)
   at OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
   at OpenQA.Selenium.Chrome.ChromeDriver..ctor(ChromeDriverService service, ChromeOptions options, TimeSpan commandTimeout)
   at OpenQA.Selenium.Chrome.ChromeDriver..ctor(ChromeOptions options)
   at RSelenium.start_Browser() in C:\Users\ruper\source\repos\T\T\RSelenium.cs:line 30
   at T.Form1.btn_selenium_Click(Object sender, EventArgs e) in C:\Users\ruper\source\repos\T\T\Form1.cs:line 61
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at T.Program.Main() in C:\Users\ruper\source\repos\T\T\Program.cs:line 47

Code

System.Environment.SetEnvironmentVariable("webdriver.chrome.driver", @"C:\Program Files\Google\Chrome\Application\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.AddArguments("start-maximized");
options.AddArguments("disable-infobars");
options.AddArguments("--disable-extensions");
options.AddArguments("--disable-gpu");
options.AddArguments("--disable-dev-shm-usage");
options.AddArguments("--no-sandbox");
IWebDriver driver = new ChromeDriver(options);

Body:
Another way of ensuring that webdriver and Chrome (actually I am suggesting Chromium) versions are the same is to download both from the same Chromium snapshots page.
https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html

For Example, v96 Chromium Linux and the respective web driver is here:
https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html?prefix=Linux_x64/929513/

The build numbers for stable versions could be found here: https://github.com/Bugazelle/chromium-all-old-stable-versions

PDHide already described how to point to the webdriver path. To point to Chromium binary/executable, use

var options = new ChromeOptions();
options.BinaryLocation = "/full/location/including/binary";
var driver = new ChromeDriver("/folder/where/webdriver/located", options);


答:
```<code>const body = {userName:"admin",model:"test"}; your parameters if you use post such as
axios.post('your url', body)
  .then(response => {
      response.data ==> this is your data
    })
    .catch(()=>{
      console.log("error")
    });
</code>```

Or If you use only Get

```<code>axios.post('your url')
  .then(response => {
      response.data ==> this is your data
    })
    .catch(()=>{
      console.log("error")
    });
</code>```

Now you have your data with axios. You can set this data in your AgGrid easily If you follow this tutorial https://www.ag-grid.com/react-data-grid/getting-started/

Don't forget to npm install your libraries (axios and Aggrid) to you react project

By the way I highly recommend you to use Aggrid instead of classic table   etc. Aggrid has so many features such as column color, export data, smart filter, multiple filters , column sort and etc..

And If you are still confused how to set data in AgGrid, then let me show you a basic example

```<code> <AgGridReact
   enableCellChangeFlash={true}
   enableCellTextSelection={true}
   enableCellExpressions={true}
   pagination={true}
   enableSorting={true}
   enableFilter={true}
   columnDefs={this.state.columnDefinition} //it's your table definition
   rowData={this.state.dataList} // it's your json data
   enableGroupEdit={true}
   enableRangeHandle={true}
   rowHeight={25}
   headerHeight={30}
   onCellClicked={this.GetSelectedMemberInfoOnSearch}
   onColumnResized={true}>
   </AgGridReact>

columnDefinition :[{ headerName: "model", field: "modelNameKey", width: 200, suppressSizeToFit: false },
         { headerName: "speen", field: "speedKey", width: 200, suppressSizeToFit: false },
         { headerName: "hd", field: "hdKey", width: 200, suppressSizeToFit: false }]
</code>```

Title: React: How to print object from state as a table?

Body:
const body = {userName:"admin",model:"test"}; your parameters if you use post such as
axios.post('your url', body)
  .then(response => {
      response.data ==> this is your data
    })
    .catch(()=>{
      console.log("error")
    });

Or If you use only Get

axios.post('your url')
  .then(response => {
      response.data ==> this is your data
    })
    .catch(()=>{
      console.log("error")
    });

Now you have your data with axios. You can set this data in your AgGrid easily If you follow this tutorial https://www.ag-grid.com/react-data-grid/getting-started/

Don't forget to npm install your libraries (axios and Aggrid) to you react project

By the way I highly recommend you to use Aggrid instead of classic table   etc. Aggrid has so many features such as column color, export data, smart filter, multiple filters , column sort and etc..

And If you are still confused how to set data in AgGrid, then let me show you a basic example

 <AgGridReact
   enableCellChangeFlash={true}
   enableCellTextSelection={true}
   enableCellExpressions={true}
   pagination={true}
   enableSorting={true}
   enableFilter={true}
   columnDefs={this.state.columnDefinition} //it's your table definition
   rowData={this.state.dataList} // it's your json data
   enableGroupEdit={true}
   enableRangeHandle={true}
   rowHeight={25}
   headerHeight={30}
   onCellClicked={this.GetSelectedMemberInfoOnSearch}
   onColumnResized={true}>
   </AgGridReact>

columnDefinition :[{ headerName: "model", field: "modelNameKey", width: 200, suppressSizeToFit: false },
         { headerName: "speen", field: "speedKey", width: 200, suppressSizeToFit: false },
         { headerName: "hd", field: "hdKey", width: 200, suppressSizeToFit: false }]


问:
How to see nested react component
When I see sample react component usecase,for example following is listed.
But I have questions.<App /> means some react component and it has some html element.
But regarding <Theme></Theme> , it is also react component. but why this is different writing form from <App />? what is the difference between them?

```<code>    <BrowserRouter>
      <Theme>
        <App />
      </Theme>
    </BrowserRouter>
</code>```

I am totally novice of React,and search them but I still have unclear about it.
If someone has materials relating that.
Will you please let me know

thanks

答:
If you define component that have children in props, you should use it as pair tag, and whatever is inside of it, its passed to props.children.
In your example imagine that Theme can look somehow like this:

```<code>const Theme = ({children}) =>{
return <div style={{backgroundColor: red, color: blue}}>
 {children} //this is where <App /> is rendered in your case
</div>
}
</code>```

Title: How to see nested react component

Body:
When I see sample react component usecase,for example following is listed.
But I have questions.<App /> means some react component and it has some html element.
But regarding <Theme></Theme> , it is also react component. but why this is different writing form from <App />? what is the difference between them?

    <BrowserRouter>
      <Theme>
        <App />
      </Theme>
    </BrowserRouter>

I am totally novice of React,and search them but I still have unclear about it.
If someone has materials relating that.
Will you please let me know

thanks

Body:
If you define component that have children in props, you should use it as pair tag, and whatever is inside of it, its passed to props.children.
In your example imagine that Theme can look somehow like this:

const Theme = ({children}) =>{
return <div style={{backgroundColor: red, color: blue}}>
 {children} //this is where <App /> is rendered in your case
</div>
}


问:
Updating a PriorityQueue when iterating it
I need to update some fixed-priority elements in a PriorityQueue based on their ID. I think it's quite a common scenario, here's an example snippet (Android 2.2):

```<code>for (Entry e : mEntries) {
    if (e.getId().equals(someId)) {
        e.setData(newData);
    }
}
</code>```

I've then made Entry "immutable" (no setter methods) so that a new Entry instance is created and returned by setData(). I modified my method into this:

```<code>for (Entry e : mEntries) {
    if (e.getId().equals(someId)) {
        Entry newEntry = e.setData(newData);
        mEntries.remove(e);
        mEntries.add(newEntry);
     }
}
</code>```

The code seems to work fine, but someone pointed out that modifying a queue while iterating over it is a bad idea: it may throw a ConcurrentModificationException and I'd need to add the elements I want to remove to an ArrayList and remove it later. He didn't explain why, and it looks quite an overhead to me, but I couldn't find any specific explanation on internet.

(This post is similar, but there priorities can change, which is not my case)

Can anyone clarify what's wrong with my code, how should I change it and - most of all - why?

Thanks,
Rippel

PS: Some implementation details...

```<code>PriorityQueue<Entry> mEntries = new PriorityQueue<Entry>(1, Entry.EntryComparator());
</code>```

with:

```<code>public static class EntryComparator implements Comparator<Entry> {
    public int compare(Entry my, Entry their) {
        if (my.mPriority < their.mPriority) {
            return 1;
        }
        else if (my.mPriority > their.mPriority) {
            return -1;
        }
        return 0;
    }
}
</code>```

答:
a slightly better implementation is

```<code>List<Entry> toAdd = new ArrayList<Entry>();
for (Iterator<Entry> it= mEntries.iterator();it.hasNext();) {
    Entry e = it.next();
    if (e.getId().equals(someId)) {
        Entry newEntry = e.setData(newData);
        it.remove();
        toAdd.add(newEntry);
     }
}
mEntries.addAll(toAdd);
</code>```

this uses the remove of the iterator and a bulk add afterwards

ContentLicense: CC BY-SA 3.0

Body:
I need to update some fixed-priority elements in a PriorityQueue based on their ID. I think it's quite a common scenario, here's an example snippet (Android 2.2):

for (Entry e : mEntries) {
    if (e.getId().equals(someId)) {
        e.setData(newData);
    }
}

I've then made Entry "immutable" (no setter methods) so that a new Entry instance is created and returned by setData(). I modified my method into this:

for (Entry e : mEntries) {
    if (e.getId().equals(someId)) {
        Entry newEntry = e.setData(newData);
        mEntries.remove(e);
        mEntries.add(newEntry);
     }
}

The code seems to work fine, but someone pointed out that modifying a queue while iterating over it is a bad idea: it may throw a ConcurrentModificationException and I'd need to add the elements I want to remove to an ArrayList and remove it later. He didn't explain why, and it looks quite an overhead to me, but I couldn't find any specific explanation on internet.

(This post is similar, but there priorities can change, which is not my case)

Can anyone clarify what's wrong with my code, how should I change it and - most of all - why?

Thanks,
Rippel

PS: Some implementation details...

PriorityQueue<Entry> mEntries = new PriorityQueue<Entry>(1, Entry.EntryComparator());

with:

public static class EntryComparator implements Comparator<Entry> {
    public int compare(Entry my, Entry their) {
        if (my.mPriority < their.mPriority) {
            return 1;
        }
        else if (my.mPriority > their.mPriority) {
            return -1;
        }
        return 0;
    }
}

Body:
a slightly better implementation is

List<Entry> toAdd = new ArrayList<Entry>();
for (Iterator<Entry> it= mEntries.iterator();it.hasNext();) {
    Entry e = it.next();
    if (e.getId().equals(someId)) {
        Entry newEntry = e.setData(newData);
        it.remove();
        toAdd.add(newEntry);
     }
}
mEntries.addAll(toAdd);

this uses the remove of the iterator and a bulk add afterwards


问:
Uncaught ReferenceError: emptyimage is not defined
Incase a img is not found , i am showing an alternate default image this way

```<code>var defaultimage = "images/emptyimage.jpg";

divhtml.append('<i><img class = "imgclss" id="'+name+'" src="'+imagename+'" onerror="this.onerror=null;this.src='+defaultimage+'"/></i>');
</code>```

But in browser console , i am getting this undefined error

Uncaught ReferenceError: emptyimage is not defined

could anybody please help me how to resolve this errors?

I was folowing this link to resolve the issue

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

答:
How do I fix uncaught ReferenceError is not defined?

Answer: Execute Code after jQuery Library has Loaded

The most common reason behind the error "Uncaught ReferenceError: $ is not defined" is executing the jQuery code before the jQuery library file has loaded. Therefore make sure that you're executing the jQuery code only after jQuery library file has finished loading.

Body:
Incase a img is not found , i am showing an alternate default image this way

var defaultimage = "images/emptyimage.jpg";

divhtml.append('');

But in browser console , i am getting this undefined error

Uncaught ReferenceError: emptyimage is not defined

could anybody please help me how to resolve this errors?

I was folowing this link to resolve the issue

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)


问:
switch camera(back/front) in android webrtc
I have used libjingle library for webrtc android application. I have successfully implemented audio video streaming for two way communication.

Till now i was using front camera for video streaming but now i want to put option for users to select front or back camera for video streaming.

How can i archive it? i have no idea about this.

I have tried VideocaptureAndroid switch camera method but not working.

If anyone one knows then help me out for this functionality?

Thanks in advance.

答:
Create a new video capturer and start it. Dont forget to stop the old one.</p>
```<code>fun switchCamera() {
    cameraFacingFront = !cameraFacingFront
    try {
        videoCapturer!!.stopCapture()
    } catch (e: InterruptedException) {
    }
    videoCapturer = createVideoCapturer(cameraFacingFront)
    videoCapturer!!.initialize(
        surfaceTextureHelper,
        activity,
        videoSource!!.getCapturerObserver()
    )
    videoCapturer!!.startCapture(
        VIDEO_SIZE_WIDTH,
        VIDEO_SIZE_HEIGHT,
        VIDEO_FPS
    )
}
</code>```

Body:
Create a new video capturer and start it. Dont forget to stop the old one.

fun switchCamera() {
    cameraFacingFront = !cameraFacingFront
    try {
        videoCapturer!!.stopCapture()
    } catch (e: InterruptedException) {
    }
    videoCapturer = createVideoCapturer(cameraFacingFront)
    videoCapturer!!.initialize(
        surfaceTextureHelper,
        activity,
        videoSource!!.getCapturerObserver()
    )
    videoCapturer!!.startCapture(
        VIDEO_SIZE_WIDTH,
        VIDEO_SIZE_HEIGHT,
        VIDEO_FPS
    )
}


问:
System.Text.Json.JsonException: The input does not contain any JSON tokens
I'm just trying to use a Http POST method in a Blazor app through

```<code>public async Task CreateUnit(UnitEntity unit)
{
    await _http.PostJsonAsync<UnitEntity>("api/units", unit);
}
</code>```

_http and myObject have been defined elsewhere, but I'm getting this weird error. Can anyone help? This is the closest thing I could find elsewhere: https://github.com/dotnet/runtime/issues/30945.

The full error message is

System.Text.Json.JsonException: The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0.

And it here's the stack

答: i had similar issue and the problem to check if the json string you are readying is empty, null, or bad formatted. debug to the code line where you are reading data into string before deserialize or serialize call.</p>

Body:
I'm just trying to use a Http POST method in a Blazor app through

public async Task CreateUnit(UnitEntity unit)
{
    await _http.PostJsonAsync<UnitEntity>("api/units", unit);
}

_http and myObject have been defined elsewhere, but I'm getting this weird error. Can anyone help? This is the closest thing I could find elsewhere: https://github.com/dotnet/runtime/issues/30945.

The full error message is

System.Text.Json.JsonException: The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0.

And it here's the stack


问:
Theory of storing a number and text in same SQL field
I have a three tables

Results:
TestID
TestCode
Value

Tests:
TestID
TestType
SysCodeID

SystemCodes
SysCodeID
ParentSysCodeID
Description

The question I have is for when the user is entering data into the results table.

The formatting code when the row gets the focus changes the value field to a dropdown combobox if the testCode is of type SystemList.  The drop down has a list of all the system codes that have a parentsyscodeID of the test.SysCodeID.  When the user chooses a value in the list it translates into a number which goes into the value field.

The datatype of the Results.Value field is integer.  I made it an integer instead of a string because when reporting it is easier to do calculations and sorting if it is a number.  There are issues if you are putting integer/decimal value into a string field.  As well, when the system was being designed they only wanted numbers in there.

The users now want to put strings into the value field as well as numbers/values from a list and I'm wondering what the best way of doing that would be.

Would it be bad practice to convert the field over to a string and then store both strings and integers in the same field?  There are different issues related to this one but i'm not sure if any are a really big deal.

Should I add another column into the table of string datatype and  if the test is a string type then put the data the user enters into the different field.

Another option would be to create a 1-1 relationship to another table and if the user types in a string into the value field it adds it into the new table with a key of a number.

Anyone have any interesting ideas?

答:
Sql Server at least has an IsNumeric function you can use:</p>

```<code>ORDER BY IsNumeric(Results.Value) DESC,
         CASE WHEN IsNumeric(Results.Value) = 1 THEN Len(Results.Value) ELSE 99 END,
         Results.Value
</code>```

OwnerDisplayName: Jaydel Gluckie

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jonathan Leffler

Body:
Sql Server at least has an IsNumeric function you can use:

ORDER BY IsNumeric(Results.Value) DESC,
         CASE WHEN IsNumeric(Results.Value) = 1 THEN Len(Results.Value) ELSE 99 END,
         Results.Value

OwnerDisplayName: Joel Coehoorn