问:
Batch Script in Windows 10 to Rename IES Files
I have a batch script to rename a couple of .IES-Files in a folder.
My knowledge is very low on this i cannot figure out why is it not renaming.

I expect that the script is renaming but it won´t do that. I do not know why. May somebody can take a look at it to help me.

```<code>@echo off

:input
set /p root_directory=Enter the path to the root directory:

if not exist "%root_directory%" goto input

for /f "delims=" %%f in ('dir /b /s /a-d "%root_directory%\*.ies"') do (
    for /f "delims=" %%l in ('type "%%f"') do (
        if "%%l" == "[LUMINAIRE]" (
            set "new_name=%%l"
            set "new_name=!new_name:~12!"
            set "new_name=!new_name: =!"
            set "new_name=!new_name:~1,-1!"
            set "new_name=!new_name!.ies"
            if not exist "%%~dpf%new_name%" ren "%%f" "%new_name%"
        )
    )
)

echo Done!
pause
</code>```

Body:
I have a batch script to rename a couple of .IES-Files in a folder.
My knowledge is very low on this i cannot figure out why is it not renaming.

I expect that the script is renaming but it won´t do that. I do not know why. May somebody can take a look at it to help me.

@echo off

:input
set /p root_directory=Enter the path to the root directory:

if not exist "%root_directory%" goto input

for /f "delims=" %%f in ('dir /b /s /a-d "%root_directory%\*.ies"') do (
    for /f "delims=" %%l in ('type "%%f"') do (
        if "%%l" == "[LUMINAIRE]" (
            set "new_name=%%l"
            set "new_name=!new_name:~12!"
            set "new_name=!new_name: =!"
            set "new_name=!new_name:~1,-1!"
            set "new_name=!new_name!.ies"
            if not exist "%%~dpf%new_name%" ren "%%f" "%new_name%"
        )
    )
)

echo Done!
pause


来源: stackexchange

问:
After make an npm update the console shows Error: Module not found: Error: Can't resolve 'angular2-moment'
I was trying to install jquery on my Angular project and after write some jquery dependency on package.json doc and type npm update, the console says Error: Module not found: Error: Can't resolve 'angular2-moment'.

Error occurs in the template of component RegisterComponent.

** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **

× Failed to compile.
✔ Browser application bundle generation complete.

Initial Chunk Files | Names   | Raw Size
main.js             | main    | 83.62 kB |
runtime.js          | runtime |  6.51 kB |

4 unchanged chunks

Build at: 2023-01-10T02:39:00.432Z - Hash: 2a1b1b37176d6913 - Time: 536ms

./src/app/app.module.ts:7:0-47 - Error: Module not found: Error: Can't resolve 'angular2-moment' in 'C:\Users\xxxxxx\Desktop\Proyectos IT\registro_cintas\client\src\app'

Error: src/app/app.component.html:6:34 - error NG8002: Can't bind to 'routerLink' since it isn't a known property of 'a'.

6             class="link-home" [routerLink]="['/home']">

continue...
~~~~~~~~~~~~~~~~~~~~~~~~

I tryed installing ngx-moment, angular2-moment again or uninstalling this last one algo I erase the entire folder and made a git clone from the last working commit but nothing, I think the angular2-moment it's not compatible with my Angular version but I don't know what to do.

ContentLicense: CC BY-SA 4.0

Body:
I was trying to install jquery on my Angular project and after write some jquery dependency on package.json doc and type npm update, the console says Error: Module not found: Error: Can't resolve 'angular2-moment'.

Error occurs in the template of component RegisterComponent.

** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **

× Failed to compile.
✔ Browser application bundle generation complete.

Initial Chunk Files | Names   | Raw Size
main.js             | main    | 83.62 kB |
runtime.js          | runtime |  6.51 kB |

4 unchanged chunks

Build at: 2023-01-10T02:39:00.432Z - Hash: 2a1b1b37176d6913 - Time: 536ms

./src/app/app.module.ts:7:0-47 - Error: Module not found: Error: Can't resolve 'angular2-moment' in 'C:\Users\xxxxxx\Desktop\Proyectos IT\registro_cintas\client\src\app'

Error: src/app/app.component.html:6:34 - error NG8002: Can't bind to 'routerLink' since it isn't a known property of 'a'.

6

continue...
~~~~~~~~~~~~~~~~~~~~~~~~

I tryed installing ngx-moment, angular2-moment again or uninstalling this last one algo I erase the entire folder and made a git clone from the last working commit but nothing, I think the angular2-moment it's not compatible with my Angular version but I don't know what to do.


问:
query planner chooses non-optimal plans for view that is union of tables
I have a PostgreSQL database that is partitioned into multiple schemas, one for each tenant and workspace (the exact meaning of these terms doesn't matter, they're just dimensions of the partition scheme):

```<code>reports/tenant1/workspace1
reports/tenant1/workspace2
reports/tenant2/workspace1
reports/tenant3/workspace1
reports/tenant3/workspace2
reports/tenant3/workspace3
</code>```

Each workspace schema has the same set of tables with identical definitions, and each table includes "_tenant" and "_workspace" columns with the values of its enclosing schema, e.g., tenant1 and workspace1.

In the public schema, there is one view per table definition that unions the tables with that definition across all workspace schemas. For example, the view for "example_table" would be:

```<code>SELECT _tenant, _workspace, column1, column2, column3
FROM "reports/tenant1/workspace1".example_table
WHERE _tenant = 'tenant1' AND _workspace = 'workspace1'
UNION ALL
SELECT _tenant, _workspace, column1, column2, column3
FROM "reports/tenant1/workspace2".example_table
WHERE _tenant = 'tenant1' AND _workspace = 'workspace2'
UNION ALL
SELECT _tenant, _workspace, column1, column2, column3
FROM "reports/tenant2/workspace1".example_table
WHERE _tenant = 'tenant2' AND _workspace = 'workspace1'
UNION ALL
</code>```

Note the "redundant" partition predicates in each SELECT. I added these because it seems to provide a hint to PostgreSQL not to execute queries on tables in unrelated partitions when querying the view with the same predicate. Indeed, EXPLAIN ANALYZE shows "(never executed)" for those queries.

Queries are made from a BI tool to the views, and the BI tool automatically adds predicates on the "_tenant" and "_workspace" columns based on attributes of the logged-in user.

Now that there are 50+ workspaces, I've noticed that queries on the views can have non-optimal plans when compared to equivalent queries on the underlying tables. For example, the following query on the views might use a nested loop join that takes 1 minute:

```<code>SELECT * FROM
(
  SELECT column1, column2, column3
  FROM example_view1
  WHERE _tenant = 'tenant1' AND _workspace = 'workspace1'
) v1
JOIN
(
  SELECT column4, column5, column6
  FROM example_view2
  WHERE _tenant = 'tenant1' AND _workspace = 'workspace1'
) v2
ON v1.column1 = v2.column4
</code>```

Whereas the equivalent query on the underlying tables would use a hash join and complete in under a second:

```<code>SELECT * FROM
(
  SELECT column1, column2, column3
  FROM "reports/tenant1/workspace1".example_table1
  WHERE _tenant = 'tenant1' AND _workspace = 'workspace1'
) v1
JOIN
(
  SELECT column4, column5, column6
  FROM "reports/tenant1/workspace1".example_table2
  WHERE _tenant = 'tenant1' AND _workspace = 'workspace1'
) v2
ON v1.column1 = v2.column4
</code>```

I know the subqueries are pointless, but it's how the BI tool's query builder generates the SQL for the join.

Is there a way to let the query planner know that all tables outside the selected partition won't return results and can be ignored? As I said before, EXPLAIN ANALYZE shows queries are never executed on these tables due to the "redundant" partition predicates in the view definition, but that doesn't seem to be used at planning time.

Body:
I have a PostgreSQL database that is partitioned into multiple schemas, one for each tenant and workspace (the exact meaning of these terms doesn't matter, they're just dimensions of the partition scheme):

reports/tenant1/workspace1
reports/tenant1/workspace2
reports/tenant2/workspace1
reports/tenant3/workspace1
reports/tenant3/workspace2
reports/tenant3/workspace3

Each workspace schema has the same set of tables with identical definitions, and each table includes "_tenant" and "_workspace" columns with the values of its enclosing schema, e.g., tenant1 and workspace1.

In the public schema, there is one view per table definition that unions the tables with that definition across all workspace schemas. For example, the view for "example_table" would be:

SELECT _tenant, _workspace, column1, column2, column3
FROM "reports/tenant1/workspace1".example_table
WHERE _tenant = 'tenant1' AND _workspace = 'workspace1'
UNION ALL
SELECT _tenant, _workspace, column1, column2, column3
FROM "reports/tenant1/workspace2".example_table
WHERE _tenant = 'tenant1' AND _workspace = 'workspace2'
UNION ALL
SELECT _tenant, _workspace, column1, column2, column3
FROM "reports/tenant2/workspace1".example_table
WHERE _tenant = 'tenant2' AND _workspace = 'workspace1'
UNION ALL

Note the "redundant" partition predicates in each SELECT. I added these because it seems to provide a hint to PostgreSQL not to execute queries on tables in unrelated partitions when querying the view with the same predicate. Indeed, EXPLAIN ANALYZE shows "(never executed)" for those queries.

Queries are made from a BI tool to the views, and the BI tool automatically adds predicates on the "_tenant" and "_workspace" columns based on attributes of the logged-in user.

Now that there are 50+ workspaces, I've noticed that queries on the views can have non-optimal plans when compared to equivalent queries on the underlying tables. For example, the following query on the views might use a nested loop join that takes 1 minute:

SELECT * FROM
(
  SELECT column1, column2, column3
  FROM example_view1
  WHERE _tenant = 'tenant1' AND _workspace = 'workspace1'
) v1
JOIN
(
  SELECT column4, column5, column6
  FROM example_view2
  WHERE _tenant = 'tenant1' AND _workspace = 'workspace1'
) v2
ON v1.column1 = v2.column4

Whereas the equivalent query on the underlying tables would use a hash join and complete in under a second:

SELECT * FROM
(
  SELECT column1, column2, column3
  FROM "reports/tenant1/workspace1".example_table1
  WHERE _tenant = 'tenant1' AND _workspace = 'workspace1'
) v1
JOIN
(
  SELECT column4, column5, column6
  FROM "reports/tenant1/workspace1".example_table2
  WHERE _tenant = 'tenant1' AND _workspace = 'workspace1'
) v2
ON v1.column1 = v2.column4

I know the subqueries are pointless, but it's how the BI tool's query builder generates the SQL for the join.

Is there a way to let the query planner know that all tables outside the selected partition won't return results and can be ignored? As I said before, EXPLAIN ANALYZE shows queries are never executed on these tables due to the "redundant" partition predicates in the view definition, but that doesn't seem to be used at planning time.


问:
onFailure: timeout after making 1 or 2 direction requests
I'm trying to make an app with places and directions I have done that but after 1 or 2 direction calls I just get onFailure: timeout and nothing shows on the screen. I am using firebase for markers but that's not the issue also the marker changes to another marker when using direction and even that isn't working anymore any help would be greatly appreciated

everything works but you have to wait like 5 seconds each time you make a routes but that might be the emulator but after 1 or 2 routes it says onFailure: timeout I was expecting it to work as i was following a tutorial but morphing it into my app

It works it works then

it doesn't then it doesnt

this error also only sometimes happens some times I can do a lot of trips and I can re click on it and try doing the direction again and sometimes that works it's really weird

Map Activity

```package au.com.tutorialmaps;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.net.PlacesClient;
import com.google.android.libraries.places.widget.Autocomplete;
import com.google.android.libraries.places.widget.AutocompleteActivity;
import com.google.android.libraries.places.widget.model.AutocompleteActivityMode;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.GeoPoint;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.maps.DirectionsApiRequest;
import com.google.maps.GeoApiContext;
import com.google.maps.PendingResult;
import com.google.maps.android.SphericalUtil;
import com.google.maps.internal.PolylineEncoding;
import com.google.maps.model.DirectionsResult;
import com.google.maps.model.DirectionsRoute;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class MapActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnPolylineClickListener {

    @SuppressLint({"SuspiciousIndentation", "PotentialBehaviorOverride"})
    @Override
    public void onMapReady(GoogleMap googleMap) {
        Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "onMapReady: map is ready");
        mMap = googleMap;

        if (mLocationPermissionsGranted) {
            getDeviceLocation();

            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }

            mMap.setMyLocationEnabled(true);
            mMap.getUiSettings().setMyLocationButtonEnabled(false);
            mMap.getUiSettings().setZoomControlsEnabled(true);
            mMap.getUiSettings().setZoomGesturesEnabled(true);
            mMap.isBuildingsEnabled();
            mMap.setOnPolylineClickListener(this);

            init();
            //mMap.setInfoWindowAdapter(new CustomInfoViewAdapter(this));

            CollectionReference shrinesRef = db.collection("Shrines");
            Query shrine = shrinesRef.whereEqualTo("isShrine", true);

            shrine.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            Log.i(TAG, Objects.requireNonNull(document.getData().get("LatLing")).toString());
                            GeoPoint geoPoint = document.getGeoPoint("LatLing");
                            String name = document.getString("Name");
                            String description = document.getString("Description");
                            if (geoPoint != null && name != null) {
                                LatLng latLng = new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude());
                                Log.i(TAG, "the latLing is   " + latLng);
                                Log.i(TAG, "the name is   " + name);
                                Log.i(TAG, "the description is   " + description);
                                 firebaseMarker = mMap.addMarker(new MarkerOptions()
                                        .position(latLng)
                                        .title(name)
                                        .snippet(description)
                                         );

                            }
                        }
                    }else{
                        Log.w(TAG, "Error getting documents", task.getException());
                    }
                }
            });

            mMap.setOnInfoWindowLongClickListener(new GoogleMap.OnInfoWindowLongClickListener() {
                @Override
                public void onInfoWindowLongClick(@NonNull Marker marker) {

                    final AlertDialog.Builder builder = new AlertDialog.Builder(MapActivity.this);
                    builder.setMessage("More Info or Directions?")
                            .setCancelable(true)
                            .setPositiveButton("Directions", (dialog, id) -> {
                                mSelectedMarker = marker;
                                calculateDirections(mSelectedMarker);
                                dialog.dismiss();
                            })
                            .setNegativeButton("More Info", (dialog, id) -> {
                                dialog.dismiss();
                            });
                    final AlertDialog alert = builder.create();
                    alert.show();

                }
           });

        }
    }

    private void addPolylinesToMap(final DirectionsResult result){
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "run: result routes: " + result.routes.length);
                if (mPolylinesData.size() > 0){
                    for (PolylineData polylineData : mPolylinesData){
                        polylineData.getPolyline().remove();
                    }
                    mPolylinesData.clear();
                    mPolylinesData = new ArrayList<>();
                }
                double duration = 999999999;
                for(DirectionsRoute route: result.routes){
                    Log.d(TAG, "run: leg: " + route.legs[0].toString());
                    List<com.google.maps.model.LatLng> decodedPath = PolylineEncoding.decode(route.overviewPolyline.getEncodedPath());

                    List<LatLng> newDecodedPath = new ArrayList<>();

                    // This loops through all the LatLng coordinates of ONE polyline.
                    for(com.google.maps.model.LatLng latLng: decodedPath){

//                        Log.d(TAG, "run: latlng: " + latLng.toString());

                        newDecodedPath.add(new LatLng(
                                latLng.lat,
                                latLng.lng
                        ));
                    }
                    Polyline polyline = mMap.addPolyline(new PolylineOptions().addAll(newDecodedPath));
                    polyline.setColor(ContextCompat.getColor(MapActivity.this, R.color.grey));
                    polyline.setClickable(true);
                    mPolylinesData.add(new PolylineData(polyline, route.legs[0]));
                    onPolylineClick(polyline);
                    double tempDuration = route.legs[0].duration.inSeconds;
                    if (tempDuration < duration) {
                        duration = tempDuration;
                        onPolylineClick(polyline);

                    }
                    mSelectedMarker.setVisible(false);
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.map_types_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.normal:
                mMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(this, R.raw.daymap));
                mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                break;
            case R.id.hybrid:
                mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                break;
            case R.id.satellite:
                mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
                break;
            case R.id.terrain:
                mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
                break;
            case R.id.normalnight:
                mMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(this, R.raw.nightmap));
                break;
        }
        return true;
    }

    private static final String TAG = "MapActivity";

    private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
    private static final float DEFAULT_ZOOM = 7f;

    //widgets
    private AutoCompleteTextView mSearchText;
    private ImageView mGps;
    private Button mSRearchFiller;

    //vars
    private Boolean mLocationPermissionsGranted = false;
    private GoogleMap mMap;
    private FusedLocationProviderClient mFusedLocationProviderClient;
    private PlacesClient mplacesclient;
    private Autocomplete autocomplete;
    private static int AUTOCOMPLETE_REQUEST_CODE = 1079;
    private FirebaseFirestore db;
    private GeoApiContext mGeoApiContext = null;
    private Location userCurrentLocation;
    private Marker firebaseMarker;
    private ArrayList<PolylineData> mPolylinesData = new ArrayList<>();
    private Marker mSelectedMarker = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        mSRearchFiller = (Button) findViewById(R.id.btn2);
        mGps = (ImageView) findViewById(R.id.ic_gps);
        Places.initialize(getApplicationContext(), "AIzaSyDa-r-kB83q9XM0CjCaRx7uQqSeSxs-m0Q");
        PlacesClient placesClient = Places.createClient(this);
        FirebaseFirestore firestore = FirebaseFirestore.getInstance();
        db = firestore;

        getLocationPermission();

        CollectionReference shrinesRef = firestore.collection("Shrines");

// Create a query against the collection.
        Query query = shrinesRef.whereEqualTo("Name", "Imam Ali");

    }

    public void startAutocompleteActivity(View view) {
        // Start the autocomplete intent.
        Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.OVERLAY, Arrays.asList(Place.Field.ID, Place.Field.NAME))
                .setCountries(Arrays.asList("IQ"))
                .build(this);

        startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                Place place = Autocomplete.getPlaceFromIntent(data);
                Log.i(TAG, "Place:"+ place.getName() + ", " + place.getId());
                LatLng placelatling = place.getLatLng();
                String placetitle = place.getName();
                moveCamera(placelatling, DEFAULT_ZOOM, placetitle);
            }else if (resultCode == AutocompleteActivity.RESULT_ERROR){
                Status status = Autocomplete.getStatusFromIntent(data);
                Log.i(TAG, status.getStatusMessage());
            }else if (resultCode == RESULT_CANCELED) {
                // user has cancelled do nothing
            }
        }
    }

    private void init(){
        Log.d(TAG, "init: initializing");

        mGps.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick: clicked gps icon");
                getDeviceLocation();
            }
        });

    }

    private void getDeviceLocation(){
        Log.d(TAG, "getDeviceLocation: getting the devices current location");

        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        try{
            if(mLocationPermissionsGranted){

                final Task<Location> location = mFusedLocationProviderClient.getLastLocation();
                location.addOnCompleteListener(new OnCompleteListener() {
                    @Override
                    public void onComplete(@NonNull Task task) {
                        if(task.isSuccessful()){
                            Log.d(TAG, "onComplete: found location!");
                            Location currentLocation = (Location) task.getResult();
                            userCurrentLocation = currentLocation;

                            moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
                                    DEFAULT_ZOOM,
                                    "My Location");

                        }else{
                            Log.d(TAG, "onComplete: current location is null");
                            Toast.makeText(MapActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }catch (SecurityException e){
            Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
        }
    }

    private void moveCamera(LatLng latLng, float zoom, String title){
        Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude );
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));

        if(!title.equals("My Location")){
            MarkerOptions options = new MarkerOptions()
                    .position(latLng)
                    .title(title);
            mMap.addMarker(options);

        }

    }

    private void initMap(){
        Log.d(TAG, "initMap: initializing map");
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        mapFragment.getMapAsync(MapActivity.this);
        if (mGeoApiContext == null){
            mGeoApiContext = new GeoApiContext.Builder()
                    .apiKey("AIzaSyAmytqSCGeWxEQMOAeI6SB7nPNH8UayubA")
                    .build();
        }
    }

    private void getLocationPermission(){
        Log.d(TAG, "getLocationPermission: getting location permissions");
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION};

        if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                    COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
                mLocationPermissionsGranted = true;
                initMap();
            }else{
                ActivityCompat.requestPermissions(this,
                        permissions,
                        LOCATION_PERMISSION_REQUEST_CODE);
            }
        }else{
            ActivityCompat.requestPermissions(this,
                    permissions,
                    LOCATION_PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.d(TAG, "onRequestPermissionsResult: called.");
        mLocationPermissionsGranted = false;

        switch (requestCode) {
            case LOCATION_PERMISSION_REQUEST_CODE: {
                if (grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                            mLocationPermissionsGranted = false;
                            Log.d(TAG, "onRequestPermissionsResult: permission failed");
                            return;
                        }
                    }
                    Log.d(TAG, "onRequestPermissionsResult: permission granted");
                    mLocationPermissionsGranted = true;
                    //initialize our map
                    initMap();
                }
            }
        }
    }

    private void hideSoftKeyboard(){
        View view = this.getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager)getSystemService(MapActivity.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    private void calculateDirections(Marker marker){
        Log.d(TAG, "calculateDirections: calculating directions.");

        com.google.maps.model.LatLng destination = new com.google.maps.model.LatLng(
                marker.getPosition().latitude,
                marker.getPosition().longitude
        );
        DirectionsApiRequest directions = new DirectionsApiRequest(mGeoApiContext);

        directions.alternatives(true);
        directions.origin(
                new com.google.maps.model.LatLng(
                        userCurrentLocation.getLatitude(),
                        userCurrentLocation.getLongitude()
                )
        );
        Log.d(TAG, "calculateDirections: destination: " + destination.toString());
        directions.destination(destination).setCallback(new PendingResult.Callback<DirectionsResult>() {
            @Override
            public void onResult(DirectionsResult result) {
                Log.d(TAG, "onResult: routes: " + result.routes[0].toString());
                Log.d(TAG, "onResult: geocodedWayPoints: " + result.geocodedWaypoints[0].toString());

                addPolylinesToMap(result);
            }

            @Override
            public void onFailure(Throwable e) {
                Log.e(TAG, "onFailure: " + e.getMessage() );

            }
        });
    }

    @Override
    public void onPolylineClick(@NonNull Polyline polyline) {
        int index = 0;
        for(PolylineData polylineData: mPolylinesData){
            index++;
            Log.d(TAG, "onPolylineClick: toString: " + polylineData.toString());
            if(polyline.getId().equals(polylineData.getPolyline().getId())){
                polylineData.getPolyline().setColor(ContextCompat.getColor(MapActivity.this, com.google.android.libraries.places.R.color.quantum_googblue));
                polylineData.getPolyline().setZIndex(1);

                LatLng endLocation = new LatLng(
                        polylineData.getLeg().endLocation.lat,
                        polylineData.getLeg().endLocation.lng
                );

                    Marker marker = mMap.addMarker(new MarkerOptions()
                            .position(endLocation)
                            .title("Trip: #" + index)
                            .snippet("Duration: " + polylineData.getLeg().duration)
                    );
                    marker.showInfoWindow();

            }
            else{
                polylineData.getPolyline().setColor(ContextCompat.getColor(MapActivity.this, R.color.grey));
                polylineData.getPolyline().setZIndex(0);
            }
        }
    }
}
```

Body:
I'm trying to make an app with places and directions I have done that but after 1 or 2 direction calls I just get onFailure: timeout and nothing shows on the screen. I am using firebase for markers but that's not the issue also the marker changes to another marker when using direction and even that isn't working anymore any help would be greatly appreciated

everything works but you have to wait like 5 seconds each time you make a routes but that might be the emulator but after 1 or 2 routes it says onFailure: timeout I was expecting it to work as i was following a tutorial but morphing it into my app

It works it works then

it doesn't then it doesnt

this error also only sometimes happens some times I can do a lot of trips and I can re click on it and try doing the direction again and sometimes that works it's really weird

Map Activity

package au.com.tutorialmaps;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.net.PlacesClient;
import com.google.android.libraries.places.widget.Autocomplete;
import com.google.android.libraries.places.widget.AutocompleteActivity;
import com.google.android.libraries.places.widget.model.AutocompleteActivityMode;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.GeoPoint;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.maps.DirectionsApiRequest;
import com.google.maps.GeoApiContext;
import com.google.maps.PendingResult;
import com.google.maps.android.SphericalUtil;
import com.google.maps.internal.PolylineEncoding;
import com.google.maps.model.DirectionsResult;
import com.google.maps.model.DirectionsRoute;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class MapActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnPolylineClickListener {

    @SuppressLint({"SuspiciousIndentation", "PotentialBehaviorOverride"})
    @Override
    public void onMapReady(GoogleMap googleMap) {
        Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "onMapReady: map is ready");
        mMap = googleMap;

        if (mLocationPermissionsGranted) {
            getDeviceLocation();

            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }

            mMap.setMyLocationEnabled(true);
            mMap.getUiSettings().setMyLocationButtonEnabled(false);
            mMap.getUiSettings().setZoomControlsEnabled(true);
            mMap.getUiSettings().setZoomGesturesEnabled(true);
            mMap.isBuildingsEnabled();
            mMap.setOnPolylineClickListener(this);

            init();
            //mMap.setInfoWindowAdapter(new CustomInfoViewAdapter(this));

            CollectionReference shrinesRef = db.collection("Shrines");
            Query shrine = shrinesRef.whereEqualTo("isShrine", true);

            shrine.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            Log.i(TAG, Objects.requireNonNull(document.getData().get("LatLing")).toString());
                            GeoPoint geoPoint = document.getGeoPoint("LatLing");
                            String name = document.getString("Name");
                            String description = document.getString("Description");
                            if (geoPoint != null && name != null) {
                                LatLng latLng = new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude());
                                Log.i(TAG, "the latLing is   " + latLng);
                                Log.i(TAG, "the name is   " + name);
                                Log.i(TAG, "the description is   " + description);
                                 firebaseMarker = mMap.addMarker(new MarkerOptions()
                                        .position(latLng)
                                        .title(name)
                                        .snippet(description)
                                         );

                            }
                        }
                    }else{
                        Log.w(TAG, "Error getting documents", task.getException());
                    }
                }
            });

            mMap.setOnInfoWindowLongClickListener(new GoogleMap.OnInfoWindowLongClickListener() {
                @Override
                public void onInfoWindowLongClick(@NonNull Marker marker) {

                    final AlertDialog.Builder builder = new AlertDialog.Builder(MapActivity.this);
                    builder.setMessage("More Info or Directions?")
                            .setCancelable(true)
                            .setPositiveButton("Directions", (dialog, id) -> {
                                mSelectedMarker = marker;
                                calculateDirections(mSelectedMarker);
                                dialog.dismiss();
                            })
                            .setNegativeButton("More Info", (dialog, id) -> {
                                dialog.dismiss();
                            });
                    final AlertDialog alert = builder.create();
                    alert.show();

                }
           });

        }
    }

    private void addPolylinesToMap(final DirectionsResult result){
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "run: result routes: " + result.routes.length);
                if (mPolylinesData.size() > 0){
                    for (PolylineData polylineData : mPolylinesData){
                        polylineData.getPolyline().remove();
                    }
                    mPolylinesData.clear();
                    mPolylinesData = new ArrayList<>();
                }
                double duration = 999999999;
                for(DirectionsRoute route: result.routes){
                    Log.d(TAG, "run: leg: " + route.legs[0].toString());
                    List<com.google.maps.model.LatLng> decodedPath = PolylineEncoding.decode(route.overviewPolyline.getEncodedPath());

                    List<LatLng> newDecodedPath = new ArrayList<>();

                    // This loops through all the LatLng coordinates of ONE polyline.
                    for(com.google.maps.model.LatLng latLng: decodedPath){

//                        Log.d(TAG, "run: latlng: " + latLng.toString());

                        newDecodedPath.add(new LatLng(
                                latLng.lat,
                                latLng.lng
                        ));
                    }
                    Polyline polyline = mMap.addPolyline(new PolylineOptions().addAll(newDecodedPath));
                    polyline.setColor(ContextCompat.getColor(MapActivity.this, R.color.grey));
                    polyline.setClickable(true);
                    mPolylinesData.add(new PolylineData(polyline, route.legs[0]));
                    onPolylineClick(polyline);
                    double tempDuration = route.legs[0].duration.inSeconds;
                    if (tempDuration < duration) {
                        duration = tempDuration;
                        onPolylineClick(polyline);

                    }
                    mSelectedMarker.setVisible(false);
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.map_types_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.normal:
                mMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(this, R.raw.daymap));
                mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                break;
            case R.id.hybrid:
                mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                break;
            case R.id.satellite:
                mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
                break;
            case R.id.terrain:
                mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
                break;
            case R.id.normalnight:
                mMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(this, R.raw.nightmap));
                break;
        }
        return true;
    }

    private static final String TAG = "MapActivity";

    private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
    private static final float DEFAULT_ZOOM = 7f;

    //widgets
    private AutoCompleteTextView mSearchText;
    private ImageView mGps;
    private Button mSRearchFiller;

    //vars
    private Boolean mLocationPermissionsGranted = false;
    private GoogleMap mMap;
    private FusedLocationProviderClient mFusedLocationProviderClient;
    private PlacesClient mplacesclient;
    private Autocomplete autocomplete;
    private static int AUTOCOMPLETE_REQUEST_CODE = 1079;
    private FirebaseFirestore db;
    private GeoApiContext mGeoApiContext = null;
    private Location userCurrentLocation;
    private Marker firebaseMarker;
    private ArrayList<PolylineData> mPolylinesData = new ArrayList<>();
    private Marker mSelectedMarker = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        mSRearchFiller = (Button) findViewById(R.id.btn2);
        mGps = (ImageView) findViewById(R.id.ic_gps);
        Places.initialize(getApplicationContext(), "AIzaSyDa-r-kB83q9XM0CjCaRx7uQqSeSxs-m0Q");
        PlacesClient placesClient = Places.createClient(this);
        FirebaseFirestore firestore = FirebaseFirestore.getInstance();
        db = firestore;

        getLocationPermission();

        CollectionReference shrinesRef = firestore.collection("Shrines");

// Create a query against the collection.
        Query query = shrinesRef.whereEqualTo("Name", "Imam Ali");

    }

    public void startAutocompleteActivity(View view) {
        // Start the autocomplete intent.
        Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.OVERLAY, Arrays.asList(Place.Field.ID, Place.Field.NAME))
                .setCountries(Arrays.asList("IQ"))
                .build(this);

        startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                Place place = Autocomplete.getPlaceFromIntent(data);
                Log.i(TAG, "Place:"+ place.getName() + ", " + place.getId());
                LatLng placelatling = place.getLatLng();
                String placetitle = place.getName();
                moveCamera(placelatling, DEFAULT_ZOOM, placetitle);
            }else if (resultCode == AutocompleteActivity.RESULT_ERROR){
                Status status = Autocomplete.getStatusFromIntent(data);
                Log.i(TAG, status.getStatusMessage());
            }else if (resultCode == RESULT_CANCELED) {
                // user has cancelled do nothing
            }
        }
    }

    private void init(){
        Log.d(TAG, "init: initializing");

        mGps.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick: clicked gps icon");
                getDeviceLocation();
            }
        });

    }

    private void getDeviceLocation(){
        Log.d(TAG, "getDeviceLocation: getting the devices current location");

        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        try{
            if(mLocationPermissionsGranted){

                final Task<Location> location = mFusedLocationProviderClient.getLastLocation();
                location.addOnCompleteListener(new OnCompleteListener() {
                    @Override
                    public void onComplete(@NonNull Task task) {
                        if(task.isSuccessful()){
                            Log.d(TAG, "onComplete: found location!");
                            Location currentLocation = (Location) task.getResult();
                            userCurrentLocation = currentLocation;

                            moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
                                    DEFAULT_ZOOM,
                                    "My Location");

                        }else{
                            Log.d(TAG, "onComplete: current location is null");
                            Toast.makeText(MapActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }catch (SecurityException e){
            Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
        }
    }

    private void moveCamera(LatLng latLng, float zoom, String title){
        Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude );
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));

        if(!title.equals("My Location")){
            MarkerOptions options = new MarkerOptions()
                    .position(latLng)
                    .title(title);
            mMap.addMarker(options);

        }

    }

    private void initMap(){
        Log.d(TAG, "initMap: initializing map");
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        mapFragment.getMapAsync(MapActivity.this);
        if (mGeoApiContext == null){
            mGeoApiContext = new GeoApiContext.Builder()
                    .apiKey("AIzaSyAmytqSCGeWxEQMOAeI6SB7nPNH8UayubA")
                    .build();
        }
    }

    private void getLocationPermission(){
        Log.d(TAG, "getLocationPermission: getting location permissions");
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION};

        if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                    COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
                mLocationPermissionsGranted = true;
                initMap();
            }else{
                ActivityCompat.requestPermissions(this,
                        permissions,
                        LOCATION_PERMISSION_REQUEST_CODE);
            }
        }else{
            ActivityCompat.requestPermissions(this,
                    permissions,
                    LOCATION_PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.d(TAG, "onRequestPermissionsResult: called.");
        mLocationPermissionsGranted = false;

        switch (requestCode) {
            case LOCATION_PERMISSION_REQUEST_CODE: {
                if (grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                            mLocationPermissionsGranted = false;
                            Log.d(TAG, "onRequestPermissionsResult: permission failed");
                            return;
                        }
                    }
                    Log.d(TAG, "onRequestPermissionsResult: permission granted");
                    mLocationPermissionsGranted = true;
                    //initialize our map
                    initMap();
                }
            }
        }
    }

    private void hideSoftKeyboard(){
        View view = this.getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager)getSystemService(MapActivity.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    private void calculateDirections(Marker marker){
        Log.d(TAG, "calculateDirections: calculating directions.");

        com.google.maps.model.LatLng destination = new com.google.maps.model.LatLng(
                marker.getPosition().latitude,
                marker.getPosition().longitude
        );
        DirectionsApiRequest directions = new DirectionsApiRequest(mGeoApiContext);

        directions.alternatives(true);
        directions.origin(
                new com.google.maps.model.LatLng(
                        userCurrentLocation.getLatitude(),
                        userCurrentLocation.getLongitude()
                )
        );
        Log.d(TAG, "calculateDirections: destination: " + destination.toString());
        directions.destination(destination).setCallback(new PendingResult.Callback<DirectionsResult>() {
            @Override
            public void onResult(DirectionsResult result) {
                Log.d(TAG, "onResult: routes: " + result.routes[0].toString());
                Log.d(TAG, "onResult: geocodedWayPoints: " + result.geocodedWaypoints[0].toString());

                addPolylinesToMap(result);
            }

            @Override
            public void onFailure(Throwable e) {
                Log.e(TAG, "onFailure: " + e.getMessage() );

            }
        });
    }

    @Override
    public void onPolylineClick(@NonNull Polyline polyline) {
        int index = 0;
        for(PolylineData polylineData: mPolylinesData){
            index++;
            Log.d(TAG, "onPolylineClick: toString: " + polylineData.toString());
            if(polyline.getId().equals(polylineData.getPolyline().getId())){
                polylineData.getPolyline().setColor(ContextCompat.getColor(MapActivity.this, com.google.android.libraries.places.R.color.quantum_googblue));
                polylineData.getPolyline().setZIndex(1);

                LatLng endLocation = new LatLng(
                        polylineData.getLeg().endLocation.lat,
                        polylineData.getLeg().endLocation.lng
                );

                    Marker marker = mMap.addMarker(new MarkerOptions()
                            .position(endLocation)
                            .title("Trip: #" + index)
                            .snippet("Duration: " + polylineData.getLeg().duration)
                    );
                    marker.showInfoWindow();

            }
            else{
                polylineData.getPolyline().setColor(ContextCompat.getColor(MapActivity.this, R.color.grey));
                polylineData.getPolyline().setZIndex(0);
            }
        }
    }
}


问:
Jetpack Compose how to change Text break strategy?
How to change the way compose Text() breaks text? I want it to be broken in spaces, but not "//seed" into "//" and "seed".</p>


问:
How to identify a user login from a new device
I am working on a functionality to send an email to user whenever a they log in to my website with a new device. For example if a user logged in to their account from iOS app, notify them that a new device login is detected. If at a later point, same user logs in from web browser, send another notification that a new device login is detected.

I came across UIDevice uniqueIdentifier deprecated - What to do now? and Is there a unique Android device ID?.

I wanted to confirm few things:

Does UIDeviceIDentifierForVendor for iOS change with iOS updates and app version updates?

A unique Device id - (UIDeviceIDentifierForVendor for iOS - https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor and IMEI for android(since hardware identifier would be sufficient for our use-case) - https://developer.android.com/training/articles/user-data-ids should be sufficient for my use-case.

Is there any similar way to uniquely identify a web browser or is a persistent cookie the only option to uniquely identify a web browser - Using cookies with Android volley library?

Note: Feel free to suggest any other better way to uniquely identify user devices(if any).

I looked through different questions on stack overflow and browsed through different blogs describing Device fingerprinting and offering services to get a device fingerprint.

I'm expecting to find the best practices around uniquely identifying devices and methods used widely for uniquely identifying user devices on iOs, Android and Web browsers.


问:
How to fix R "expected ',' after expression" on every line?
At least half of my lines in my rmd contains the error of "expected ',' after expression", however the code runs perfectly fine with no issues

I tried:

copying and pasting the code to a new code block

retyping the code manually instead of using copy/paste from a code cheat sheet

updating R and Rstudio as well as packages associated with the code

I have not been able to find any related help documentation on this matter


问:
How to get the first value and remove all duplicate value in data studio
I'm trying to create a table to show emails by country in data studio but there are many duplicate emails displayed.

Country
Email
Date Created

Country A
Email A
Jan 1, 2022

Country A
Email B
Jan 12, 2022

Country A
Email C
Jan 15, 2022

Country B
Email A
Jan 12, 2022

Country B
Email D
Jan 20, 2022

Country B
Email E
Jan 21, 2022

Country C
Email F
Jan 12, 2022

Country C
Email D
Feb 02, 2022

Country C
Email B
Feb 03, 2022

I would like to keep the first generated email and remove all duplicate emails, like that:

Country
Email
Date Created

Country A
Email A
Jan 1, 2022

Country A
Email B
Jan 12, 2022

Country A
Email C
Jan 15, 2022

Country B
Email D
Jan 20, 2022

Country B
Email E
Jan 21, 2022

Country C
Email F
Jan 12, 2022

Can someone help me?

Thanks,


问:
How to import a file from a subdirectory when that file imports another file from that subdirectory?
Here is a minimal example of the problem I'm facing.

I have a file named main.py in a folder. This is the entry point for my program, and is the file I'd like to simply double-click to run my program.

I also have a directory called "functions_for_main" in the same folder. Within functions_for_main, I have two files. Here's a visual for the directory layout:

```<code>main.py
functions_for_main/__init__.py (empty file)
functions_for_main/file1.py
functions_for_main/file2.py
</code>```

File contents:

main.py:

```<code>import functions_for_main.file2 as file2

print(file2.f(2))
</code>```

file1.py:

```<code>def f(x):
    return x**2
</code>```

file2.py:

```<code>import file1

def f(x):
    return file1.f(x)+1
</code>```

When I run main.py, it fails with traceback

```<code>Traceback (most recent call last):
  File "C:\temp\py_folder_problem\main.py", line 1, in <module>
    import functions_for_main.file2 as file2
  File "C:\temp\py_folder_problem\functions_for_main\file2.py", line 1, in <module>
    import file1
ModuleNotFoundError: No module named 'file1'
</code>```

Note that if I run file2.py from its directory (e.g., by clicking on it), it works as expected.

Now, if I change the first line of file2.py to:

```<code>from . import file1
</code>```

then main.py works as expected, but I can no longer run file2.py (from its directory) by double-clicking on it: That fails on line 1 with error message

ImportError: cannot import name 'file1'.

How can I fix this? I need to be able to run both main.py and file2.py by double-clicking on them.

I have tried adding or removing __init__.py files and using __all__, as suggested in other answers.

I have also tried changing the first line of file2.py to

```<code>from functions_for_main import file1
</code>```

and that has the same effect as from . import file1: main.py can be run by double-click, but file2.py cannot. I don't have much experience with non-flat directory structures in python, and I really need some help.

Body:
Here is a minimal example of the problem I'm facing.

I have a file named main.py in a folder. This is the entry point for my program, and is the file I'd like to simply double-click to run my program.

I also have a directory called "functions_for_main" in the same folder. Within functions_for_main, I have two files. Here's a visual for the directory layout:

main.py
functions_for_main/__init__.py (empty file)
functions_for_main/file1.py
functions_for_main/file2.py

File contents:

main.py:

import functions_for_main.file2 as file2

print(file2.f(2))

file1.py:

def f(x):
    return x**2

file2.py:

import file1

def f(x):
    return file1.f(x)+1

When I run main.py, it fails with traceback

Traceback (most recent call last):
  File "C:\temp\py_folder_problem\main.py", line 1, in <module>
    import functions_for_main.file2 as file2
  File "C:\temp\py_folder_problem\functions_for_main\file2.py", line 1, in <module>
    import file1
ModuleNotFoundError: No module named 'file1'

Note that if I run file2.py from its directory (e.g., by clicking on it), it works as expected.

Now, if I change the first line of file2.py to:

from . import file1

then main.py works as expected, but I can no longer run file2.py (from its directory) by double-clicking on it: That fails on line 1 with error message

ImportError: cannot import name 'file1'.

How can I fix this? I need to be able to run both main.py and file2.py by double-clicking on them.

I have tried adding or removing __init__.py files and using __all__, as suggested in other answers.

I have also tried changing the first line of file2.py to

from functions_for_main import file1

and that has the same effect as from . import file1: main.py can be run by double-click, but file2.py cannot. I don't have much experience with non-flat directory structures in python, and I really need some help.


问:
Makefile: Unterminated String
I have the following Makefile and I keep getting /bin/sh: 1: Syntax error: Unterminated quoted string errors:

```<code>BASE=/mnt/c/Users/kilgore/scripts
SCRIPTS=$(BASE)/scripts
CSV=$(BASE)/csv

DIR=
QUOTED_DIR := $(patsubst %, "%", $(DIR))
REPORTS=./$(firstword $(subst ., ,$(subst /, ,$(QUOTED_DIR))))/reports

SH_INV=$(SCRIPTS)/inventory.sh
PY_INV=$(SCRIPTS)/filecheck.py
CSV_NAME=$(shell echo "$(DIR)" | sed -r "s/[[:punct:][:space:]]//g")

.PHONY: peek csv scan

peek:
        find "$(DIR)"* -maxdepth 0 -type d -exec sh -c 'echo -n "{}: "; find "{}" -type f -print | wc -l' \;

scan:
        bash $(SH_INV) "$(DIR)"

dir:
        @echo "$(DIR)"
        @echo $(REPORTS)

INVENTORY=$(CSV)/$(CSV_NAME)_inventory.csv
REPORT=$(CSV_NAME)_inventory.xlsx

$(INVENTORY):
        bash $(SH_INV) "$(DIR)" >$@

$(REPORT): $(INVENTORY)
        unoconv -d spreadsheet -f xlsx -i FilterOptions=9,34 -o "$(REPORTS)/$(REPORT)" $<

report: $(REPORT)

report2:
        python3 $(PY_INV) -f "$(REPORTS)/$(REPORT)"
</code>```

If I remove quotes for guarding against directories with spaces, it goes away. However, I have directories with spaces.

How can I process directories with spaces and get rid of the unterminated error?

Title: Makefile: Unterminated String

Body:
I have the following Makefile and I keep getting /bin/sh: 1: Syntax error: Unterminated quoted string errors:

BASE=/mnt/c/Users/kilgore/scripts
SCRIPTS=$(BASE)/scripts
CSV=$(BASE)/csv

DIR=
QUOTED_DIR := $(patsubst %, "%", $(DIR))
REPORTS=./$(firstword $(subst ., ,$(subst /, ,$(QUOTED_DIR))))/reports

SH_INV=$(SCRIPTS)/inventory.sh
PY_INV=$(SCRIPTS)/filecheck.py
CSV_NAME=$(shell echo "$(DIR)" | sed -r "s/[[:punct:][:space:]]//g")

.PHONY: peek csv scan

peek:
        find "$(DIR)"* -maxdepth 0 -type d -exec sh -c 'echo -n "{}: "; find "{}" -type f -print | wc -l' \;

scan:
        bash $(SH_INV) "$(DIR)"

dir:
        @echo "$(DIR)"
        @echo $(REPORTS)

INVENTORY=$(CSV)/$(CSV_NAME)_inventory.csv
REPORT=$(CSV_NAME)_inventory.xlsx

$(INVENTORY):
        bash $(SH_INV) "$(DIR)" >$@

$(REPORT): $(INVENTORY)
        unoconv -d spreadsheet -f xlsx -i FilterOptions=9,34 -o "$(REPORTS)/$(REPORT)" $<

report: $(REPORT)

report2:
        python3 $(PY_INV) -f "$(REPORTS)/$(REPORT)"

If I remove quotes for guarding against directories with spaces, it goes away. However, I have directories with spaces.

How can I process directories with spaces and get rid of the unterminated error?


问:
Client-server multithreading C - sending a warning to client when max connections is reached
My question is - is it possible to send the client a warning when max connections is reached, before accepting the connection.

E
verything is working fine, i dont have a problem in the interaction once the connection is accepted, but when the max connection is reached nothing happens, and i need to send a warning.
For context, this is what i have so far:

(thread)

```<code>void* tratar_lig(void * socket_fd){

int val_sem;

sem_getvalue(&semaforo,&val_sem);

if (val_sem <= 0) {
    char *aviso = "xxxxxxxx.\n";
    send(*(int*)socket_fd, aviso, sizeof(aviso), 0 );
}

sem_wait(&semaforo);

int end = 1;
    do{

            struct sockaddr_in nome_cliente;
            socklen_t cliente_nome_len;
            int cliente_socket_fd;
            cliente_socket_fd = accept(*(int*)socket_fd, (structsockaddr*)&nome_cliente,&cliente_nome_len);

... dealing with the messages until client types end... close(cliente_socket_fd);

        } while (end != 0);

        sem_post(&semaforo);

        pthread_exit(NULL); .........

</code>```

Body:
My question is - is it possible to send the client a warning when max connections is reached, before accepting the connection.

E
verything is working fine, i dont have a problem in the interaction once the connection is accepted, but when the max connection is reached nothing happens, and i need to send a warning.
For context, this is what i have so far:

(thread)

void* tratar_lig(void * socket_fd){

int val_sem;

sem_getvalue(&semaforo,&val_sem);

if (val_sem <= 0) {
    char *aviso = "xxxxxxxx.\n";
    send(*(int*)socket_fd, aviso, sizeof(aviso), 0 );
}

sem_wait(&semaforo);

int end = 1;
    do{

            struct sockaddr_in nome_cliente;
            socklen_t cliente_nome_len;
            int cliente_socket_fd;
            cliente_socket_fd = accept(*(int*)socket_fd, (structsockaddr*)&nome_cliente,&cliente_nome_len);

... dealing with the messages until client types end... close(cliente_socket_fd);

        } while (end != 0);

        sem_post(&semaforo);

        pthread_exit(NULL); .........


问:
Bug - "Copied" toast notification when opening my app - Android 13 devices
I'm working on an app and whenever I open it, there's a "Copied" toast notification pops up.  It doesn't actually copy any content to clipboard. Please see link to screenshot here.

There're people online talking about workarounds  (KDE Connect, etc.) but those are for their own devices as users. This behavior doesn't happen on other apps so I suspect certain setting in my app leads to this.

I'm new to mobile development so appreciate if any direction suggested so that I could investigate my app setting further.


问:
Safari web extension content script's runtime.Port won't post message after extension was re-enabled
I am developing an extension that lets web pages and extensions exchange data. And there's a user scenario like the one below.

User opens a website that matches the content script list.

The user can use the web page normally (The content script and extension were working).

The user disabled the extension.

Webpage must notify the user to enable the extension in order to let the web page function properly.

The user re-enables the extension.

The webpage can reconnect itself to the extension without requiring the user to reload the page.

I've found that when the user disabled the extension, the content script can keep working. And when the user re-enabled the extension. The background will re-inject a new content script to the web page. However, the new content script seems to not have the ability to postMessage to the extension.

How can I retrieve the connection of a disconnected web page to the extension, and destroy the old/orphaned content script to prevent it from working?

PS. By the way, in Chrome. I can listen to onDisconnect event of the port and do clean-up of the content script but I won't get any event from onDisconnect on Safari. Am I doing it wrong?


问:
GCP Quota for Multiple Spot/Preemptible GPUs into a Single Region is Always Denied
I am trying to build deep neural network models natural for language processing models like GPT2 or BERT.

The request for GPUS_ALL_REGIONS is partially approved for 4 GPUs, I want to use multiple GPUs (at most 4) in a single instance.

However, all requests which assign more than 2 PREEMPTIBLE_NVIDIA_{A100 or V100}_GPUS (i.e. spot or preemptible) into a single region are denied.

How could I obtain quote for multiple spot GPUs in a single region?

What I did so far:

Checked billing account and credit card is correctly registered.

Confirmed not to log-in as a free trial user.

Repeated to send Quota Request many times for various regions and various GPU types(A100, V100, T4, P100)

Confirmed to log-in gcloud auth log-in as the account of 1.

As a result, I expect:

The number of GPUs “1” is increased into 4 for each single region.

GPUS_ALL_REGIONS is increased into 4 times of the number of regions.

The following gcloud-cli would be successfully executed with ACCELERATOR=="count="${NUM_GPUS}",type=nvidia-tesla-a100"

gcloud compute instances create ${VM_NAME} --preemptible \
    --zone ${ZONE} \
    --machine-type ${MACHINE_TYPE} \
    --network-interface=${NETWORK_INTERFACE} \
    --maintenance-policy=TERMINATE \
    --provisioning-model=SPOT \
    --service-account="**********@developer.gserviceaccount.com" \
    --accelerator=${ACCELERATOR} \
    --enable-display-device --tags=http-server,https-server \
    --create-disk=auto-delete=yes,boot=yes,device-name=instance-1,image=projects/debian-cloud/global/images/debian-11-bullseye-v20221206,mode=rw,size=${BOOT_DISK_SIZE},type=projects/${PROJECT_NAME}/zones/${ZONE}/diskTypes/${BOOT_DISK_TYPE} \
    --image-project ${IMAGE_PROJECT} \
    --image-family ${IMAGE_FAMILY} \
    --no-shielded-secure-boot --shielded-vtpm --shielded-integrity-monitoring --reservation-affinity=any \
    --threads-per-core=2 --visible-core-count=6 \

```


问:
Can Private Certificate be used in Azure AD CBA?
I was able to register the Root certificate with Azure, but the certificate login does not work.
Is it possible to use CBA with a Private certificate?

I checked the Microsoft help page but could not find it. Can someone please tell me what to do?

RootCA, InterCA, and Client Certificate were created.
Client Certificate is signed by InterCA.


问:
Drag and Drop items in a lazyvgrid/lazyhgrid
pretty new here, and to coding in general. I actually want to comment on another post, but I don't have enough reputation :(

I'm trying to drag and drop rearrange a lazyVgrid.

I tested this, and indeed it works for a list, but it doesn't work for a LVG.

The hold and drag still works, but it doesn't affect the other times, they stay where they are and you can't place your item anywhere - it just goes back to it's original position.

I had to comment out .onDelete as I need a function for it, but I don't think that's causing the problem, but it still worked as a list.

I've tried a few other solutions on here but can't seem to crack it.

I'm also a little confused about how to reorder items, and have them stay in the new position when I return to the view.

```<code>    let book: Book
    let books: [Book]

    @State private var selected: Book? = nil

    let spacing: CGFloat = 10

    var gridItems: [GridItem] {
        [GridItem(.adaptive(minimum: 180))]
    }

    var body: some View {

            LazyVGrid(columns: gridItems,
                      spacing: spacing
            ) {
                ForEach(books) { item in
                    Group { // Container of a row
                        Button {
                            selected = item
                        } label: {
                            BookTileModel(book: item)
                        }
                    }
                    .onDrag { // mean drag a row container
                        return NSItemProvider()
                    }
                }
//              .delete(perform: deleteItems)
                .onMove(perform: move)
        }
    }
}

struct TestView_Previews: PreviewProvider {
    static var previews: some View {
        TestView(book: books[1], books: books)
    }
}

func move(from source: IndexSet, to destination: Int) {
    books.move(fromOffsets: source, toOffset: destination )
}

struct Book: Hashable, Codable, Identifiable {

    var id: Int
    var series: String
    var title: String?
    var issue: String
    var volume: String
    var storyArc: String?
    var description: String?
    var favorite: Bool?
    var read: Int?
    var downloaded: Bool?

    private var imageName: String
    var image: Image {
        Image(imageName)
    }

    private var publisherLogo: String
    var logo: Image {
        Image(publisherLogo)
    }

}
</code>```

Body:
pretty new here, and to coding in general. I actually want to comment on another post, but I don't have enough reputation :(

I'm trying to drag and drop rearrange a lazyVgrid.

I tested this, and indeed it works for a list, but it doesn't work for a LVG.

The hold and drag still works, but it doesn't affect the other times, they stay where they are and you can't place your item anywhere - it just goes back to it's original position.

I had to comment out .onDelete as I need a function for it, but I don't think that's causing the problem, but it still worked as a list.

I've tried a few other solutions on here but can't seem to crack it.

I'm also a little confused about how to reorder items, and have them stay in the new position when I return to the view.

    let book: Book
    let books: [Book]

    @State private var selected: Book? = nil

    let spacing: CGFloat = 10

    var gridItems: [GridItem] {
        [GridItem(.adaptive(minimum: 180))]
    }

    var body: some View {

            LazyVGrid(columns: gridItems,
                      spacing: spacing
            ) {
                ForEach(books) { item in
                    Group { // Container of a row
                        Button {
                            selected = item
                        } label: {
                            BookTileModel(book: item)
                        }
                    }
                    .onDrag { // mean drag a row container
                        return NSItemProvider()
                    }
                }
//              .delete(perform: deleteItems)
                .onMove(perform: move)
        }
    }
}

struct TestView_Previews: PreviewProvider {
    static var previews: some View {
        TestView(book: books[1], books: books)
    }
}

func move(from source: IndexSet, to destination: Int) {
    books.move(fromOffsets: source, toOffset: destination )
}

struct Book: Hashable, Codable, Identifiable {

    var id: Int
    var series: String
    var title: String?
    var issue: String
    var volume: String
    var storyArc: String?
    var description: String?
    var favorite: Bool?
    var read: Int?
    var downloaded: Bool?

    private var imageName: String
    var image: Image {
        Image(imageName)
    }

    private var publisherLogo: String
    var logo: Image {
        Image(publisherLogo)
    }

}


问:
How to filter words in text columns using pandas .query?
There is a way to filter in a df column only the rows with a especific word inside the text, like function 'str.contains' just using the .query function ?

This is the code i have:

```<code>def filter(self):

    build_query = ""

    if self.lineEdit_name.Text():
        build_query += f'& "{self.lineEdit_name.Text()}" in `name`'
    if self.lineEdit_description.Text():
        build_query += f'& "{self.lineEdit_description.Text()}" in `desc`'
    if self.comboBox_section.currentText():
        build_query += f'& "{self.comboBox_section.currentText()}" in `section`'

    if build_query:
        self.queried_df = self.df.query(build_query[1:])
    else:
        self.queried_df = self.df
</code>```

I wanted to search in the description column for keywords.

Body:
There is a way to filter in a df column only the rows with a especific word inside the text, like function 'str.contains' just using the .query function ?

This is the code i have:

def filter(self):

    build_query = ""

    if self.lineEdit_name.Text():
        build_query += f'& "{self.lineEdit_name.Text()}" in `name`'
    if self.lineEdit_description.Text():
        build_query += f'& "{self.lineEdit_description.Text()}" in `desc`'
    if self.comboBox_section.currentText():
        build_query += f'& "{self.comboBox_section.currentText()}" in `section`'

    if build_query:
        self.queried_df = self.df.query(build_query[1:])
    else:
        self.queried_df = self.df

I wanted to search in the description column for keywords.


问:
How to investigate how the memory in active_file is used for a process
I'm running my process in a Linux container. The memory usage (I believe that is the same value we will get by running 'docker stats') in our dashboard (memory usage dashboard) is about 1GB, but the sum of RSS in 'ps aux' is less than 350MB.

Checked /sys/fs/cgroups/memory/memory.stat, active_file is about 58MB before(and right after) my process runs, and it is about 599MB several hours after my process runs.(memory.stat comparison)

My questions are

is active_file the cache used for reading/writing file? If not, where I can find the info about how Linux use this kind of memory and for what purpose?

how to investigate how the memory in active_file is used by my process? I try to reduce it.

I'm new to Linxu. I tried to know how 'docker stats' calculate memory usage, in our case, it should be memory.usage_in_bytes - total_inactive_file in memory.stat. Memory usage should include total_active_file.

active_file is the number of bytes of file backed memory on active LRU list. But I do not really understand what file backed memory and active LRU list are, how Linux use this kind of memory, and for what.

If active_file is huge, how to investigate how the memory is used. I do not find any info about it.


问:
direnv cannot find .envrc file even it does exist
I set up a virtual environment for a Django-React project. I have created the .bashrc in the user home directory, and .envrc file in the root folder of the project repo. But when I tried 'direnv allow' it always return '.envrc does not exit' with a weird referenced folder path. Can someone please help?
direnv allow error
direnv status

I'm doing it on Windows 11.

I tried to re-install everything and change the position of the folder from E to C driver. I also tried to rename the folder to anything else to see if any of it results in the weird folder path. But the error message remains.


问:
Dropzone.js | How to validate with different `maxFileSize` for images and videos?
I need to validate the maximum file limit of images and videos with different limits when it is added to the dropzone. For example, the maximum file limit for the image should be 2MB and for video, it should be 100MB.

Note: The framework I use is meteor.js.

How to achieve this in dropzone.js?


问:
Why there are Nullable view and NonNull view in same xm file
I use viewbinding in Activity

```<code>private val binding: ActivityThirdPartyRedirectBinding by lazy { ActivityThirdPartyRedirectBinding.inflate(LayoutInflater.from(this)) }
</code>```

but somehow there are Nullable view and NonNull view

confirmView and llLoading are both ConstraintLayout but return different view?

I have tried invalid cache and clean and rebuild but the problem is still there.

How to solve it?

Body:
I use viewbinding in Activity

private val binding: ActivityThirdPartyRedirectBinding by lazy { ActivityThirdPartyRedirectBinding.inflate(LayoutInflater.from(this)) }

but somehow there are Nullable view and NonNull view

confirmView and llLoading are both ConstraintLayout but return different view?

I have tried invalid cache and clean and rebuild but the problem is still there.

How to solve it?


问:
Admob issue - "Ads Disguised as Content - Must fix"
I have a policy violation that says "Ads Disguised as Content - Must fix", I am not really sure why I am seeing this.

I have native advanced, interstitial, and appOpen admob ads in the app.

The native advanced were designed to follow the recycler view item design and after seeing this policy violation message, I have removed the ad unit.

The interstitial is placed in between a view transition at the click of a button

The appOpen on opening the app, alternate times

Has anyone here found a similar issue or know more about this violation of the policy? Any suggestions?


问:
Opening a page when clicking on an Android notification using MAUI and Shiny.Notifications
I have a .NET MAUI app that tests notifications using Shiny.Notifications and the Community.Toolkit.Mvvm.
I know that the MAUI version is in Alpha but I am desperate.
I have the notification appearing and when I click on it the app opens. I want to be able to open at a specific page. Can someone point me in the right direction?

I have tried to find a way within the Shiny Library to set up an Action that would open a page but with no luck. I have also looked at the Xamarin sample and have the same issue with it


问:
Using panda gives and error, but same command in cursor works
```<code> import pandas as pd
 data_BG2= pd.read_sql("SELECT * FROM [dbo].[Bullgear geometry] WHERE [Bullgear]=?", "3810907-01110", cnxn)
</code>```

where cnxn is the connection

This is the first time I am using Panda and I keep getting the following error

ArgumentError: Could not parse rfc1738 URL from string '3810907-01110'

This error is only there if a searching for a string in the database. if I search for a float or an integer it works.

If I run it via a cursor like below the exact same code works.

```<code>cursor=cnxn.cursor()
cursor.execute("SELECT * FROM [dbo].[Bullgear geometry] WHERE [Bullgear]=?","3810907-01110")

for i in cursor:
    print (i)
</code>```

Body:
 import pandas as pd
 data_BG2= pd.read_sql("SELECT * FROM [dbo].[Bullgear geometry] WHERE [Bullgear]=?", "3810907-01110", cnxn)

where cnxn is the connection

This is the first time I am using Panda and I keep getting the following error

ArgumentError: Could not parse rfc1738 URL from string '3810907-01110'

This error is only there if a searching for a string in the database. if I search for a float or an integer it works.

If I run it via a cursor like below the exact same code works.

cursor=cnxn.cursor()
cursor.execute("SELECT * FROM [dbo].[Bullgear geometry] WHERE [Bullgear]=?","3810907-01110")

for i in cursor:
    print (i)


问:
Github Pages HTML file other than index.html

Here is my current File Structure For GITHUB PAGES:

Note: loading.html is my "landing page" and the file I want to load as soon as the user enters the website.

```<code>dist
│   CNAME
│   poster.png
│
└───assets
│   │   css/images/js files
│
└───src
│   │
│   └───loading-page
│       │   loading.html
│   └───main-page
│       │   main.html
</code>```

Here's the dilemma: I've seen many things about .htaccess or _config.yml to route GitHub pages but they don't seem to work. Is there any way to tell GitHub to show loading.html to the user, instead of a file in the root named index.html?

Or is this strictly how GitHub needs to work, and there is no config file, or setting I can enable that changes this behavior? I can understand if it's strictly index.html but would love to customize the names of my .html files.

Body:
Here is my current File Structure For GITHUB PAGES:

Note: loading.html is my "landing page" and the file I want to load as soon as the user enters the website.

dist
│   CNAME
│   poster.png
│
└───assets
│   │   css/images/js files
│
└───src
│   │
│   └───loading-page
│       │   loading.html
│   └───main-page
│       │   main.html

Here's the dilemma: I've seen many things about .htaccess or _config.yml to route GitHub pages but they don't seem to work. Is there any way to tell GitHub to show loading.html to the user, instead of a file in the root named index.html?

Or is this strictly how GitHub needs to work, and there is no config file, or setting I can enable that changes this behavior? I can understand if it's strictly index.html but would love to customize the names of my .html files.


问:
How to solve Flutter FormatException: Unexpected character
I found a case here I tried to change the API to local API but when I GET the data an error occurs as shown and this happens on every page, but when I try to use the live API it's normal, why is this, before it was normal just when you want to use a local API or a live API.
Thank you in advance.

and this my code:

```<code>class Constant {
  // static const String baseURL = 'http://dev.api.app.asdsadsadasd.com/v1';
  static const String baseURL = 'http://192.168.1.115:8080/v1';
  static const String token = 'access_token';
}
</code>```

and this api call:

```<code>class BiodataProvider extends ChangeNotifier {
  Future<UserBiodata> getBiodata() async {
    String url = Constant.baseURL;
    // String _token = await UtilSharedPreferences.getToken();
    //SharedPreferences _pref = await SharedPreferences.getInstance();
    String token = await UtilSharedPreferences.getToken();
    final response = await http.get(
      Uri.parse(
        '$url/auth/mhs_siakad/biodata',
      ),
      headers: {
        'Authorization': 'Bearer $token',
      },
    );

    print(response.statusCode);
    print(response.body);
    if (response.statusCode == 200) {
      return UserBiodata.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('Token Expired!');
    }
  }
}
</code>```

this call api in widget UI

```<code>FutureBuilder<UserBiodata>(
                future: biodataProvider.getBiodata(),
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    // return Text(snapshot.data!.status);
                    return Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Image.asset(
                          'assets/images/user_prof.png',
                          height: 65,
                        ),
                        const SizedBox(
                          height: 12,
                        ),
                        Text(
                          snapshot.data!.data.name.toString(),
                          style: bold15,
                        ),
                        const SizedBox(
                          height: 2,
                        ),
                        Text(
                          snapshot.data!.data.nim,
                          style: regular5,
                        ),
                        const SizedBox(
                          height: 2,
                        ),
                        Text(
                          snapshot.data!.data.prodi,
                          style: regular5,
                        ),
                        Text(
                          'IPK ${snapshot.data!.data.ipk}',
                          style: bold5,
                        ), ...
</code>```

Body:
I found a case here I tried to change the API to local API but when I GET the data an error occurs as shown and this happens on every page, but when I try to use the live API it's normal, why is this, before it was normal just when you want to use a local API or a live API.
Thank you in advance.

and this my code:

class Constant {
  // static const String baseURL = 'http://dev.api.app.asdsadsadasd.com/v1';
  static const String baseURL = 'http://192.168.1.115:8080/v1';
  static const String token = 'access_token';
}

and this api call:

class BiodataProvider extends ChangeNotifier {
  Future<UserBiodata> getBiodata() async {
    String url = Constant.baseURL;
    // String _token = await UtilSharedPreferences.getToken();
    //SharedPreferences _pref = await SharedPreferences.getInstance();
    String token = await UtilSharedPreferences.getToken();
    final response = await http.get(
      Uri.parse(
        '$url/auth/mhs_siakad/biodata',
      ),
      headers: {
        'Authorization': 'Bearer $token',
      },
    );

    print(response.statusCode);
    print(response.body);
    if (response.statusCode == 200) {
      return UserBiodata.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('Token Expired!');
    }
  }
}

this call api in widget UI

FutureBuilder<UserBiodata>(
                future: biodataProvider.getBiodata(),
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    // return Text(snapshot.data!.status);
                    return Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Image.asset(
                          'assets/images/user_prof.png',
                          height: 65,
                        ),
                        const SizedBox(
                          height: 12,
                        ),
                        Text(
                          snapshot.data!.data.name.toString(),
                          style: bold15,
                        ),
                        const SizedBox(
                          height: 2,
                        ),
                        Text(
                          snapshot.data!.data.nim,
                          style: regular5,
                        ),
                        const SizedBox(
                          height: 2,
                        ),
                        Text(
                          snapshot.data!.data.prodi,
                          style: regular5,
                        ),
                        Text(
                          'IPK ${snapshot.data!.data.ipk}',
                          style: bold5,
                        ), ...


问:
Change position of facet strip text
I want to have strip and their texts for each facet on the right side of y axis instead of the top of x axis in ggplot2 in R.

I tried theme**(strip.placement = c("right"))** after removing the strip and their texts from top of the x axis by using theme(strip.text = element_blank(), strip.background = element_blank())+

Strip texts were disappeared from the top but I am not able to place them on the right side of the y axis.

Title: Change position of facet strip text


问:
Can we get facebook app id and app secret with access token?
Am trying to get the fb reports, better way is to use facebook internal functionality to get reports. But for that i need app id and app secret, i have access token with that token is it possible to fetch app id and app secret?</p>


问:
How to add and access a yaml file as a resource in Ballerina?
I have a YAML file that I want to keep as part of my jar resources and consume inside my .bal program.
I have created a resources folder under my project and placed the file there.
The file is being added to the JAR and I can confirm it.

But how do I now access it within my code:

```<code>string requestedFile = "./resources/service_openapi.yaml"; // <--- here
res.setFileAsPayload(requestedFile, contentType = mime:APPLICATION_OCTET_STREAM);
</code>```

The above throws a runtime error: no such file or directory

Body:
I have a YAML file that I want to keep as part of my jar resources and consume inside my .bal program.
I have created a resources folder under my project and placed the file there.
The file is being added to the JAR and I can confirm it.

But how do I now access it within my code:

string requestedFile = "./resources/service_openapi.yaml"; // <--- here
res.setFileAsPayload(requestedFile, contentType = mime:APPLICATION_OCTET_STREAM);

The above throws a runtime error: no such file or directory


问:
S3 GET PreSigned URL 403 Forbidden from Viewing files in browsers
I am trying to view files from my S3 Bucket. I am a PreSigned URL and the react Package react-file-viewer.

Whenever I call the Signed URL through  react-file-viewer I get an error 403 forbidden. But if I copy and paste the Pre-Signed URL into my search bar I can view the file. I can also download the files and they open the data.

This is what my response is.

Request Method:

HEAD

Status Code:

403 Forbidden

Remote Address:

xx.x.xx.xx..x..x

Referrer Policy:

strict-origin-when-cross-origin

In my S3 bucket, I have this as my CORS header:

```<code>[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "PUT",
            "POST",
            "DELETE",
            "HEAD",
            "GET"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [
            "x-amz-server-side-encryption",
            "x-amz-request-id",
            "x-amz-id-2"
        ],
        "MaxAgeSeconds": 3000
    }
]
</code>```

and my pre-signed URL is

```<code>var url = s3.getSignedUrl('getObject', {
          Bucket: BucketName,
          Key:  fileURLData[fileSpot].file_url,
          Expires: signedUrlExpireSeconds,
           })
</code>```

Does this look like an CORS issue or something to do with my S3 Bucket permissions?

Body:
I am trying to view files from my S3 Bucket. I am a PreSigned URL and the react Package react-file-viewer.

Whenever I call the Signed URL through  react-file-viewer I get an error 403 forbidden. But if I copy and paste the Pre-Signed URL into my search bar I can view the file. I can also download the files and they open the data.

This is what my response is.

Request Method:

HEAD

Status Code:

403 Forbidden

Remote Address:

xx.x.xx.xx..x..x

Referrer Policy:

strict-origin-when-cross-origin

In my S3 bucket, I have this as my CORS header:

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "PUT",
            "POST",
            "DELETE",
            "HEAD",
            "GET"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [
            "x-amz-server-side-encryption",
            "x-amz-request-id",
            "x-amz-id-2"
        ],
        "MaxAgeSeconds": 3000
    }
]

and my pre-signed URL is

var url = s3.getSignedUrl('getObject', {
          Bucket: BucketName,
          Key:  fileURLData[fileSpot].file_url,
          Expires: signedUrlExpireSeconds,
           })

Does this look like an CORS issue or something to do with my S3 Bucket permissions?


问:
How to find the current market price of an asset using pybit?
Reading the pybit docs I am unable to find a way to obtain market price, specifically for BTC/USDT. How can I access this info?

Read the docs, concluded market price could be contained in latest_information_for_symbol() but I don't know how to write something to select just market price.


问:
Django aggregate calculating incorrectly because of many-to-many join in queryset
We have a model with a many-to-many relationship with another model, and doing a Sum aggregation on it seems to multiply the result by the number of many-to-many relationships. Example models below:

```<code>class Attendee(models.Model):
  name = models.TextField()
  category = models.TextField()

class Event(models.Model):
  start_date = models.DateTimeField()
  end_date = models.DateTimeField()
  attendees = models.ManyToManyField(Attendee, related_name="event")

class CalendarEvent(models.Model):
  calendar = models.TextField()
  event = models.ForeignKey(Event, related_name="calendar_events")
</code>```

We filter out some records based on Attendee, and then aggregate the duration of the events.

```<code>queryset = queryset.filter(event__attendee__category="Accountant")

queryset = queryset.annotate(duration=models.ExpressionWrapper(
  models.F('event__end_date') - models.F('event__start_date'),
  output_field=models.fields.DurationField()
))
</code>```

Whenever we run the aggregation at the end, all duration values would be multiplied by the number of Attendees associated with the Event/CalendarEvent. For example, if the event is 15 minutes long and has 4 attendees, we would expect the duration to be 900 seconds, but instead it's 3600 seconds. We noticed in the raw PSQL query that there is a LEFT OUTER JOIN against Attendees, so we tried removing the Attendee filter and it gave us the proper data.

Is there any way to aggregate across a relationship like this without the joined results getting mixed in?

Body:
We have a model with a many-to-many relationship with another model, and doing a Sum aggregation on it seems to multiply the result by the number of many-to-many relationships. Example models below:

class Attendee(models.Model):
  name = models.TextField()
  category = models.TextField()

class Event(models.Model):
  start_date = models.DateTimeField()
  end_date = models.DateTimeField()
  attendees = models.ManyToManyField(Attendee, related_name="event")

class CalendarEvent(models.Model):
  calendar = models.TextField()
  event = models.ForeignKey(Event, related_name="calendar_events")

We filter out some records based on Attendee, and then aggregate the duration of the events.

queryset = queryset.filter(event__attendee__category="Accountant")

queryset = queryset.annotate(duration=models.ExpressionWrapper(
  models.F('event__end_date') - models.F('event__start_date'),
  output_field=models.fields.DurationField()
))

Whenever we run the aggregation at the end, all duration values would be multiplied by the number of Attendees associated with the Event/CalendarEvent. For example, if the event is 15 minutes long and has 4 attendees, we would expect the duration to be 900 seconds, but instead it's 3600 seconds. We noticed in the raw PSQL query that there is a LEFT OUTER JOIN against Attendees, so we tried removing the Attendee filter and it gave us the proper data.

Is there any way to aggregate across a relationship like this without the joined results getting mixed in?


问:
How do i update an element inside a ckeditor 5 dynamically using javascript innerHTML
I want to automatically load up adverts inside the body of my blog website

For Example:

After loading up ckeditor 5, i want to replace the above element with an advert code from platforms like ezoic, google, etc. I have tried to put the code directly in the blog post body, but ckeditor keeps filtering, after rigorous research, i could only preserve the custom html elements like , but any form of script tags are filtered out, i want to use the approach of loading up ckeditor before adding the advert code dynamically, I tried editor:

document.querySelectorAll(".dynamic-ads-div").forEach(ads => { ads.innerHTML = '<custom-element></custom-element>' }).

Ckeditor completely ignores the above code.

Any form of help will be greatly appreciated; If you can help me preserve the script tags, or help me insert content dynamically after loading up ckeditor.

Thanks