问:
Adding Multiple Markers from Firestore Database on Google Maps in Android Studio using Java
I'm new to Android development and I wanted to ask how I would be able to add multiple markers to my application using the coordinates stored in Firebase. A screenshot of the Firebase is shown, but it helps me get only one marker for now. I want to get multiple markers by accessing the same document or suggestions that can help me manage places stored in firebase in a more organized way and display them on the map along with name and location. I've been able to retrieve on location, for now, screenshots of the app and firebase are attached.

```<code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private static final int REQUEST_LOCATION_PERMISSION = 1009;
    private GoogleMap mMap;
    private ActivityMapsBinding binding;
    private FusedLocationProviderClient mFusedLocationClient;
    //These Clusters were used to manage the marker Clusters that had images on maps too
    private ClusterManager mClusterManager;
    //Same is the case with these clusters
    private MyClusterManagerRenderer myClusterManagerRenderer;
    //Instantiating the Firestore Database
    FirebaseFirestore db;

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

        // initializing our firebase firestore.
        db = FirebaseFirestore.getInstance();

        binding = ActivityMapsBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        //Getting the device location over here
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    private void addMapMarkers(){

    }

    private void getLastKnownLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mFusedLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                if(task.isSuccessful()){
                    Location location = task.getResult();

                }
            }
        });
    }
    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // creating a variable for document reference.
        DocumentReference documentReference = db.collection("MapsData").document("7QWDor9vozLaHdFYV9kh");

        // calling document reference class with on snap shot listener.
        documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {
                if (value != null && value.exists()) {
                    // below line is to create a geo point and we are getting
                    // geo point from firebase and setting to it.
                    GeoPoint geoPoint = value.getGeoPoint("geoPoint");

                    // getting latitude and longitude from geo point
                    // and setting it to our location.
                    LatLng location = new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude());

                    // adding marker to each location on google maps
                    mMap.addMarker(new MarkerOptions().position(location).title("Name"));

                    // below line is use to move camera.
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
                } else {
                    Toast.makeText(MapsActivity.this, "Error found is " + error, Toast.LENGTH_SHORT).show();
                }
            }
        });
        //Adding custom maps style over here
        //******** THIS PART OF CODE EXCLUSIVELY DESIGNED TO FETCH THE CUSTOM MAPS.JSON TEMPLATE**********
        enableMyLocation();

        try {
            // Customise the styling of the base map using a JSON object defined
            // in a raw resource file.
            boolean success = googleMap.setMapStyle(
                    MapStyleOptions.loadRawResourceStyle(
                            this, R.raw.mapstyle));
            if (!success) {
                Log.e("MapsActivity", "Style parsing failed.");
            }
            } catch (Resources. NotFoundException e) {
            Log.e("MapsActivity", "Can't find style. Error: ", e);
        }
        //******** MAP STYLING CODE ENDS OVER HERE **********
        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        LatLng islamabad = new LatLng(33.68, 73.04);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Islamabad"));
        //moving the camera position to Islamabad.
        mMap.moveCamera(CameraUpdateFactory.newLatLng(islamabad));
    }
    //Getting the Users current Location
    private void enableMyLocation() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
        } else {
            ActivityCompat.requestPermissions(this, new String[]
                            {Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_LOCATION_PERMISSION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        // Check if location permissions are granted and if so enable the
        // location data layer.
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_LOCATION_PERMISSION:
                if (grantResults.length > 0
                        && grantResults[0]
                        == PackageManager.PERMISSION_GRANTED) {
                    enableMyLocation();
                    break;
                }
        }
    }
}
</code>```

答:
To be able to get multiple markers from Firestore, you need to read all the documents that exist under the MapsData collection. This means that you need to create a reference that points exact to the collection and then perform a get() call:

```<code>FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("MapsData").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (QueryDocumentSnapshot document : task.getResult()) {
                if (document != null) {
                    GeoPoint geoPoint = value.getGeoPoint("geoPoint");
                    LatLng location = new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude());
                    mMap.addMarker(new MarkerOptions().position(location).title("Name"));
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
                }
            }
        } else {
            Log.d(TAG, task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});
</code>```

Your code adds a single marker because you are creating only a DocumentReference object that contains only a single GeoPoint object. If you need to read them in real-time, then you can listen for real-time updates.

Body:
I'm new to Android development and I wanted to ask how I would be able to add multiple markers to my application using the coordinates stored in Firebase. A screenshot of the Firebase is shown, but it helps me get only one marker for now. I want to get multiple markers by accessing the same document or suggestions that can help me manage places stored in firebase in a more organized way and display them on the map along with name and location. I've been able to retrieve on location, for now, screenshots of the app and firebase are attached.

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private static final int REQUEST_LOCATION_PERMISSION = 1009;
    private GoogleMap mMap;
    private ActivityMapsBinding binding;
    private FusedLocationProviderClient mFusedLocationClient;
    //These Clusters were used to manage the marker Clusters that had images on maps too
    private ClusterManager mClusterManager;
    //Same is the case with these clusters
    private MyClusterManagerRenderer myClusterManagerRenderer;
    //Instantiating the Firestore Database
    FirebaseFirestore db;

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

        // initializing our firebase firestore.
        db = FirebaseFirestore.getInstance();

        binding = ActivityMapsBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        //Getting the device location over here
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    private void addMapMarkers(){

    }

    private void getLastKnownLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mFusedLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                if(task.isSuccessful()){
                    Location location = task.getResult();

                }
            }
        });
    }
    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // creating a variable for document reference.
        DocumentReference documentReference = db.collection("MapsData").document("7QWDor9vozLaHdFYV9kh");

        // calling document reference class with on snap shot listener.
        documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {
                if (value != null && value.exists()) {
                    // below line is to create a geo point and we are getting
                    // geo point from firebase and setting to it.
                    GeoPoint geoPoint = value.getGeoPoint("geoPoint");

                    // getting latitude and longitude from geo point
                    // and setting it to our location.
                    LatLng location = new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude());

                    // adding marker to each location on google maps
                    mMap.addMarker(new MarkerOptions().position(location).title("Name"));

                    // below line is use to move camera.
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
                } else {
                    Toast.makeText(MapsActivity.this, "Error found is " + error, Toast.LENGTH_SHORT).show();
                }
            }
        });
        //Adding custom maps style over here
        //******** THIS PART OF CODE EXCLUSIVELY DESIGNED TO FETCH THE CUSTOM MAPS.JSON TEMPLATE**********
        enableMyLocation();

        try {
            // Customise the styling of the base map using a JSON object defined
            // in a raw resource file.
            boolean success = googleMap.setMapStyle(
                    MapStyleOptions.loadRawResourceStyle(
                            this, R.raw.mapstyle));
            if (!success) {
                Log.e("MapsActivity", "Style parsing failed.");
            }
            } catch (Resources. NotFoundException e) {
            Log.e("MapsActivity", "Can't find style. Error: ", e);
        }
        //******** MAP STYLING CODE ENDS OVER HERE **********
        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        LatLng islamabad = new LatLng(33.68, 73.04);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Islamabad"));
        //moving the camera position to Islamabad.
        mMap.moveCamera(CameraUpdateFactory.newLatLng(islamabad));
    }
    //Getting the Users current Location
    private void enableMyLocation() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
        } else {
            ActivityCompat.requestPermissions(this, new String[]
                            {Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_LOCATION_PERMISSION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        // Check if location permissions are granted and if so enable the
        // location data layer.
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_LOCATION_PERMISSION:
                if (grantResults.length > 0
                        && grantResults[0]
                        == PackageManager.PERMISSION_GRANTED) {
                    enableMyLocation();
                    break;
                }
        }
    }
}

Body:
To be able to get multiple markers from Firestore, you need to read all the documents that exist under the MapsData collection. This means that you need to create a reference that points exact to the collection and then perform a get() call:

FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("MapsData").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (QueryDocumentSnapshot document : task.getResult()) {
                if (document != null) {
                    GeoPoint geoPoint = value.getGeoPoint("geoPoint");
                    LatLng location = new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude());
                    mMap.addMarker(new MarkerOptions().position(location).title("Name"));
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
                }
            }
        } else {
            Log.d(TAG, task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});

Your code adds a single marker because you are creating only a DocumentReference object that contains only a single GeoPoint object. If you need to read them in real-time, then you can listen for real-time updates.


来源: stackexchange

问:
Select string by time
I have a Dataframe and i'd like to classify the rows by some periods of time in a day.
I added a new column with the name: "turno" and this column was suposed to be classified in "NoiteAnterior", "Dia" and "Noite". I made a function to do this, but always comes the same classification, independent of the time. I need some help to know where i am been wrong. This is the function:

time_test.xlsx

dataframe

def turno(event):
  early_morning = dt.strptime('00:00:00', '%H:%M:%S').time()
  morning = dt.strptime('07:00:00', '%H:%M:%S').time()
  night = dt.strptime('19:00:00', '%H:%M:%S').time()

  for hour in event:
   if early_morning < hour < morning:
      return 'NoiteAnterior'
   elif morning < hour < night:
      return 'Dia'
   else:
      return 'Noite'
df['turno'] = turno(df['hora_inicio_evento'])
```

the column df['hora_inicio_evento']:
['hora_inicio_turno']

答:
I make the assumption that df['hora_inicio_evento'] looks something like '15:37:14'. Then you should first extract the hour from this input. if it's already a datetime format, just use event everywhere instead of event_time.

```<code>def turno(event):
    early_morning = dt.strptime('00:00:00', '%H:%M:%S').time()
    morning = dt.strptime('07:00:00', '%H:%M:%S').time()
    night = dt.strptime('19:00:00', '%H:%M:%S').time()

    for e in event:
        event_time = dt.strptime(e, '%H:%M:%S').time()
        if early_morning.hour < event_time.hour <= morning.hour:
            return 'NoiteAnterior'
        elif morning.hour < event_time.hour <= night.hour:
            return 'Dia'
        else:
            return 'Noite'
</code>```

Note that for in loops don't work like you wanted to use them, they iterate over every element of an iterable and take this single element into the loop denoted as, in your case hour and not the attribute hour of the iterable itself.

ContentLicense: CC BY-SA 4.0

Title: Select string by time

Body:
I have a Dataframe and i'd like to classify the rows by some periods of time in a day.
I added a new column with the name: "turno" and this column was suposed to be classified in "NoiteAnterior", "Dia" and "Noite". I made a function to do this, but always comes the same classification, independent of the time. I need some help to know where i am been wrong. This is the function:

time_test.xlsx

dataframe

def turno(event):
  early_morning = dt.strptime('00:00:00', '%H:%M:%S').time()
  morning = dt.strptime('07:00:00', '%H:%M:%S').time()
  night = dt.strptime('19:00:00', '%H:%M:%S').time()

  for hour in event:
   if early_morning < hour < morning:
      return 'NoiteAnterior'
   elif morning < hour < night:
      return 'Dia'
   else:
      return 'Noite'
df['turno'] = turno(df['hora_inicio_evento'])

the column df['hora_inicio_evento']:
['hora_inicio_turno']

Body:
I make the assumption that df['hora_inicio_evento'] looks something like '15:37:14'. Then you should first extract the hour from this input. if it's already a datetime format, just use event everywhere instead of event_time.

def turno(event):
    early_morning = dt.strptime('00:00:00', '%H:%M:%S').time()
    morning = dt.strptime('07:00:00', '%H:%M:%S').time()
    night = dt.strptime('19:00:00', '%H:%M:%S').time()

    for e in event:
        event_time = dt.strptime(e, '%H:%M:%S').time()
        if early_morning.hour < event_time.hour <= morning.hour:
            return 'NoiteAnterior'
        elif morning.hour < event_time.hour <= night.hour:
            return 'Dia'
        else:
            return 'Noite'

Note that for in loops don't work like you wanted to use them, they iterate over every element of an iterable and take this single element into the loop denoted as, in your case hour and not the attribute hour of the iterable itself.


问:
how to run multiple watch script in docker
I'am moving my react apps into docker, I am working in legacy project and we have multiple react apps. We are attaching script with react apps in script tags on every page whose need to use this files. For docker we want to use Express to serve our files.
Is there any way to run multiple watch commands ?

here is my package.json file:

```<code>{
  "name": "docker apps",
  "version": "3.0.0",
  "description": "apps",
  "license": "ISC",
  "author": "devs",
  "main": "main.js",
  "engines": {
    "node": ">=14.7.0",
    "npm": ">=6.14.13"
  },
  "scripts": {
    "requirements-check": "node checkNodeVersion.js",
    "react": "webpack --env.mode production --env.app react",
    "react-watch": "webpack --env.mode development --env.app react --watch",
    "serve": "nodemon server.js",
    "serve:prod": "node server.js --port=80",
    "build": "npm run react",
    "start": "npm run react-watch",
    "test": "jest",
    "lint": "eslint .",
    "dev-start": "concurrently \"npm run react-watch\" \"npm run serve\"",
    "dev-build": "concurrently \"npm run build\" \"npm run serve:prod\"",
    "lint-payment": "eslint payment/",
    "lint-formLibrary": "eslint formLibrary/",
    "lint-fileManager": "eslint fileManager/",
    "lint-blockLibrary": "eslint LPBlockLibrary/",
    "lint-contracts": "eslint contracts/",
    "lint-payment:fix": "eslint --fix payment/",
    "lint-formLibrary:fix": "eslint --fix formLibrary/",
    "lint-fileManager:fix": "eslint --fix fileManager/",
    "lint-blockLibrary:fix": "eslint --fix LPBlockLibrary/",
    "lint-contracts:fix": "eslint --fix contracts/",
    "lint:fix": "eslint --fix ."
  },
  "dependencies": {
    "@mikecousins/react-pdf": "^5.5.1",
    "@tkaramanski/fmcomponents": "^1.6.2",
    "@types/testing-library__jest-dom": "^5.9.5",
    "axios": "^0.21.1",
    "bootstrap": "^4.1.3",
    "classnames": "^2.2.6",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "gulp-cli": "^2.2.0",
    "gulp-install": "^1.1.0",
    "handlebars-loader": "^1.7.1",
    "jsdom": "^16.6.0",
    "lodash": "^4.17.11",
    "postcss": "^8.1.4",
    "postcss-js": "^3.0.1",
    "prop-types": "^15.7.2",
    "react": "^16.9.0",
    "react-bs-notifier": "^5.0.0",
    "react-datepicker": "^4.1.1",
    "react-dnd": "^7.3.2",
    "react-dnd-html5-backend": "^7.2.0",
    "react-dom": "^16.9.0",
    "react-dropzone": "^7.0.1",
    "react-hook-form": "^4.9.6",
    "react-hot-loader": "^4.12.18",
    "react-infinite-scroll-component": "^4.2.0",
    "react-jss": "^8.6.1",
    "react-popper-tooltip": "^4.3.1",
    "react-redux": "^7.1.3",
    "react-router-dom": "^5.2.0",
    "react-scrollbar": "^0.5.4",
    "reactstrap": "^6.5.0",
    "redux": "^4.0.4",
    "redux-devtools-extension": "^2.13.8",
    "redux-persist": "^6.0.0",
    "redux-thunk": "^2.3.0",
    "reselect": "^4.0.0",
    "resolve-url-loader": "^3.1.2",
    "semver": "^5.7.1",
    "styled-components": "^5.3.0",
    "typesafe-actions": "^5.1.0"
  },
  "devDependencies": {
    "@babel/core": "^7.13.14",
    "@babel/plugin-proposal-class-properties": "^7.13.0",
    "@babel/plugin-proposal-optional-chaining": "^7.13.12",
    "@babel/plugin-transform-runtime": "^7.13.10",
    "@babel/preset-env": "^7.13.12",
    "@babel/preset-react": "^7.13.13",
    "@babel/preset-stage-0": "^7.8.3",
    "@babel/preset-typescript": "^7.13.0",
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.5",
    "@tkaramanski/fmcomponents": "^1.5.1",
    "@types/jest": "^26.0.22",
    "@types/react": "^17.0.3",
    "@types/react-datepicker": "^4.1.4",
    "@types/react-dom": "^17.0.2",
    "@types/react-lazyload": "^3.1.0",
    "@types/react-redux": "^7.1.16",
    "@types/react-router-dom": "^5.1.8",
    "@types/styled-components": "^5.1.7",
    "@typescript-eslint/eslint-plugin": "^4.17.0",
    "autoprefixer": "^9.8.0",
    "babel-eslint": "^10.1.0",
    "babel-jest": "^26.6.3",
    "babel-loader": "^8.2.2",
    "babel-plugin-macros": "^3.0.1",
    "babel-plugin-styled-components": "^1.12.0",
    "babel-polyfill": "^6.26.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "clean-webpack-plugin": "^3.0.0",
    "concurrently": "^5.2.0",
    "copy-webpack-plugin": "^6.0.1",
    "css-loader": "^3.6.0",
    "enzyme": "^3.11.0",
    "enzyme-adapter-react-16": "^1.15.4",
    "eslint": "^7.10.0",
    "eslint-config-airbnb": "^18.2.1",
    "eslint-config-airbnb-typescript": "^12.3.1",
    "eslint-plugin-import": "^2.23.4",
    "eslint-plugin-jsx-a11y": "^6.3.1",
    "eslint-plugin-react": "^7.21.3",
    "eslint-plugin-react-hooks": "^4.2.0",
    "extract-loader": "^5.1.0",
    "file-loader": "^6.0.0",
    "gulp": "^4.0.2",
    "gulp-babel": "^8.0.0",
    "gulp-cli": "^2.2.0",
    "gulp-concat": "^2.6.1",
    "gulp-sourcemaps": "^2.6.5",
    "gulp-uglify": "^3.0.2",
    "husky": "^4.3.0",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^26.6.3",
    "mini-css-extract-plugin": "^0.9.0",
    "moment": "^2.26.0",
    "postcss-loader": "^3.0.0",
    "prettier": "^2.4.1",
    "pump": "^3.0.0",
    "react-copy-to-clipboard": "^5.0.2",
    "react-test-renderer": "^16.13.1",
    "react-tippy": "^1.4.0",
    "redux-mock-store": "^1.5.4",
    "renamer": "^1.1.4",
    "sass": "^1.35.1",
    "sass-loader": "^8.0.2",
    "style-loader": "^1.2.1",
    "ts-jest": "^26.5.4",
    "ts-loader": "^8.1.0",
    "typescript": "4.2.3",
    "url-loader": "^4.1.0",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.11",
    "webpack-fix-style-only-entries": "^0.5.0",
    "webpack-merge": "^4.2.2",
    "wildcards-entry-webpack-plugin": "^2.1.0"
  },
  "husky": {
    "hooks": {
      "pre-commit": "npm run requirements-check",
      "pre-push": "npm run lint"
    }
  },
  "jest": {
    "setupTestFrameworkScriptFile": "./setupTests.js",
    "setupFiles": [
      "./payment/src/__mocks__/data.js"
    ],
    "collectCoverageFrom": [
      "payment/src/__tests__/*.{js,jsx}",
      "LPBlockLibrary/src/__testes__/*{ts,tsx}"
    ],
    "moduleNameMapper": {
      "\\.(png|jpg|gif|ttf|eot|svg)$": "<rootDir>/config/jest/fileMock.js"
    },
    "transform": {
      "\\.tsx?$": "ts-jest",
      "\\.jsx?$": "babel-jest"
    }
  }
}

</code>```

here is my docker:

```<code>FROM node:14.17.0

WORKDIR /frontend-apps

ENV PATH /frontend-apps/node_modules/.bin:$PATH

COPY package.json \
    package-lock.json \
    .npmrc ./

RUN npm config set strict-ssl false
RUN npm install
RUN npm config set strict-ssl true

COPY . ./

EXPOSE 80
CMD [ "npm", "run", "dev-start"]

</code>```

here is my docker-compose file.

```<code>version: '3.7'

services:
  frontend-docker-app:
    container_name: docker-front-apps
    build:
      context: .
      dockerfile: Dockerfile.test
    volumes:
      - '.:/frontendApps'
      - '/frontendApps/node_modules'
    ports:
      - 3000:3000
</code>```

in docker file I try to run multiple commands with concurrently

```<code> "react-watch": "webpack --env.mode development --env.app react --watch",

 "serve": "nodemon server.js",

 "dev-start": "concurrently \"npm run react-watch\" \"npm run serve\"",
</code>```

答:
I solved my problem, it turned out that I accidentally remove my nodemon package from package.json, and I had bad docker compose config. I changed it to this version:

```<code>version: '3.7'

services:
  frontend-docker-app:
    container_name: docker-front-apps
    working_dir: /var/www/app
    build:
      context: .
      dockerfile: Dockerfile.test
    volumes:
      - .:/var/www/app
      - '/frontendApps/node_modules'
    tty: true
    ports:
      - 3000:3000
    environment:
      - CHOKIDAR_USEPOLLING=true
</code>```

and changed cmd command from Docker file to this:

```<code>EXPOSE 80
CMD [ "npm", "run", "dev-build"]
</code>```

and everything works fine.

Body:
I'am moving my react apps into docker, I am working in legacy project and we have multiple react apps. We are attaching script with react apps in script tags on every page whose need to use this files. For docker we want to use Express to serve our files.
Is there any way to run multiple watch commands ?

here is my package.json file:

{
  "name": "docker apps",
  "version": "3.0.0",
  "description": "apps",
  "license": "ISC",
  "author": "devs",
  "main": "main.js",
  "engines": {
    "node": ">=14.7.0",
    "npm": ">=6.14.13"
  },
  "scripts": {
    "requirements-check": "node checkNodeVersion.js",
    "react": "webpack --env.mode production --env.app react",
    "react-watch": "webpack --env.mode development --env.app react --watch",
    "serve": "nodemon server.js",
    "serve:prod": "node server.js --port=80",
    "build": "npm run react",
    "start": "npm run react-watch",
    "test": "jest",
    "lint": "eslint .",
    "dev-start": "concurrently \"npm run react-watch\" \"npm run serve\"",
    "dev-build": "concurrently \"npm run build\" \"npm run serve:prod\"",
    "lint-payment": "eslint payment/",
    "lint-formLibrary": "eslint formLibrary/",
    "lint-fileManager": "eslint fileManager/",
    "lint-blockLibrary": "eslint LPBlockLibrary/",
    "lint-contracts": "eslint contracts/",
    "lint-payment:fix": "eslint --fix payment/",
    "lint-formLibrary:fix": "eslint --fix formLibrary/",
    "lint-fileManager:fix": "eslint --fix fileManager/",
    "lint-blockLibrary:fix": "eslint --fix LPBlockLibrary/",
    "lint-contracts:fix": "eslint --fix contracts/",
    "lint:fix": "eslint --fix ."
  },
  "dependencies": {
    "@mikecousins/react-pdf": "^5.5.1",
    "@tkaramanski/fmcomponents": "^1.6.2",
    "@types/testing-library__jest-dom": "^5.9.5",
    "axios": "^0.21.1",
    "bootstrap": "^4.1.3",
    "classnames": "^2.2.6",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "gulp-cli": "^2.2.0",
    "gulp-install": "^1.1.0",
    "handlebars-loader": "^1.7.1",
    "jsdom": "^16.6.0",
    "lodash": "^4.17.11",
    "postcss": "^8.1.4",
    "postcss-js": "^3.0.1",
    "prop-types": "^15.7.2",
    "react": "^16.9.0",
    "react-bs-notifier": "^5.0.0",
    "react-datepicker": "^4.1.1",
    "react-dnd": "^7.3.2",
    "react-dnd-html5-backend": "^7.2.0",
    "react-dom": "^16.9.0",
    "react-dropzone": "^7.0.1",
    "react-hook-form": "^4.9.6",
    "react-hot-loader": "^4.12.18",
    "react-infinite-scroll-component": "^4.2.0",
    "react-jss": "^8.6.1",
    "react-popper-tooltip": "^4.3.1",
    "react-redux": "^7.1.3",
    "react-router-dom": "^5.2.0",
    "react-scrollbar": "^0.5.4",
    "reactstrap": "^6.5.0",
    "redux": "^4.0.4",
    "redux-devtools-extension": "^2.13.8",
    "redux-persist": "^6.0.0",
    "redux-thunk": "^2.3.0",
    "reselect": "^4.0.0",
    "resolve-url-loader": "^3.1.2",
    "semver": "^5.7.1",
    "styled-components": "^5.3.0",
    "typesafe-actions": "^5.1.0"
  },
  "devDependencies": {
    "@babel/core": "^7.13.14",
    "@babel/plugin-proposal-class-properties": "^7.13.0",
    "@babel/plugin-proposal-optional-chaining": "^7.13.12",
    "@babel/plugin-transform-runtime": "^7.13.10",
    "@babel/preset-env": "^7.13.12",
    "@babel/preset-react": "^7.13.13",
    "@babel/preset-stage-0": "^7.8.3",
    "@babel/preset-typescript": "^7.13.0",
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.5",
    "@tkaramanski/fmcomponents": "^1.5.1",
    "@types/jest": "^26.0.22",
    "@types/react": "^17.0.3",
    "@types/react-datepicker": "^4.1.4",
    "@types/react-dom": "^17.0.2",
    "@types/react-lazyload": "^3.1.0",
    "@types/react-redux": "^7.1.16",
    "@types/react-router-dom": "^5.1.8",
    "@types/styled-components": "^5.1.7",
    "@typescript-eslint/eslint-plugin": "^4.17.0",
    "autoprefixer": "^9.8.0",
    "babel-eslint": "^10.1.0",
    "babel-jest": "^26.6.3",
    "babel-loader": "^8.2.2",
    "babel-plugin-macros": "^3.0.1",
    "babel-plugin-styled-components": "^1.12.0",
    "babel-polyfill": "^6.26.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "clean-webpack-plugin": "^3.0.0",
    "concurrently": "^5.2.0",
    "copy-webpack-plugin": "^6.0.1",
    "css-loader": "^3.6.0",
    "enzyme": "^3.11.0",
    "enzyme-adapter-react-16": "^1.15.4",
    "eslint": "^7.10.0",
    "eslint-config-airbnb": "^18.2.1",
    "eslint-config-airbnb-typescript": "^12.3.1",
    "eslint-plugin-import": "^2.23.4",
    "eslint-plugin-jsx-a11y": "^6.3.1",
    "eslint-plugin-react": "^7.21.3",
    "eslint-plugin-react-hooks": "^4.2.0",
    "extract-loader": "^5.1.0",
    "file-loader": "^6.0.0",
    "gulp": "^4.0.2",
    "gulp-babel": "^8.0.0",
    "gulp-cli": "^2.2.0",
    "gulp-concat": "^2.6.1",
    "gulp-sourcemaps": "^2.6.5",
    "gulp-uglify": "^3.0.2",
    "husky": "^4.3.0",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^26.6.3",
    "mini-css-extract-plugin": "^0.9.0",
    "moment": "^2.26.0",
    "postcss-loader": "^3.0.0",
    "prettier": "^2.4.1",
    "pump": "^3.0.0",
    "react-copy-to-clipboard": "^5.0.2",
    "react-test-renderer": "^16.13.1",
    "react-tippy": "^1.4.0",
    "redux-mock-store": "^1.5.4",
    "renamer": "^1.1.4",
    "sass": "^1.35.1",
    "sass-loader": "^8.0.2",
    "style-loader": "^1.2.1",
    "ts-jest": "^26.5.4",
    "ts-loader": "^8.1.0",
    "typescript": "4.2.3",
    "url-loader": "^4.1.0",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.11",
    "webpack-fix-style-only-entries": "^0.5.0",
    "webpack-merge": "^4.2.2",
    "wildcards-entry-webpack-plugin": "^2.1.0"
  },
  "husky": {
    "hooks": {
      "pre-commit": "npm run requirements-check",
      "pre-push": "npm run lint"
    }
  },
  "jest": {
    "setupTestFrameworkScriptFile": "./setupTests.js",
    "setupFiles": [
      "./payment/src/__mocks__/data.js"
    ],
    "collectCoverageFrom": [
      "payment/src/__tests__/*.{js,jsx}",
      "LPBlockLibrary/src/__testes__/*{ts,tsx}"
    ],
    "moduleNameMapper": {
      "\\.(png|jpg|gif|ttf|eot|svg)$": "<rootDir>/config/jest/fileMock.js"
    },
    "transform": {
      "\\.tsx?$": "ts-jest",
      "\\.jsx?$": "babel-jest"
    }
  }
}

here is my docker:

FROM node:14.17.0

WORKDIR /frontend-apps

ENV PATH /frontend-apps/node_modules/.bin:$PATH

COPY package.json \
    package-lock.json \
    .npmrc ./

RUN npm config set strict-ssl false
RUN npm install
RUN npm config set strict-ssl true

COPY . ./

EXPOSE 80
CMD [ "npm", "run", "dev-start"]

here is my docker-compose file.

version: '3.7'

services:
  frontend-docker-app:
    container_name: docker-front-apps
    build:
      context: .
      dockerfile: Dockerfile.test
    volumes:
      - '.:/frontendApps'
      - '/frontendApps/node_modules'
    ports:
      - 3000:3000

in docker file I try to run multiple commands with concurrently

 "react-watch": "webpack --env.mode development --env.app react --watch",

 "serve": "nodemon server.js",

 "dev-start": "concurrently \"npm run react-watch\" \"npm run serve\"",

Body:
I solved my problem, it turned out that I accidentally remove my nodemon package from package.json, and I had bad docker compose config. I changed it to this version:

version: '3.7'

services:
  frontend-docker-app:
    container_name: docker-front-apps
    working_dir: /var/www/app
    build:
      context: .
      dockerfile: Dockerfile.test
    volumes:
      - .:/var/www/app
      - '/frontendApps/node_modules'
    tty: true
    ports:
      - 3000:3000
    environment:
      - CHOKIDAR_USEPOLLING=true

and changed cmd command from Docker file to this:

EXPOSE 80
CMD [ "npm", "run", "dev-build"]

and everything works fine.


问:
printing a list of values within a certain range
So I am having a problem with printing certain values that fall within a certain range from a list

Here is the code

```<code>import statistics as st

players = [180, 172, 178, 185, 190, 195, 192, 200, 210, 190]
players.sort()

avg = sum(players)/ len(players)

std = st.stdev(players)

low = avg - std
high = avg + std

for i in range (int(low), int(high)):
 print(players[i])
</code>```

It is giving me this error

```<code>Traceback (most recent call last):
File "file0.py", line 16, in <module>
print(players[i])
IndexError: list index out of range
</code>```

Thank you

答:
Your code at the moment is returning players at position index i (players[i]), and your i values here the numbers between your low and high variables.

Since these variables are larger than the length of your list, you are trying to index your list players with numbers that are too large, meaning you are returned the "IndexError: list index out of range" error.

Try instead:

```<code>print([player for player in players if player >int(low) and player < int(high)])
</code>```

using list comprehension or:

```<code>for player in players:
    if player > int(low) and player < int(high):
        print(player)
</code>```

using a classic for loop.

Body:
So I am having a problem with printing certain values that fall within a certain range from a list

Here is the code

import statistics as st

players = [180, 172, 178, 185, 190, 195, 192, 200, 210, 190]
players.sort()

avg = sum(players)/ len(players)

std = st.stdev(players)

low = avg - std
high = avg + std

for i in range (int(low), int(high)):
 print(players[i])

It is giving me this error

Traceback (most recent call last):
File "file0.py", line 16, in <module>
print(players[i])
IndexError: list index out of range

Thank you

Body:
Your code at the moment is returning players at position index i (players[i]), and your i values here the numbers between your low and high variables.

Since these variables are larger than the length of your list, you are trying to index your list players with numbers that are too large, meaning you are returned the "IndexError: list index out of range" error.

Try instead:

print([player for player in players if player >int(low) and player < int(high)])

using list comprehension or:

for player in players:
    if player > int(low) and player < int(high):
        print(player)

using a classic for loop.


问:
How to fix this npm "code 1" error installing electron
While installing electron using this command:

```<code>npm install electron --save-dev
</code>```

I get the following error:

```<code>npm ERR! code 1
npm ERR! path C:\Users\ducpm34\Desktop\04_01_2022\electron-app\node_modules\electron
npm ERR! command failed
npm ERR! command C:\Windows\system32\cmd.exe /d /s /c node install.js
npm ERR! RequestError: self signed certificate in certificate chain
npm ERR!     at ClientRequest.<anonymous> (C:\Users\ducpm34\Desktop\04_01_2022\electron-app\node_modules\got\source\request-as-event-emitter.js:178:14)
npm ERR!     at Object.onceWrapper (node:events:510:26)
npm ERR!     at ClientRequest.emit (node:events:402:35)
npm ERR!     at ClientRequest.origin.emit (C:\Users\ducpm34\Desktop\04_01_2022\electron-app\node_modules\@szmarczak\http-timer\source\index.js:37:11)
npm ERR!     at TLSSocket.socketErrorListener (node:_http_client:447:9)
npm ERR!     at TLSSocket.emit (node:events:390:28)
npm ERR!     at emitErrorNT (node:internal/streams/destroy:157:8)
npm ERR!     at emitErrorCloseNT (node:internal/streams/destroy:122:3)
npm ERR!     at processTicksAndRejections (node:internal/process/task_queues:83:21)

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\ducpm34\AppData\Local\npm-cache\_logs\2022-01-04T07_39_31_143Z-debug.log
</code>```

How do I fix the RequestError: self signed certificate in certificate chain error?

答: Use this command $export NODE_TLS_REJECT_UNAUTHORIZED=0 ,and thank me later!</p>

Body:
While installing electron using this command:

npm install electron --save-dev

I get the following error:

npm ERR! code 1
npm ERR! path C:\Users\ducpm34\Desktop\04_01_2022\electron-app\node_modules\electron
npm ERR! command failed
npm ERR! command C:\Windows\system32\cmd.exe /d /s /c node install.js
npm ERR! RequestError: self signed certificate in certificate chain
npm ERR!     at ClientRequest.<anonymous> (C:\Users\ducpm34\Desktop\04_01_2022\electron-app\node_modules\got\source\request-as-event-emitter.js:178:14)
npm ERR!     at Object.onceWrapper (node:events:510:26)
npm ERR!     at ClientRequest.emit (node:events:402:35)
npm ERR!     at ClientRequest.origin.emit (C:\Users\ducpm34\Desktop\04_01_2022\electron-app\node_modules\@szmarczak\http-timer\source\index.js:37:11)
npm ERR!     at TLSSocket.socketErrorListener (node:_http_client:447:9)
npm ERR!     at TLSSocket.emit (node:events:390:28)
npm ERR!     at emitErrorNT (node:internal/streams/destroy:157:8)
npm ERR!     at emitErrorCloseNT (node:internal/streams/destroy:122:3)
npm ERR!     at processTicksAndRejections (node:internal/process/task_queues:83:21)

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\ducpm34\AppData\Local\npm-cache\_logs\2022-01-04T07_39_31_143Z-debug.log

How do I fix the RequestError: self signed certificate in certificate chain error?


问:
How to upload data using the new swift async/await methods?
The new features in Swift with async/await allow a better control about the process and a simplification in coding. But I cannot find out how this method can be applied for requests which go above a simple data reading. E.g. I need to pass a parameter in order to get a specific answer from a SQL database in the backend (accessed via php).

At first my code about the "standard" way to start with. This function reads all customer records and stores them into an account-array:

```<code>@available(iOS 15.0, *)
static func getCustomerListFromBackend() async throws -> [Account] {
    let url = URL(string: "https://xxx.de/xxx/getCustomerList.php")!
    let (data, _) = try await URLSession.shared.data(from: url)
    var accounts: [Account] = []
    accounts = try JSONDecoder().decode([Account].self, from: data)
    return accounts
}
</code>```

In order to make my question clear, now a piece of code in which the central statement does not work and exist. In this function I want to check whether a customer exists in the database and I need to pass the emailAddress as a parameter.

```<code>@available(iOS 15.0, *)
static func checkCustomerExistsInBackend(emailAddress: String) async throws -> String {
    let url = URL(string: "https://xxx.de/xxx/checkCustomerexists.php")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    var dataString = "EmailAddress=\(emailAddress)"
    let dataD = dataString.data(using: .utf8)

    // Statement which does not work but for which I need an alternative
    let (data, _) = try await URLSession.shared.upload(request: request, data: dataD)

    let answer = try JSONDecoder().decode(BackendMessage.self, from: data)
    return answer.Message
}
</code>```

Unfortunately there is no statement for URLSession.shared.upload(request: request, data: dataD) Until now (before async/await), I used URLSession.shared.uploadTask(with: request, from: dataD) and then used .resume() to process it. This method however gave me too many problems in controlling the right sequence of tasks in the app. Async/await could simplify this very much as in my first example.

So, is there a way to realize this? Any advice would be appreciated.

答:
you could try using URLComponents  something like:

```<code>func checkCustomerExistsInBackend(emailAddress: String) async throws -> String {
    if let url = URL(string: "https://xxx.de/xxx/checkCustomerexists.php"),
       var components = URLComponents(url: url, resolvingAgainstBaseURL: false) {

        components.queryItems = [URLQueryItem(name: "EmailAddress", value: emailAddress)]

        var request = URLRequest(url: components.url!)
        request.httpMethod = "POST"

        let (data, _) = try await URLSession.shared.data(for: request)

        let answer = try JSONDecoder().decode(BackendMessage.self, from: data)
        return answer.Message
    }
    throw URLError(.badURL)
}
</code>```

Body:
The new features in Swift with async/await allow a better control about the process and a simplification in coding. But I cannot find out how this method can be applied for requests which go above a simple data reading. E.g. I need to pass a parameter in order to get a specific answer from a SQL database in the backend (accessed via php).

At first my code about the "standard" way to start with. This function reads all customer records and stores them into an account-array:

@available(iOS 15.0, *)
static func getCustomerListFromBackend() async throws -> [Account] {
    let url = URL(string: "https://xxx.de/xxx/getCustomerList.php")!
    let (data, _) = try await URLSession.shared.data(from: url)
    var accounts: [Account] = []
    accounts = try JSONDecoder().decode([Account].self, from: data)
    return accounts
}

In order to make my question clear, now a piece of code in which the central statement does not work and exist. In this function I want to check whether a customer exists in the database and I need to pass the emailAddress as a parameter.

@available(iOS 15.0, *)
static func checkCustomerExistsInBackend(emailAddress: String) async throws -> String {
    let url = URL(string: "https://xxx.de/xxx/checkCustomerexists.php")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    var dataString = "EmailAddress=\(emailAddress)"
    let dataD = dataString.data(using: .utf8)

    // Statement which does not work but for which I need an alternative
    let (data, _) = try await URLSession.shared.upload(request: request, data: dataD)

    let answer = try JSONDecoder().decode(BackendMessage.self, from: data)
    return answer.Message
}

Unfortunately there is no statement for URLSession.shared.upload(request: request, data: dataD) Until now (before async/await), I used URLSession.shared.uploadTask(with: request, from: dataD) and then used .resume() to process it. This method however gave me too many problems in controlling the right sequence of tasks in the app. Async/await could simplify this very much as in my first example.

So, is there a way to realize this? Any advice would be appreciated.

Body:
you could try using URLComponents  something like:

func checkCustomerExistsInBackend(emailAddress: String) async throws -> String {
    if let url = URL(string: "https://xxx.de/xxx/checkCustomerexists.php"),
       var components = URLComponents(url: url, resolvingAgainstBaseURL: false) {

        components.queryItems = [URLQueryItem(name: "EmailAddress", value: emailAddress)]

        var request = URLRequest(url: components.url!)
        request.httpMethod = "POST"

        let (data, _) = try await URLSession.shared.data(for: request)

        let answer = try JSONDecoder().decode(BackendMessage.self, from: data)
        return answer.Message
    }
    throw URLError(.badURL)
}


问:
Blackberry: Efficient debugging on device?
I am currently trying to debug a blackberry application on a real device.
I find the setup time to be ludicrous!
Here is my workflow:

Uninstall the application using Blackberry Desktop Manager (BBDM)

it takes about one minute to select the options to uninstall the app...

BBDM needs to connect to the device and load the application list

you need to find and uncheck the application

BBDM takes about 30 seconds to uninstall the application and its submodules

the blackberry bold 9700 now spends 2 minutes rebooting...

Use eclipse to start debugging

eclipse installs the app

wait for the debugger to attach itself to the device

Start the app manually

All in all, a single debugging run can take more than 10 minutes to execute.
If I miss a breakpoint, I have to start all over again.

Is there a way to optimize this workflow to make debugging on a blackberry device more efficient ?

答: I am using Debug as-> Blackberry Device to debug the application on my Blackberry Torch 9800. It is doing OK most of the times although I admit that debugging in blackberry is not as fast as in iPhone(much faster) or Android(just fine).</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Android Studio: Cannot import libraries JUnit and Truth
After creating class for unit tests like in official documentation I imported com.google.common.truth.Truth.assertThat and org.junit.Test libraries, but android studio can't pick it up and shows errors "Cannot resolve symbol "Truth"" and "Cannot resolve symbol "Test"".

After searching the ways to solve this problem I came across a question on StackOverflow that asked similar thing. I did all the things that were recommended over there but I still can't import those classes.

My project build.gradle

```<code>buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.0.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
</code>```

My project module build.gradle

```<code>dependencies {
    testImplementation 'junit:junit:4.13.2'
    testImplementation 'com.google.truth:truth:1.1.3'
}
</code>```

My test class

```<code>import com.google.common.truth.Truth.assertThat;
import org.junit.Test;
</code>```

答:
Android gradle plugin requires java 11 to run.

Please change gradle java plugin to 11 like below screenshot.

Body:
After creating class for unit tests like in official documentation I imported com.google.common.truth.Truth.assertThat and org.junit.Test libraries, but android studio can't pick it up and shows errors "Cannot resolve symbol "Truth"" and "Cannot resolve symbol "Test"".

After searching the ways to solve this problem I came across a question on StackOverflow that asked similar thing. I did all the things that were recommended over there but I still can't import those classes.

My project build.gradle

buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.0.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

My project module build.gradle

dependencies {
    testImplementation 'junit:junit:4.13.2'
    testImplementation 'com.google.truth:truth:1.1.3'
}

My test class

import com.google.common.truth.Truth.assertThat;
import org.junit.Test;


问:
SSIS Error while deploying package The locale identifier (LCID) is not supported by SQL Server
I get this error when deploying a package to SQL 2012 SSISDB catalog:

```<code>A .NET Framework error occurred during execution user-defined routine or aggregate "deploy-project-internal":

System.Data.SqlClient.SqlException: The locale identifier (LCID) 9242 is not supported by SQL Server
</code>```

......

答: Also I had a similar issue with the LCID for the Palestinian State which was added recently to windows and it seems that the SSIS doesn't recognize this LCID. So changing the windows LCID to another one solved the problem (from contorl panel then regions)</p>

Body:
I get this error when deploying a package to SQL 2012 SSISDB catalog:

A .NET Framework error occurred during execution user-defined routine or aggregate "deploy-project-internal":

System.Data.SqlClient.SqlException: The locale identifier (LCID) 9242 is not supported by SQL Server

......


问:
Merge two streams to get result
I have a list of model Config which looks like

```<code>class Config extends Model{
String name;
String type;
JsonNode config;
}

</code>```

On querying the db, I get config for name 'abc' (which is passed by user) and id 'default'. There can be 3 config types (type1, type2, type3)

Requirement: If any config type is missing for the user input, config from 'default' is returned.
For example:
On querying for only name 'abc', I get

```<code>[
  {
    "name": "abc",
    "type": "type1",
    "config": []
  },
  {
    "name": "abc",
    "type": "type2",
    "config": []
  }
]
</code>```
```<code>[
  {
    "name": "default",
    "type": "type1",
    "config": []
  },
  {
    "name": "default",
    "type": "type2",
    "config": []
  }
  {
    "name": "default",
    "type": "type3",
    "config": []
  }
]
</code>```

As config of type3 is missing response should be

```<code>[
  {
    "name": "abc",
    "type": "type1",
    "config": []
  },
  {
    "name": "abc",
    "type": "type2",
    "config": []
  },
  {
    "name": "default",
    "type": "type3",
    "config": []
  }
]
</code>```

What I have done:

I have a map <id, Config>. In a db query, I fetch Config for both id 1 and 0 in a list.

```<code>Map<String, JsonNode> customConfig = configList.stream()
            .filter(o -> o.getOrgId().equals(1))
            .collect(Collectors.toMap(Config::getKey, Config::getValue));
Map<String, JsonNode> defaultConfig = configList.stream()
                .filter(o -> o.getId().equals(0))
                .collect(Collectors.toMap(Config::getKey, Config::getValue));
</code>```

And then I just do

```<code>configList.getOrDefault(type, defaultConfig.get(type));
</code>```

What I want to do:

I want to merge the two streams into a single stream.

What I've tried:
I looked into using groupingBy along with collectingAndThen in collectors but got confused on how to get the final result.

答:
If you are on the same method you can directly filter by the two options:

```<code>Map<String, JsonNode> customConfig = configList.stream()
        .filter(o -> o.getOrgId().equals(1) || o.getOrgId().equals(0))
        .collect(Collectors.toMap(Config::getKey, Config::getValue));
</code>```

Another option is to return a stream and use the concat option:

```<code>Stream<Config> stream1 = configList.stream()
        .filter(o -> o.getOrgId().equals(1));
Stream<Config> stream2 = configList.stream()
            .filter(o -> o.getId().equals(0));
Map<String, JsonNode> config = Stream.concat(stream1, stream2)
            .collect(Collectors.toMap(Config::getKey, Config::getValue));

</code>```

Title: Merge two streams to get result

Body:
I have a list of model Config which looks like

class Config extends Model{
String name;
String type;
JsonNode config;
}

On querying the db, I get config for name 'abc' (which is passed by user) and id 'default'. There can be 3 config types (type1, type2, type3)

Requirement: If any config type is missing for the user input, config from 'default' is returned.
For example:
On querying for only name 'abc', I get

[
  {
    "name": "abc",
    "type": "type1",
    "config": []
  },
  {
    "name": "abc",
    "type": "type2",
    "config": []
  }
]

[
  {
    "name": "default",
    "type": "type1",
    "config": []
  },
  {
    "name": "default",
    "type": "type2",
    "config": []
  }
  {
    "name": "default",
    "type": "type3",
    "config": []
  }
]

As config of type3 is missing response should be

[
  {
    "name": "abc",
    "type": "type1",
    "config": []
  },
  {
    "name": "abc",
    "type": "type2",
    "config": []
  },
  {
    "name": "default",
    "type": "type3",
    "config": []
  }
]

What I have done:

I have a map <id, Config>. In a db query, I fetch Config for both id 1 and 0 in a list.

Map<String, JsonNode> customConfig = configList.stream()
            .filter(o -> o.getOrgId().equals(1))
            .collect(Collectors.toMap(Config::getKey, Config::getValue));
Map<String, JsonNode> defaultConfig = configList.stream()
                .filter(o -> o.getId().equals(0))
                .collect(Collectors.toMap(Config::getKey, Config::getValue));

And then I just do

configList.getOrDefault(type, defaultConfig.get(type));

What I want to do:

I want to merge the two streams into a single stream.

What I've tried:
I looked into using groupingBy along with collectingAndThen in collectors but got confused on how to get the final result.

Body:
If you are on the same method you can directly filter by the two options:

Map<String, JsonNode> customConfig = configList.stream()
        .filter(o -> o.getOrgId().equals(1) || o.getOrgId().equals(0))
        .collect(Collectors.toMap(Config::getKey, Config::getValue));

Another option is to return a stream and use the concat option:

Stream<Config> stream1 = configList.stream()
        .filter(o -> o.getOrgId().equals(1));
Stream<Config> stream2 = configList.stream()
            .filter(o -> o.getId().equals(0));
Map<String, JsonNode> config = Stream.concat(stream1, stream2)
            .collect(Collectors.toMap(Config::getKey, Config::getValue));


问:
INTENT not getting called with training phrases
I have total 4 Dialogflow Intents. They are

Default Welcome Intent ( Events: Welcome, webhook call enabled )

Default Fallback Intent ( Default Fallback Intent: Enabled, webhook call disabled )

goodbye ( Events: actions_intent_CANCEL, intent as end of conv: enabled )

astro (webhok call enabled)

intent named "astro" contains 5 training phrases and its events field is empty. Upon calling out any one phrase from the 5 specified it should respond with normal Text response. As of know I tried using all the 5 phrases and it invokes only "Default Fallback Intent". Below is the small glimpse of my code (index.js)

```<code>.
.
.
function welcome(agent) {
  var request = require('request');
        return new Promise((resolve, reject) => {
                request(options, (error, response, body) => {
          });

  }

  function astro(agent) {
  var request = require('request');
        return new Promise((resolve, reject) => {
          request(astro_options, (error, response, body) => {
      });
  }

let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('astro', astro);
agent.handleRequest(intentMap);
</code>```

答:
So I faced the same issue and I resolved it so I am going to recommend you the same solution maybe it works for you if you are making the same mistake.
So before giving input always keep an eye on the context section of the intent you are trying to test.
It might have some input context, if it does, you need to first use that then you can proceed with the current intent.

For example: you have an intent -> "goodbye", and within this goodbye intent you are having an input context of "welcomeContext".
So now if you directly start with the phrases of goodbye intent it will throw back a default fallback intent.
What you should do is, send a Hi and use welcomeContext intent and then proceed with goodbye intent, this way it should work, and it worked for as I have just started with dialogflow I made this silly mistake and came to know this thing.
let me know if it works for you or not.

Body:
I have total 4 Dialogflow Intents. They are

Default Welcome Intent ( Events: Welcome, webhook call enabled )

Default Fallback Intent ( Default Fallback Intent: Enabled, webhook call disabled )

goodbye ( Events: actions_intent_CANCEL, intent as end of conv: enabled )

astro (webhok call enabled)

intent named "astro" contains 5 training phrases and its events field is empty. Upon calling out any one phrase from the 5 specified it should respond with normal Text response. As of know I tried using all the 5 phrases and it invokes only "Default Fallback Intent". Below is the small glimpse of my code (index.js)

.
.
.
function welcome(agent) {
  var request = require('request');
        return new Promise((resolve, reject) => {
                request(options, (error, response, body) => {
          });

  }

  function astro(agent) {
  var request = require('request');
        return new Promise((resolve, reject) => {
          request(astro_options, (error, response, body) => {
      });
  }

let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('astro', astro);
agent.handleRequest(intentMap);


问:
How to use index and get rid of React Warning: Each child in a list should have a unique "key" prop?
Hello I'm facing this error, question is how to propertly pass index in this component?

Error:

```<code>react-jsx-dev-runtime.development.js:117 Warning: Each child in a list should have a unique "key" prop.
</code>```

Here is the component's code fragment:

```<code>                            {calculatorScreenshots.map((imgUrl: any, index) => {
                                return (
                                    <Zoom>
                                        {props.projectName == 'Calculator' && (
                                            <CardMedia
                                                key={index}
                                                component="img"
                                                height="200"
                                                alt="project picture"
                                                image={imgUrl}
                                            />
                                        )}
                                    </Zoom>
                                );
                            })}
</code>```

答:
You need to add a key props to the element you rendering with map().

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity

In your case, you forgot to add a key={imgUrl} to <Zoom></Zoom> element whereas it's the first element rendered with map()

To turn off this warning, here the solution:

```<code>{calculatorScreenshots.map((imgUrl: String, index) => {
    return (
        <Zoom key={imageUrl}>
            {props.projectName == 'Calculator' && (
                <CardMedia
                  component="img"
                  height="200"
                  alt="project picture"
                  image={imgUrl}
                />
             )}
       </Zoom>
   )})}
</code>```

You were almost there, you simply put the key props for the second mapped element, not for the first one <Zoom></Zoom>.

Happy coding

Some good pieces of information :

The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys

When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort

We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state. Check out Robin Pokorny’s article for an in-depth explanation on the negative impacts of using an index as a key. If you choose not to assign an explicit key to list items then React will default to using indexes as keys.

You can find more information here :

List and Keys with React

Index as a key is an anti-pattern by Robin Pokorny

Why keys are necessary for React?

Body:
Hello I'm facing this error, question is how to propertly pass index in this component?

Error:

react-jsx-dev-runtime.development.js:117 Warning: Each child in a list should have a unique "key" prop.

Here is the component's code fragment:

                            {calculatorScreenshots.map((imgUrl: any, index) => {
                                return (
                                    <Zoom>
                                        {props.projectName == 'Calculator' && (
                                            <CardMedia
                                                key={index}
                                                component="img"
                                                height="200"
                                                alt="project picture"
                                                image={imgUrl}
                                            />
                                        )}
                                    </Zoom>
                                );
                            })}

Body:
You need to add a key props to the element you rendering with map().

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity

In your case, you forgot to add a key={imgUrl} to <Zoom></Zoom> element whereas it's the first element rendered with map()

To turn off this warning, here the solution:

{calculatorScreenshots.map((imgUrl: String, index) => {
    return (
        <Zoom key={imageUrl}>
            {props.projectName == 'Calculator' && (
                <CardMedia
                  component="img"
                  height="200"
                  alt="project picture"
                  image={imgUrl}
                />
             )}
       </Zoom>
   )})}

You were almost there, you simply put the key props for the second mapped element, not for the first one <Zoom></Zoom>.

Happy coding

Some good pieces of information :

The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys

When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort

We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state. Check out Robin Pokorny’s article for an in-depth explanation on the negative impacts of using an index as a key. If you choose not to assign an explicit key to list items then React will default to using indexes as keys.

You can find more information here :

List and Keys with React

Index as a key is an anti-pattern by Robin Pokorny

Why keys are necessary for React?


答:
Use:

```<code>from datetime import datetime as dt
df = pd.DataFrame({'hora_inicio_evento':['00:10:00', '07:19:00', '19:00:01']})
def turno(event):
    early_morning = 0
    morning = 7
    night = 19
    hour = event.hour
    if early_morning <= hour and hour < morning:
      return 'NoiteAnterior'
    elif morning <= hour and hour < night:
      return 'Dia'
    else:
      return 'Noite'
df['turno'] = pd.to_datetime(df['hora_inicio_evento']).apply(turno)
</code>```

Result:

Based on your comment:

```<code>df['turno'] = df['hora_inicio_evento'].apply(turno)
</code>```

Result:

Based on the other comment:

```<code>df = pd.read_excel('time_test.xlsx')
df['turno'] = df['inicio_evento'].apply(turno)
</code>```

The result:

Title: Select string by time

Body:
Use:

from datetime import datetime as dt
df = pd.DataFrame({'hora_inicio_evento':['00:10:00', '07:19:00', '19:00:01']})
def turno(event):
    early_morning = 0
    morning = 7
    night = 19
    hour = event.hour
    if early_morning <= hour and hour < morning:
      return 'NoiteAnterior'
    elif morning <= hour and hour < night:
      return 'Dia'
    else:
      return 'Noite'
df['turno'] = pd.to_datetime(df['hora_inicio_evento']).apply(turno)

Result:

Based on your comment:

df['turno'] = df['hora_inicio_evento'].apply(turno)

Result:

Based on the other comment:

df = pd.read_excel('time_test.xlsx')
df['turno'] = df['inicio_evento'].apply(turno)

The result:


问:
Finding the current volume level of the speaker output in Windows
EDITED: I'm trying to write a sort of audio visualizer and I need to get the current volume of the sound being sent to the speakers. I need the actual volume of the sound, not just the master volume of the device. I've been trying to do it using this but I'm unsure how to implement it. Having called the IAudioCaptureClient::GetBuffer() method, I don't know how to use the resulting data packet to find what I need. The audio is 2 channel, 32 bits per sample. Any help would be greatly appreciated. </p>

答:
not sure if you found it for yourself.
I would start here with the peakmeter info:

https://learn.microsoft.com/en-us/windows/win32/coreaudio/peak-meters


问:
Adding query parameters to URL on HTTP request
I was looking at a few post regrading query parameters in my URL and I couldn't quite find what I was looking for.

So far the external API I am fetching data from requires a specific I will call in this case "tag" parameter when making HTTP request in the browser.

Here is my Post model with a tag defined as a field

```<code>package com.example.blog.post;

import javax.persistence.*;

@Entity
@Table(name = "post")
public class Post{

    @Id
    @GeneratedValue
    private Long id;

    private String tag;

    public Post() {

    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getId() {

        return id;
    }

    public String getTag() {
        return tag;
    }
}
</code>```

And here is my controller class and the "getPosts()" method is where I am fetching the external data but it requires a tag parameter (query parameter) in order to complete the response. How do I incorporate the "tag" query parameter in this case?

```<code>package com.example.blog.post;

import org.springframework.web.bind.annotation.*;
import java.util.*;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import com.example.blog.HttpRequest;

@RestController
@RequestMapping
public class PostController {

    private PostRepository postRepository;

    private RestTemplate restTemplate;

//    @GetMapping("/api/ping")
//    public ResponseEntity<?> ping(){
//        String res = request.body();
//        return new ResponseEntity<>(res,HttpStatus.OK);
//    }

    @GetMapping("/api/posts")
    public ResponseEntity<?> getPosts(@RequestParam(value="tag") String tag){
        try{
            HttpRequest request = HttpRequest.get("https://api.blogs.io/blog/posts").connectTimeout(12000);
            String res = request.body();
            return new ResponseEntity<>(res,HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseEntity<>("Error!,please try again",HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
</code>```

答:
The tag request parameter should be sent to the url. And your getPosts() method tag parameter should be correct as follows.

```<code>getPosts(@RequestParam String tag)
</code>```

value field is used in @RequestAttribute

Body:
I was looking at a few post regrading query parameters in my URL and I couldn't quite find what I was looking for.

So far the external API I am fetching data from requires a specific I will call in this case "tag" parameter when making HTTP request in the browser.

Here is my Post model with a tag defined as a field

package com.example.blog.post;

import javax.persistence.*;

@Entity
@Table(name = "post")
public class Post{

    @Id
    @GeneratedValue
    private Long id;

    private String tag;

    public Post() {

    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getId() {

        return id;
    }

    public String getTag() {
        return tag;
    }
}

And here is my controller class and the "getPosts()" method is where I am fetching the external data but it requires a tag parameter (query parameter) in order to complete the response. How do I incorporate the "tag" query parameter in this case?

package com.example.blog.post;

import org.springframework.web.bind.annotation.*;
import java.util.*;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import com.example.blog.HttpRequest;

@RestController
@RequestMapping
public class PostController {

    private PostRepository postRepository;

    private RestTemplate restTemplate;

//    @GetMapping("/api/ping")
//    public ResponseEntity<?> ping(){
//        String res = request.body();
//        return new ResponseEntity<>(res,HttpStatus.OK);
//    }

    @GetMapping("/api/posts")
    public ResponseEntity<?> getPosts(@RequestParam(value="tag") String tag){
        try{
            HttpRequest request = HttpRequest.get("https://api.blogs.io/blog/posts").connectTimeout(12000);
            String res = request.body();
            return new ResponseEntity<>(res,HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseEntity<>("Error!,please try again",HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

Body:
The tag request parameter should be sent to the url. And your getPosts() method tag parameter should be correct as follows.

getPosts(@RequestParam String tag)

value field is used in @RequestAttribute


问:
Change color of close button in bootstrap modal window
I'm using modal window with boostrap. I've already changed the background and font color, but I did not succed changing the upper right close button to white.

```<code><button type="button" class="close" data-dismiss="modal"><span aria-hidden="true" class="modal_button">×</span><span class="sr-only">Close</span></button>
</code>```

Here's my css attribute

```<code>.modal-header {
  border-top: 1px solid white;
  border-left: 1px solid white;
  border-right: 1px solid white;
  text-align: left;
  font-size: 23px;
  color: white;
  background-color: #261f31;
  border-bottom: 0px;
}
</code>```

I would like to turn the X button in white

答: For Bootstrap 5 you need to add the btn-close-white class</p>

Body:
I'm using modal window with boostrap. I've already changed the background and font color, but I did not succed changing the upper right close button to white.

<button type="button" class="close" data-dismiss="modal">×Close</button>

Here's my css attribute

.modal-header {
  border-top: 1px solid white;
  border-left: 1px solid white;
  border-right: 1px solid white;
  text-align: left;
  font-size: 23px;
  color: white;
  background-color: #261f31;
  border-bottom: 0px;
}

I would like to turn the X button in white


问:
An unhandled exception occurred: The target entry-point "@angular/material/menu"
I am new to angular.After reaching to clientapp folder of my project,I have used command called 'ng serve'.
I am getting an error.
Your global Angular CLI version (12.2.9) is greater than your local version (11.2.18). The local Angular CLI version is used.

To disable this warning use "ng config -g cli.warnings.versionMismatch false".(Yellow color msg)
An unhandled exception occurred: The target entry-point "@angular/material/menu" has missing dependencies:

@angular/cdk/a11y

@angular/cdk/coercion

@angular/cdk/keycodes

@angular/cdk/portal

@angular/cdk/bidi

@angular/cdk/overlay

@angular/cdk/platform

@angular/cdk/scrolling (in red color).
So again I have used npm install command and ng serve.Still getting this error.

What shall I do now?

答:
Your global Angular CLI version (12.2.9) is greater than your local
version (11.2.18). The local Angular CLI version is used.

Angular cli is producing this warning because your project is build with 11.2.18 while your globally installed version is 12.2.9. You can ignore this warning because your project will use locally installed 11.2.18 version present in node-modules folder.

An unhandled exception occurred: The target entry-point
"@angular/material/menu" has missing dependencies:

You are getting this error because some of the modules of @angular/material internally depend on @angular/cdk package.

Try installing @angular/cdk package with:

```<code>npm install --save @angular/cdk
</code>```

If the error still persists, force clean the cache & delete node-modules folder.

```<code>npm cache clear --force
</code>```

After this, run the npm install command. It will download all your project dependencies again.

Body:
Your global Angular CLI version (12.2.9) is greater than your local
version (11.2.18). The local Angular CLI version is used.

Angular cli is producing this warning because your project is build with 11.2.18 while your globally installed version is 12.2.9. You can ignore this warning because your project will use locally installed 11.2.18 version present in node-modules folder.

An unhandled exception occurred: The target entry-point
"@angular/material/menu" has missing dependencies:

You are getting this error because some of the modules of @angular/material internally depend on @angular/cdk package.

Try installing @angular/cdk package with:

npm install --save @angular/cdk

If the error still persists, force clean the cache & delete node-modules folder.

npm cache clear --force

After this, run the npm install command. It will download all your project dependencies again.


问:
Storing Access & Refresh tokens from multiple Providers?
Say I am allowing my users to connect to Facebook, Instagram, Pinterest & Twitter, so they can use their API's. So I get access tokens for all those providers.

From what I've read, my inclination now is to store them in a http-only cookie.

However, with 4 access tokens, would that mean that all 4 access tokens are always being sent on every request?

What would be a secure approach here? Or would I in this case not store them on the client at all?

答:
It depends on the exact architecture of your solution. If you have a backend, and your backend calls these APIs then you can keep those tokens in your backend. They don't have to be kept in the front-end at all. If your front-end needs those tokens (e.g. it is calling these APIs directly), then you have to keep the tokens there, and they have to be readable by your frontend app (so they can't be stored in an HTTP-only cookie).

I would struggle not to have any tokens in the browser. It's best to keep them in the backend.


问:
One dimensional array but multiple string
I want to make a multiple string of array but with just a one dimensional array, Is it possible?

```<code>#include <stdio.h>

int main()
{
    char name1[10];
    char name2[10];

    printf("Enter name1: ");
    scanf("%s", name1);

    printf("Enter name2: ");
    scanf("%s", name2);

    printf("\n%s", name1);
    printf("\n%s", name2);

    return 0;
}
</code>```

I just started to learn array and I wanted to try to get multiple input from user and display only specific of the elements.
This is one of the code I tried before but it does not run.

```<code>int main()
{
    char *name[10];

    int i = 1, input;
    printf("How many days a week: ");
    scanf("%d", &input);

    do{
        printf("enter day %d: ", i);
        scanf("%s", name[i]);
        i++;
    }while(i < input);

    //output wanted
    printf("\n%s", name[0]);
    printf("\n%s", name[4]);

    return 0;
}
</code>```

答:
See this beginner string handling FAQ: Common string handling pitfalls in C programming. Yours is FAQ #3 - you try to store data using a pointer which isn't pointing at a valid memory location.

char *name[10]; is correct as far as it can be used for the name[i] syntax to access a string. However, it is just an array of pointers which don't point to allocated data yet. You need to set these pointers to point somewhere before using them.

One way to do so:

```<code>char name1[100];
char name2[100];
char* name[10] = {name1, name2};
...
scanf("%s", name[i]); // now this is fine
</code>```

Alternatively using dynamic allocation:

```<code>#include <stdlib.h>
...

char* name[10];
for(int i=0; i<10; i++)
{
  name[i] = malloc(100);
  if(name[i]==NULL) { /* handle error */ return 0; }
}
...
scanf("%s", name[i]); // now this is fine
...
for(int i=0; i<10; i++) // cleanup
{
  free(name[i]);
}
</code>```

The advantage of dynamic allocation is that we can realloc a string later in runtime to change the string length.

Body:
I want to make a multiple string of array but with just a one dimensional array, Is it possible?

#include <stdio.h>

int main()
{
    char name1[10];
    char name2[10];

    printf("Enter name1: ");
    scanf("%s", name1);

    printf("Enter name2: ");
    scanf("%s", name2);

    printf("\n%s", name1);
    printf("\n%s", name2);

    return 0;
}

I just started to learn array and I wanted to try to get multiple input from user and display only specific of the elements.
This is one of the code I tried before but it does not run.

int main()
{
    char *name[10];

    int i = 1, input;
    printf("How many days a week: ");
    scanf("%d", &input);

    do{
        printf("enter day %d: ", i);
        scanf("%s", name[i]);
        i++;
    }while(i < input);

    //output wanted
    printf("\n%s", name[0]);
    printf("\n%s", name[4]);

    return 0;
}

Body:
See this beginner string handling FAQ: Common string handling pitfalls in C programming. Yours is FAQ #3 - you try to store data using a pointer which isn't pointing at a valid memory location.

char *name[10]; is correct as far as it can be used for the name[i] syntax to access a string. However, it is just an array of pointers which don't point to allocated data yet. You need to set these pointers to point somewhere before using them.

One way to do so:

char name1[100];
char name2[100];
char* name[10] = {name1, name2};
...
scanf("%s", name[i]); // now this is fine

Alternatively using dynamic allocation:

#include <stdlib.h>
...

char* name[10];
for(int i=0; i<10; i++)
{
  name[i] = malloc(100);
  if(name[i]==NULL) { /* handle error */ return 0; }
}
...
scanf("%s", name[i]); // now this is fine
...
for(int i=0; i<10; i++) // cleanup
{
  free(name[i]);
}

The advantage of dynamic allocation is that we can realloc a string later in runtime to change the string length.


问:
How do I display role members separately from online members?
I searched for my problem in the API Reference, but I didn't find anything.

I want to add a role setting that "Displays role members separately from online members". Even if I can do that manually without programming, I just want to learn and apply it for fun.

This is just a part of my code:

name = discord.Permissions(
    send_messages = True,
    read_messages = True
)

await guild.create_role(
    name = "name",
    colour = discord.Colour(0x000000),
    permissions = name
)
```

答:
You can set the hoist parameter to True when creating your role as mentioned in the documentation.

name = discord.Permissions(send_messages=True, read_messages=True)

await guild.create_role(name="name",colour=discord.Colour(0x000000),permissions=name, hoist=True)
```


问:
Disable button based on variable in other div
I have an html form where you can select multiple days in the form of a button (in the code, these buttons are the one with the ID days). Then, i have a confirm button with the ID book, which should be enabled only if at least one of the days button is selected. How can I check this condition considering i have the variable in another div?
Here is the code:

```<code><ion-card-content>
<ion-label style="display: block;" class="datepicker_middleTitle"><h3>Pick days</h3></ion-label>
<div class="datepicker_generalDaysContainer" >
    <div class="datepicker_daysOfWeekContainer">
        <div *ngFor="let day of componentData.days" class="datepicker_singleDayWeek">
            <p>{{day.letter}}</p>
        </div>
    </div>

    <div class="datepicker_buttonDaysContainer active">
        <ion-button id="days" style="font-weight: bold;" *ngFor="let day of componentData.days" [class]="day.selected ? 'active' : day.occupied ? 'disabled' : ''" (click)="selectDay(day.number, day.occupied)">{{day.number}}</ion-button>
    </div>
</div>
<ion-button id="book" expand="block" class="btn-big" [disabled]="???" (click)="bookDesk()">BOOK DESK</ion-button>
</code>```

答:
On your days buttons you have (click)="selectDay(day.number, day.occupied)">{{day.number}}

So using same method you could store the selected days somewhere, like an array for example.

this.selectedDays = [];
selectDay(number: any, occupied: any) {
  this.selectedDays.push(number);
}
```
<p>I don't see all of your code so be prepared to go add type checkings and refactor where necessary.</p>
<p>We could then check, if we have any dates selected to endable or disable the book buttons.</p>
<pre class="lang-html prettyprint-override"><code><ion-button id="book" expand="block" class="btn-big" [disabled]="selectedDays.length == 0" (click)="bookDesk()">BOOK DESK</ion-button>
</code>```

Body:
I have an html form where you can select multiple days in the form of a button (in the code, these buttons are the one with the ID days). Then, i have a confirm button with the ID book, which should be enabled only if at least one of the days button is selected. How can I check this condition considering i have the variable in another div?
Here is the code:

<ion-card-content>
<ion-label style="display: block;" class="datepicker_middleTitle">
Pick days
</ion-label>

{{day.letter}}

        <ion-button id="days" style="font-weight: bold;" *ngFor="let day of componentData.days" [class]="day.selected ? 'active' : day.occupied ? 'disabled' : ''" (click)="selectDay(day.number, day.occupied)">{{day.number}}</ion-button>

<ion-button id="book" expand="block" class="btn-big" [disabled]="???" (click)="bookDesk()">BOOK DESK</ion-button>

Body:
On your days buttons you have (click)="selectDay(day.number, day.occupied)">{{day.number}}

So using same method you could store the selected days somewhere, like an array for example.

this.selectedDays = [];
selectDay(number: any, occupied: any) {
  this.selectedDays.push(number);
}

I don't see all of your code so be prepared to go add type checkings and refactor where necessary.

We could then check, if we have any dates selected to endable or disable the book buttons.

<ion-button id="book" expand="block" class="btn-big" [disabled]="selectedDays.length == 0" (click)="bookDesk()">BOOK DESK</ion-button>


问:
Android Studio : Cannot resolve symbol "Truth" (Truth library)
After coming across this gist : https://gist.github.com/chemouna/00b10369eb1d5b00401b, I noticed it was using the Google Truth library : https://google.github.io/truth/. So I started by following the procedure to add the library in my build.gradle file in Android Studio:

```<code>buildscript {
  repositories.mavenLocal()
}

dependencies {
  testImplementation "com.google.truth:truth:0.40"
}
</code>```

But when I wanted to add the static imports for Truth’s entry points for my assertions java class:

```<code>import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
</code>```

I got the error that the symbol Truth cannot be resolved.
I tried to rebuild my project and implement the solutions stated here: AndroidTestCompile dependencies not recognized in the imports, mainly running the following gradle tasks:

./gradlew app:dependencies

assembleAndroidTest

but the problem persists.

Any help on that?

Should I actually add these lines in my build.gradle file ? :

```<code> buildscript {
  repositories.mavenLocal()
}
</code>```

if I already have these :

```<code>repositories {
   mavenCentral()
   jcenter()
   google()
}
</code>```

答: As android Gradle plugin requires java 11. Please update Gradle JDK

Body:
After coming across this gist : https://gist.github.com/chemouna/00b10369eb1d5b00401b, I noticed it was using the Google Truth library : https://google.github.io/truth/. So I started by following the procedure to add the library in my build.gradle file in Android Studio:

buildscript {
  repositories.mavenLocal()
}

dependencies {
  testImplementation "com.google.truth:truth:0.40"
}

But when I wanted to add the static imports for Truth’s entry points for my assertions java class:

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;

I got the error that the symbol Truth cannot be resolved.
I tried to rebuild my project and implement the solutions stated here: AndroidTestCompile dependencies not recognized in the imports, mainly running the following gradle tasks:

./gradlew app:dependencies

assembleAndroidTest

but the problem persists.

Any help on that?

Should I actually add these lines in my build.gradle file ? :

 buildscript {
  repositories.mavenLocal()
}

if I already have these :

repositories {
   mavenCentral()
   jcenter()
   google()
}


问:
How important is optimization?
I got into a bit of a debate yesterday with my boss about the proper role of optimization when building software. Essentially, his position was that optimization needs to be a primary concern during the entire process of development.

My opinion is that you need to make the right algorithmic decisions during development, but you should never be counting cycles during development. In fact, I feel so strongly about this I had to walk away from the conversation. I've seen too many bad programming decisions in the name of "optimization", and too much bad code defended with the excuse "this way is faster".

What does the StackOverflow.com community think?

答:
Premature optimization is the root of all evil...There is a fine balance between, but I would say 95% of the time you need to optimize at the end; however, there are decisions you can make early on to help prevent issues. For example assume we are talking about an e-commerce web site. You have a requirement to display the catalog. Now you can grab all 100,000 items and display 50 of them, or you can grab just 50 from the database. These type of decisions should be made up front.

Cycle counting should only be done when a problem has been identified.

OwnerDisplayName: dicroce

Title: How important is optimization?

LastEditorDisplayName: jpalecek

OwnerDisplayName: Josh


问:
How to append values to an Array in Structured text in PLC software like twincat
I have to sorting algorithm to sort out recipes from one of my machines. Is there a way to push/append values into my array?</p>

答:
There is no standard List or similar implementation in the Beckhoff/TwinCAT libraries.

Best choice would be to make your own.
Make a function block containing an array and public method for appending (and other functionality you want).
Internally in the function block you then keep track of which indices are used and which are free.


问:
I don't understand where I made a mistake
I tried this code after documenting myself :

```<code>struct person
{
    int a;
    char s;
};
struct person test;
test.a = 12;
</code>```

And Code::Blocks returns this following error :

error: 'test' does not name a type

Can someone explain this error to me? I found this sample code on the internet! I don't understand my mistake.

Thanks for reading, have a nice day.

答:
To make your code work you need to put it in a function and there should be a main function too.</p>
```<code>struct person
{
    int a;
    char s;
};

int main() // you need to have a main
{
    // code needs to be in a function

    /*struct*/ person test; // struct is not needed
    test.a = 12;

    return 0;
}
</code>```

Body:
I tried this code after documenting myself :

struct person
{
    int a;
    char s;
};
struct person test;
test.a = 12;

And Code::Blocks returns this following error :

error: 'test' does not name a type

Can someone explain this error to me? I found this sample code on the internet! I don't understand my mistake.

Thanks for reading, have a nice day.

Body:
To make your code work you need to put it in a function and there should be a main function too.

struct person
{
    int a;
    char s;
};

int main() // you need to have a main
{
    // code needs to be in a function

    /*struct*/ person test; // struct is not needed
    test.a = 12;

    return 0;
}


问:
Stop Rails Console from loading Test::Unit
I have a model named "Test" (I commented everything out of that model so all that's left is class Test end for debugging purposes) and every time I try instantiating it in the rails console I get an error that the "new" method does not exist for Test:Module.  This error does not occur when instantiating any of my other models, and I think it has to do with the fact that the rails console is loading up Test::Unit or something like that (on a hunch I ran Test.constants and the console returned [:Unit], so I am pretty sure that's the issue).  At any rate, there is no question that some module named Test is being run by the rails console, and I don't want this to happen.  How do I avoid this?  It would be highly inconvenient for me to change me class name to a different value, so if there is any way to resolve this issue that would be great~!

答: You could add a module and have your test class inside of it to avoid that issue. You will then need to address your class like module::class.</p>


问:
What catalog format from webtranslateit.com to select for LinguiJS that will work with plurals?
I am trying to switch from i18next to LinguiJS due to big bundle size of i18next.

I use webtranslateit, which supports these formats.

I currently use i18next json v3 format on webtranslateit:

What format to select on webtranslateit that will work with multiple variations of plurals? (not just singular and single plural)

Thank you

答: Looking at the LinguiJS documentation they seem to work with Gettext PO files and JSON files. Both these formats are supported by the WebTranslateIt tool (Gettext PO and JSON) and they both support plural forms.</p>