问:
Resolving connection string in EFv6.3 in ASP.NET Core Windows service project
I have an ASP.NET Core application running as a Windows Service. Due to project requirements, I am using Entity Framework v6.3 (as opposed to using EF Core).

I am having trouble retrieving the correct connection string when performing a migration and also upon publishing the service to a server. When running the service locally, the connection string is retrieved successfully.

As I understand it, Entity Framework 6 is supposed to retrieve connection strings from web.config or app.config files, right? Therefore, I have an app.config file containing two connection strings, e.g.

```<code><connectionStrings>
    <add name="DataContext" providerName="System.Data.SqlClient" connectionString="Server=localhost\SQLEXPRESS;[redacted]" />
    <add name="CrmContext" providerName="System.Data.SqlClient" connectionString="Server=localhost\SQLEXPRESS;[redacted]" />
</connectionStrings>
</code>```

In my Startup class, I have registered both database contexts, e.g.

```<code>services.AddTransient<DataContext>();
services.AddTransient<CrmContext>();
</code>```

On a Razor page, when I instantiate both data contexts on my local machine I can see the correct connection string is being resolved for both contexts (by using _crmContext.Database.Connection.ConnectionString).

When I attempt to add a migration using the update-database command on my CrmContext (automatic migrations enabled), the correct connection string isn't resolved. Instead, it defaults to creating a LocalDB database using the default connection string: (localdb)\MSSQLLocalDB

How come it isn't using the connection string I have provided in my app.config file? I also a web.config file but it doesn't resolve from there either.

CrmContext.cs

```<code>public class CrmContext : DbContext
{
    public CrmContext() : base("CrmContext")
    {
        Database.SetInitializer<CrmContext>(null);
    }

    public IDbSet<CustomerDetails> CustomerDetails { get; set; }
}
</code>```

CrmConfiguration.cs

```<code>internal sealed class CrmConfiguration : DbMigrationsConfiguration<CrmContext>
{
    public CrmConfiguration()
    {
        AutomaticMigrationsEnabled = true;
    }

    protected override void Seed(CrmContext context)
    {
        ...

        context.SaveChanges();
    }
}
</code>```

I've tried to explicitly update the CRM connection by specifying my CrmConfiguration file:

```<code>update-database -ConfigurationTypeName CrmContext
</code>```

When I do this, it creates and updates the LocalDB database instead of using my connection string.

I've also tried to explicitly referencing the connection string:

```<code>update-database -ConnectionStringName "CrmContext"
</code>```

This results in this error:

No connection string named 'CrmContext' could be found in the
  application config file.

My CrmContext class exists within my ASP.NET Core windows application where my DataContext class exists in a separate 'Data' project (as it's shared with an ASP.NET MVC v5 application)

When I publish my service and install the application as a Windows Service, I found that it also doesn't pick up the connection strings at all from any of the config files - it again just looks for the default localdb database. As I understand, it should pick it up from my PaymentBatchProcessorService.exe.config file, right?

My PaymentBatchProcessorService.exe.config file looks like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="DataContext" providerName="System.Data.SqlClient" connectionString="redacted" />
    <add name="CrmContext" providerName="System.Data.SqlClient" connectionString="redacted" />
  </connectionStrings>
</configuration>
</code>```

As per Microsoft documentation, it should be possible to load in the additional XML configuration files via the following code in the Program.cs file, but EntityFramework still didn't pick up the connection strings:

```<code>Host.CreateDefaultBuilder(args)
    .UseWindowsService()
    .ConfigureAppConfiguration((hostingContext, config) =>
    {
        var workingDirectoryPath = Environment.GetEnvironmentVariable(EnvironmentVariables.ServiceWorkingDirectory);

        config.AddXmlFile(Path.Combine(workingDirectoryPath, "app.config"));
        config.AddXmlFile(Path.Combine(workingDirectoryPath, "web.config"));
    })
</code>```

e.g. in the above sample, the working directory path resolves to the location where my .exe is for the Windows Service.

Thanks for reading this far!

答: When you deploy your service, the .config file should instead be called servicename.exe.config. It should reside on the same folder where the service was registered with installutil. See Windows service app.config location.</p>

Body:
I have an ASP.NET Core application running as a Windows Service. Due to project requirements, I am using Entity Framework v6.3 (as opposed to using EF Core).

I am having trouble retrieving the correct connection string when performing a migration and also upon publishing the service to a server. When running the service locally, the connection string is retrieved successfully.

As I understand it, Entity Framework 6 is supposed to retrieve connection strings from web.config or app.config files, right? Therefore, I have an app.config file containing two connection strings, e.g.

<connectionStrings>
    <add name="DataContext" providerName="System.Data.SqlClient" connectionString="Server=localhost\SQLEXPRESS;[redacted]" />
    <add name="CrmContext" providerName="System.Data.SqlClient" connectionString="Server=localhost\SQLEXPRESS;[redacted]" />
</connectionStrings>

In my Startup class, I have registered both database contexts, e.g.

services.AddTransient<DataContext>();
services.AddTransient<CrmContext>();

On a Razor page, when I instantiate both data contexts on my local machine I can see the correct connection string is being resolved for both contexts (by using _crmContext.Database.Connection.ConnectionString).

When I attempt to add a migration using the update-database command on my CrmContext (automatic migrations enabled), the correct connection string isn't resolved. Instead, it defaults to creating a LocalDB database using the default connection string: (localdb)\MSSQLLocalDB

How come it isn't using the connection string I have provided in my app.config file? I also a web.config file but it doesn't resolve from there either.

CrmContext.cs

public class CrmContext : DbContext
{
    public CrmContext() : base("CrmContext")
    {
        Database.SetInitializer<CrmContext>(null);
    }

    public IDbSet<CustomerDetails> CustomerDetails { get; set; }
}

CrmConfiguration.cs

internal sealed class CrmConfiguration : DbMigrationsConfiguration<CrmContext>
{
    public CrmConfiguration()
    {
        AutomaticMigrationsEnabled = true;
    }

    protected override void Seed(CrmContext context)
    {
        ...

        context.SaveChanges();
    }
}

I've tried to explicitly update the CRM connection by specifying my CrmConfiguration file:

update-database -ConfigurationTypeName CrmContext

When I do this, it creates and updates the LocalDB database instead of using my connection string.

I've also tried to explicitly referencing the connection string:

update-database -ConnectionStringName "CrmContext"

This results in this error:

No connection string named 'CrmContext' could be found in the
  application config file.

My CrmContext class exists within my ASP.NET Core windows application where my DataContext class exists in a separate 'Data' project (as it's shared with an ASP.NET MVC v5 application)

When I publish my service and install the application as a Windows Service, I found that it also doesn't pick up the connection strings at all from any of the config files - it again just looks for the default localdb database. As I understand, it should pick it up from my PaymentBatchProcessorService.exe.config file, right?

My PaymentBatchProcessorService.exe.config file looks like this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>

  </configSections>
  <connectionStrings>
    <add name="DataContext" providerName="System.Data.SqlClient" connectionString="redacted" />
    <add name="CrmContext" providerName="System.Data.SqlClient" connectionString="redacted" />
  </connectionStrings>
</configuration>

As per Microsoft documentation, it should be possible to load in the additional XML configuration files via the following code in the Program.cs file, but EntityFramework still didn't pick up the connection strings:

Host.CreateDefaultBuilder(args)
    .UseWindowsService()
    .ConfigureAppConfiguration((hostingContext, config) =>
    {
        var workingDirectoryPath = Environment.GetEnvironmentVariable(EnvironmentVariables.ServiceWorkingDirectory);

        config.AddXmlFile(Path.Combine(workingDirectoryPath, "app.config"));
        config.AddXmlFile(Path.Combine(workingDirectoryPath, "web.config"));
    })

e.g. in the above sample, the working directory path resolves to the location where my .exe is for the Windows Service.

Thanks for reading this far!


来源: stackexchange

问:
Is it mandatory to check "Retrieve All Embedded Resources" in HTTP Request Defaults for performance testing?
During performance testing "Retrieve All Embedded Resources" should be checked or unchecked?

My analysis: "Retrieve All Embedded Resources" should not be checked. And cache also should not be cleared automatically.

Note:
a. "Retrieve All Embedded Resources" option is not checked in Jmeter default recording template.

Which is the correct response time, if 500 user are iterating 2 scenarios 50 times.

My analysis: Need to refer "Transaction Controller - Sample Time [sum value]" in "View Results in Table" listener. Note, need to user parallel controller in order to handle parallel requests and need to refer max response time in that.

答:
If you're testing a web application you need to configure JMeter to behave like a real browser. Real browsers download these "embedded resources" like images, scripts, styles, fonts, sounds, etc. and doing this in parallel (one main request followed by 6 threads to download the embedded resources). So you should:

Configure JMeter to download embedded resources

Do it using parallel downloads with i.e. 6 threads

Limit the resources location to the domain(s) you're testing to exclude 3rd-party resources like CDNs for scripts, banners from external sites, etc)

Cache: if you want to simulate "new" user each iteration you should clear the cache, if you want to simulate "returning" user - he should already have the resources in his cache and shouldn't download them.

More information: Web Testing with JMeter: How To Properly Handle Embedded Resources in HTML Responses

We don't know what you're measuring, the response time for a single request or for the whole business transaction. Personally I would go for the single request (but including all the embedded resources and eventually AJAX requests simulated by the parallel controller if any) and look not into the average response time but rather at 90% percentile as average can mask the problem while 90% percentile is the response time which 90% of the users will get.

ContentLicense: CC BY-SA 4.0


问:
Make the layout below button
In one of my fragment class, it has two buttons (A and B) on top, used to switch to another fragment when clicked using viewPager.

When buttonA is clicked, it should switch to page A and so on.

When I click button A, how can I make the text in A show below the two buttons?

fragment_menu.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/buttonA"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="10dp"
        android:padding="15dp"
        android:text="ButtonA"
        android:textSize="12sp" />

    <Button
        android:id="@+id/buttonB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="15dp"
        android:layout_toRightOf="@+id/buttonB"
        android:backgroundTint="@color/materialGrey600"
        android:padding="15dp"
        android:text="ButtonB"
        android:textSize="12sp" />

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>
</code>```

MenuFragment

```<code>public class MenuFragment extends BaseFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_menu, container, false);
        final ViewPager viewPager = (ViewPager) v.findViewById(R.id.pager);
        viewPager.setAdapter(new ViewPagerAdapter(getActivity().getFragmentManager()));

        Button btnA = (Button) v.findViewById(R.id.buttonA);
        Button btnB = (Button) v.findViewById(R.id.buttonB);

        btnA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(0, true);
            }
        });

        btnB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(1, true);
            }
        });
        return v;
    }
}
</code>```

ViewPagerAdapter

```<code>  public class ViewPagerAdapter extends FragmentPagerAdapter {

        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position)
            {
                case 0:
                    return new A()
                case 1:
                    return new B()

            }
            return null;
        }

        @Override
        public int getCount() {
            return 2;
        }
    }
</code>```

Output

答:
```<code>You have to set your layout like this....

[I think you want something like this 2 button fisrt and then viewpager for change the content ][1]

  [1]: https://i.stack.imgur.com/dluXA.png

**Code for main Page **

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:padding="5dp"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:padding="10dp"
        android:layout_marginTop="10dp"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/frame_content">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_gravity="center_horizontal">

                <Button
                    android:id="@+id/btn_donner"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="2"
                    android:background="@drawable/rect_outline"
                    android:text="Donor's"
                    android:textAlignment="center"
                    android:textColor="@color/white" />

                <Button
                    android:id="@+id/btn_blood_bank"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Blood Bank"
                    android:background="@drawable/rect_outline"
                    android:layout_weight="2"
                    android:textAlignment="gravity"
                    android:textColor="@color/white" />
            </LinearLayout>
        </FrameLayout>
    </LinearLayout>
</LinearLayout>

Code For Java File of two Buttons And ViewPager

      //Click Event for donor's and blood bank .....
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Fragment fragment = null;
                if (view == view.findViewById(R.id.btn_donner))
                {
                    fragment = new TabDonnerFragment();
                }
                else
                {
                    fragment = new TabBloodBankFragment();
                }
                FragmentManager manager = getFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.replace(R.id.frame_content, fragment);
                transaction.commit();
            }
        };
        btn_donner.setOnClickListener(listener);
        btn_blood_bank.setOnClickListener(listener);

        return root;
    }

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

        Fragment fragment = null;
        fragment = new TabDonnerFragment();
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.frame_content, fragment);
        transaction.commit();
    }
}
</code>```

Title: Make the layout below button

Body:
In one of my fragment class, it has two buttons (A and B) on top, used to switch to another fragment when clicked using viewPager.

When buttonA is clicked, it should switch to page A and so on.

When I click button A, how can I make the text in A show below the two buttons?

fragment_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/buttonA"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="10dp"
        android:padding="15dp"
        android:text="ButtonA"
        android:textSize="12sp" />

    <Button
        android:id="@+id/buttonB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="15dp"
        android:layout_toRightOf="@+id/buttonB"
        android:backgroundTint="@color/materialGrey600"
        android:padding="15dp"
        android:text="ButtonB"
        android:textSize="12sp" />

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

MenuFragment

public class MenuFragment extends BaseFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_menu, container, false);
        final ViewPager viewPager = (ViewPager) v.findViewById(R.id.pager);
        viewPager.setAdapter(new ViewPagerAdapter(getActivity().getFragmentManager()));

        Button btnA = (Button) v.findViewById(R.id.buttonA);
        Button btnB = (Button) v.findViewById(R.id.buttonB);

        btnA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(0, true);
            }
        });

        btnB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(1, true);
            }
        });
        return v;
    }
}

ViewPagerAdapter

  public class ViewPagerAdapter extends FragmentPagerAdapter {

        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position)
            {
                case 0:
                    return new A()
                case 1:
                    return new B()

            }
            return null;
        }

        @Override
        public int getCount() {
            return 2;
        }
    }

Output


问:
XIB-less iOS project template refuses to receive touch events
As the title says... I'm creating a template purely from code, ie without using XIBs.

So I create a window and a view controller,  and the view controller in turn creates a view

( I am going to provide the answer below, just putting this up so is to save someone from banging their head from week on it.   I'm creating a new question because the first question was poorly formed -- the solution had nothing to do with iAd framework, I should have debugged further and figured this out before posting. )

答:
This is a UIKit bug.   Full answer at iAd -- cannot click banner

The solution is to set the background colour of the view to anything!  eg [UIColor redColor]

ContentLicense: CC BY-SA 3.0


问:
How to save multiple location coordinates in your project?
I'm fetching some of the locations from the server and need to point them as markers in the google map, so what i did was i created a model of the locations and used the volley library to fetch the details from the server and saved them in a variable and post it in the map. But I'm getting an error as java.lang.NumberFormatException: multiple points.
So need some assistance.
This is my model

```<code>public class LocationModel
private String pdLatitude;
private String pdLongitude;

public LocationModel(String pdLatitude, String pdLongitude){
this.pdLatitude = pdLatitude;
this.pdLongitude = pdLongitude; }

public String getPdLatitude() {
return pdLatitude;
}

public String getPdLongitude() {
return pdLongitude;
}
</code>```

This is my Activity where i'm retreiving the information from the server

```<code>private void findRoute(){
        StringRequest request = new StringRequest(Request.Method.GET,
                Constant.Route_URL + "/" + driverschoolname + "/" + driverid,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        String pdlatitude = "";
                        String pdlongitude = "";
                        try{
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray array = jsonObject.getJSONArray("res");
                            for (int i=0; i<array.length(); i++){
                                JSONObject object = array.getJSONObject(i);
                                StudentsPickDropModel pickDropModel = new StudentsPickDropModel(
                                        object.getString("pdloc_latitude"),
                                        object.getString("pdloc_longitude")
                                );
                                pdlatitude += pickDropModel.getPdLatitude();
                                pdlongitude += pickDropModel.getPdLongitude();
                                Toast.makeText(StudentsPickDropActivity.this, pickDropModel.getPdName(), Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(Activity.this, GetRoute.class);
                                intent.putExtra("pd_latitude", pdlatitude);
                                intent.putExtra("pd_longitude", pdlongitude);
                                startActivity(intent);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(Activity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        RequestQueue queue = Volley.newRequestQueue(this);
        queue.add(request);
    }
</code>```

And this is how i'm posting my coordiantes in Google maps

```<code>Bundle bundle = getIntent().getExtras();
        schoollat = bundle.getString("school_lat");
        schoollng = bundle.getString("school_lng");
        pdlat = bundle.getString("pd_latitude");
        pdlng = bundle.getString("pd_longitude");

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        mFusedLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                Location location = task.getResult();
                if (location == null){
                    requestNewLocationData();
                } else {
                    currentLat = location.getLatitude();
                    currentLng = location.getLongitude();
                    System.out.println("Current Latitude: "+location.getLatitude());
                    System.out.println("Current Longitude: "+location.getLongitude());
                }
            }
        });

        Double clat = currentLat;
        System.out.println("Current Latitude : "+clat);

        Double schoollatitude = new Double(schoollat);
        Double schoollongitude = new Double(schoollng);
        System.out.println("School latitude : "+schoollatitude + ", School Longitude : "+schoollongitude);
        Double pdlatitude = new Double(pdlat);
        Double pdlongitude = new Double(pdlng);

        getDirections = findViewById(R.id.getdirection);
        getDirections.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new FetchURL(GetRoute.this).execute(getUrl(placeOne.getPosition(), placeTwo.getPosition(), "driving"), "driving");
            }
        });

        MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map_fragment);
        mapFragment.getMapAsync(this);

        places = new MarkerOptions().position(new LatLng(pdlatitude, pdlongitude)).title("Office");
</code>```

And this is my JSON

```<code>  "res": [
        {
            "pdloc_latitude": "12.3111356",
            "pdloc_longitude": "76.6075989",
        },
        {
            "pdloc_latitude": "88.568645787",
            "pdloc_longitude": "75.54544454887",
        }
</code>```

答:
Your PDlat have 2 points. That is invalid for Double since Double have 1 point.

Your value:

```<code>12.311135688.568645787
</code>```

What it should has 1 point like this:

```<code>12.311135688568645787
</code>```

PS. You can catch an exception If the value parsing is fail, and what to do is up to what exception occurs.

Body:
I'm fetching some of the locations from the server and need to point them as markers in the google map, so what i did was i created a model of the locations and used the volley library to fetch the details from the server and saved them in a variable and post it in the map. But I'm getting an error as java.lang.NumberFormatException: multiple points.
So need some assistance.
This is my model

public class LocationModel
private String pdLatitude;
private String pdLongitude;

public LocationModel(String pdLatitude, String pdLongitude){
this.pdLatitude = pdLatitude;
this.pdLongitude = pdLongitude; }

public String getPdLatitude() {
return pdLatitude;
}

public String getPdLongitude() {
return pdLongitude;
}

This is my Activity where i'm retreiving the information from the server

private void findRoute(){
        StringRequest request = new StringRequest(Request.Method.GET,
                Constant.Route_URL + "/" + driverschoolname + "/" + driverid,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        String pdlatitude = "";
                        String pdlongitude = "";
                        try{
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray array = jsonObject.getJSONArray("res");
                            for (int i=0; i<array.length(); i++){
                                JSONObject object = array.getJSONObject(i);
                                StudentsPickDropModel pickDropModel = new StudentsPickDropModel(
                                        object.getString("pdloc_latitude"),
                                        object.getString("pdloc_longitude")
                                );
                                pdlatitude += pickDropModel.getPdLatitude();
                                pdlongitude += pickDropModel.getPdLongitude();
                                Toast.makeText(StudentsPickDropActivity.this, pickDropModel.getPdName(), Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(Activity.this, GetRoute.class);
                                intent.putExtra("pd_latitude", pdlatitude);
                                intent.putExtra("pd_longitude", pdlongitude);
                                startActivity(intent);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(Activity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        RequestQueue queue = Volley.newRequestQueue(this);
        queue.add(request);
    }

And this is how i'm posting my coordiantes in Google maps

Bundle bundle = getIntent().getExtras();
        schoollat = bundle.getString("school_lat");
        schoollng = bundle.getString("school_lng");
        pdlat = bundle.getString("pd_latitude");
        pdlng = bundle.getString("pd_longitude");

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        mFusedLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                Location location = task.getResult();
                if (location == null){
                    requestNewLocationData();
                } else {
                    currentLat = location.getLatitude();
                    currentLng = location.getLongitude();
                    System.out.println("Current Latitude: "+location.getLatitude());
                    System.out.println("Current Longitude: "+location.getLongitude());
                }
            }
        });

        Double clat = currentLat;
        System.out.println("Current Latitude : "+clat);

        Double schoollatitude = new Double(schoollat);
        Double schoollongitude = new Double(schoollng);
        System.out.println("School latitude : "+schoollatitude + ", School Longitude : "+schoollongitude);
        Double pdlatitude = new Double(pdlat);
        Double pdlongitude = new Double(pdlng);

        getDirections = findViewById(R.id.getdirection);
        getDirections.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new FetchURL(GetRoute.this).execute(getUrl(placeOne.getPosition(), placeTwo.getPosition(), "driving"), "driving");
            }
        });

        MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map_fragment);
        mapFragment.getMapAsync(this);

        places = new MarkerOptions().position(new LatLng(pdlatitude, pdlongitude)).title("Office");

And this is my JSON

  "res": [
        {
            "pdloc_latitude": "12.3111356",
            "pdloc_longitude": "76.6075989",
        },
        {
            "pdloc_latitude": "88.568645787",
            "pdloc_longitude": "75.54544454887",
        }

Body:
Your PDlat have 2 points. That is invalid for Double since Double have 1 point.

Your value:

12.311135688.568645787

What it should has 1 point like this:

12.311135688568645787

PS. You can catch an exception If the value parsing is fail, and what to do is up to what exception occurs.


问:
Symfony/Doctrine/authentication, I can't recover the roles
I have a problem when i want to connect. Let me explain, I have two User and Role entities that are linked to a ManyToMany relationship, so I have a dynamic user_role table. I would like to connect with the user who has the ROLE_ADMIN but the problem is that I cannot read the object so that it reads this role. This shows me this error.

Warning: Illegal offset type in isset or empty

I think the problem comes from the line "$ role = $ this-> roles-> toArray ();" in getRoles.

Here is the code for User.php

```<code>class User implements UserInterface, \Serializable
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=180, unique=true)
     */
    private $username;

    /**
     * @var string The hashed password
     * @ORM\Column(type="string")
     */
    private $password;

    /**
     * @ORM\Column(type="boolean", nullable=false, options={"default" : 0})
     */
    private $isActive;

    /**
     * @ORM\Column(type="string", unique=true, length=64)
     */
    private $token;

    /**
     * @ORM\Column(type="datetime")
     */
    private $expiresAt;

    /**
     * @ORM\ManyToMany(targetEntity="Role", inversedBy="users", fetch="LAZY")
     * @ORM\JoinTable(name="user_role",
     *     joinColumns={
     *      @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="role_id", referencedColumnName="id")
     *   }
     *  )
     */
    private $role;

    public function __construct()
    {
        //$this->repository = $repository;
        $this->role = new ArrayCollection();
        //$this->roles = new Role();
    }

    /**
     * Add userRoles
     *
     * @param \App\Entity\Role $roles
     * @return User
     */
    public function addRoles(\App\Entity\Role $role)
    {
        $this->role[] = $role;

        return $this;
    }

    /**
     * Remove userRoles
     *
     * @param \App\Entity\Role $roles
     */
    public function removeRoles(\App\Entity\Role $role)
    {
        $this->role->removeElement($role);
    }

    /**
     * Get Role
     */
    public function getRoles() : array //Role return
    {
        //$role = $this->repository->find($this->getId());
        //$role = $role->getName();
        $role = $this->role->toArray();

        //$roles = ['ROLE_ADMIN'];
        //$role = $this->serialize($role);
        var_dump($role);
        //$role = $role[0]['name'];

        if (empty($role)) {
            $role[] = ['ROLE_ADMIN'];
        }
        return array_unique($role);
    }

    public function setRoles($role): self
    {
        //$this->roles = $roles;
        if (is_array($role)) {
            $this->role = $role;
        } else {
            $this->role->clear();
            $this->role->add($role);
        }
        return $this;
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUsername(): string
    {
        return (string)$this->username;
    }

    public function setUsername(string $username): self
    {
        $this->username = $username;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getPassword(): string
    {
        return (string)$this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getSalt()
    {
        // not needed when using the "bcrypt" algorithm in security.yaml
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials()
    {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }

    public function getIsActive(): ?bool
    {
        return $this->isActive;
    }

    public function setIsActive(bool $isActive): self
    {
        $this->isActive = $isActive;

        return $this;
    }

    public function getToken(): ?string
    {
        return $this->token;
    }

    public function setToken(string $token): self
    {
        $this->token = $token;

        return $this;
    }

    public function getExpiresAt(): ?\DateTimeInterface
    {
        return $this->expiresAt;
    }

    public function setExpiresAt(\DateTimeInterface $expiresAt): self
    {
        $this->expiresAt = $expiresAt;

        return $this;
    }

    public function isExpired(): bool
    {
        return $this->getExpiresAt() <= new \DateTime();
    }

    public function createToken()
    {
        return substr(str_replace(['+', '/'], ['-', '_'], base64_encode(random_bytes(50))), 0, 63);
    }

    /**
     * String representation of object
     * @link https://php.net/manual/en/serializable.serialize.php
     * @return string the string representation of the object or null
     * Transform object to string
     */
    public function serialize()
    {
        return serialize([
            $this->id,
            $this->username,
            $this->password,
            $this->isActive,
            $this->token,
            $this->expiresAt
        ]);
    }

    /**
     * @param string $serialized
     * Transform string to object
     */
    public function unserialize($serialized)
    {
        list(
            $this->id,
            $this->username,
            $this->password,
            $this->isActive,
            $this->token,
            $this->expiresAt
            ) = unserialize($serialized, ['allowed_classes' => false]);
    }

}
</code>```

And here is the code for Role.php

```<code>class Role implements \Serializable
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $role;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $description;

    /**
     * @ORM\ManyToMany(targetEntity="User", mappedBy="roles")
     */
    private $users;

    public function __construct()
    {
        $this->users = new ArrayCollection();
    }

    public function getUsers()
    {
        return $this->users;
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getRole(): ?string
    {
        return $this->role;
    }

    public function setRole($role)
    {
        $this->role = $role;

        return $this;
    }

    public function getDescription(): ?string
    {
        return $this->description;
    }

    public function setDescription(string $description): self
    {
        $this->description = $description;

        return $this;
    }

    /*
    * methods for RoleInterface
    */
    /*public function getRoles()
    {
        return $this->getRole();
    }*/

    /**
     * Add users
     *
     * @param \App\Entity\User $users
     * @return Role
     */
    public function addUser(\App\Entity\User $users)
    {
        $this->users[] = $users;

        return $this;
    }

    /**
     * Remove users
     *
     * @param \App\Entity\User $users
     */
    public function removeUser(App\Entity\User $users)
    {
        $this->users->removeElement($users);
    }

    /**
     * String representation of object
     * @link https://php.net/manual/en/serializable.serialize.php
     * @return string the string representation of the object or null
     * Transform object to string
     */
    public function serialize()
    {
        return serialize([
            $this->id,
            $this->role,
            $this->description
        ]);
    }

    /**
     * @param string $serialized
     * Transform string to object
     */
    public function unserialize($serialized)
    {
        list(
            $this->id,
            $this->role,
            $this->description
            ) = unserialize($serialized, ['allowed_classes' => false]);
    }
}
</code>```

then in my controller I did a findAll

```<code>/**
* @Route("/admin/user", name="admin_user_index")
* @return \Symfony\Component\HttpFoundation\Response
*/
public function listUser(UserRepository $user)
{
return $this->render('admin/security_user/list_user.html.twig', ['user' => $user->findAll()]);
}
</code>```

var_dump($role)

```<code>/var/www/api/symfony/src/Entity/User.php:108:
array (size=1)
  0 =>
    object(App\Entity\Role)[423]
      private 'id' => int 2
      private 'role' => string '['ROLE_ADMIN']' (length=14)
      private 'description' => string 'administrateur' (length=14)
      private 'users' =>
        object(Doctrine\ORM\PersistentCollection)[425]
          private 'snapshot' =>
            array (size=0)
              ...
          private 'owner' =>
            &object(App\Entity\Role)[423]
          private 'association' =>
            array (size=16)
              ...
          private 'em' =>
            object(Doctrine\ORM\EntityManager)[205]
              ...
          private 'backRefFieldName' => string 'roles' (length=5)
          private 'typeClass' =>
            object(Doctrine\ORM\Mapping\ClassMetadata)[262]
              ...
          private 'isDirty' => boolean false
          protected 'collection' =>
            object(Doctrine\Common\Collections\ArrayCollection)[426]
              ...
          protected 'initialized' => boolean false
</code>```

Here is the user list code:

```<code>{% extends '/admin/base_admin.html.twig' %}

{% block style %}
    <style>
        h1#titlelist{
            float: left;
        }
        button#edit {
            float: right;
        }
        button#create{
            float: right;
            margin-left: 15px;
        }
    </style>
{% endblock %}

{% block logout %}
    <a style="color: grey" href="{{ path('security_logout') }}">Deconnexion</a>
{% endblock %}

{% block body %}
    <br /><br />
    <h1 id="titlelist" class="h3 mb-3 font-weight-normal">Liste des utilisateurs</h1>
    {% for message in app.flashes('success') %}
        <div class="alert alert-success">
            {{ message }}
        </div>
    {% endfor %}
    <a href="{{ path('admin_index') }}">
        <button id="create" class="btn btn-lg btn-primary">
            Annuler
        </button>
    </a>
    <a href="{{ path('admin_user_create') }}">
        <button id="create" class="btn btn-lg btn-primary">
            Ajouter
        </button>
    </a>

    <br />
    <br />
    <br />
    <TABLE  class="table table-striped">
        <thead>
        <TR>
            <TH>ID</TH>
            <TH>Utilisateur</TH>
            <TH>Password</TH>
            <TH>Rôles</TH>
            <TH>Actif</TH>
            <TH>Editer</TH>
        </TR>
        </thead>
        <tbody>
        {% for list in user %}
            <TR>
                <TD>{{ list.id }}</TD>
                <TD>{{ list.username }}</TD>
                <TD>{{ list.password }}</TD>
                <TD>
                    {% for role in list.roles %}
                        {{ role.name }},
                    {% endfor %}
                </TD>
                <TD>{{ list.isActive }}</TD>

                <TD>
                    <a href="{{ path('admin_user_edit', {id: list.id}) }}" class="btn btn-primary">Editer</a>
                    <form method="post" action="{{ path('admin_user_delete', {id: list.id}) }}" style="display: inline-block"
                          onsubmit="return confirm('Voulez-vous vraiment supprimer l\'utilisateur ?')">
                        <input type="hidden" name="_method" value="DELETE">
                        <input type="hidden" name="_token" value="{{ csrf_token('delete' ~ list.id) }}">
                        <button class="btn btn-primary">Supprimer</button>
                    </form>
                </TD>
            </TR>
        {% endfor %}
        </tbody>
    </TABLE>
{% endblock %}
</code>```

I would like to retrieve the role store in the role table.

If any of you can enlighten me, thank you in advance.

答:
With little help, Here is the solution

```<code>/**
 * Get Role
 * @return array
 */
public function getRoles() : array
{
    $roles = $this->roles;
    $name = $roles;
    $name = $name->first()->getName();

    $roles = $roles->first()->getRole();
    $roles = [$roles, $name];

    //dump($roles);
    if (empty($roles)){
        $roles = ['ROLE_USER'];
    }
    return $roles;
}
</code>```

And the code for the twig

```<code>{% for list in user %}
        <TR>

            <TD>{{ list.id }}</TD>
            <TD>{{ list.username }}</TD>
            <TD>{{ list.password }}</TD>
            <TD>{{ list.roles[1] }}</TD>
            <TD>{{ list.isActive }}</TD>

            <TD>
                <a href="{{ path('admin_user_edit', {id: list.id}) }}" class="btn btn-primary">Editer</a>
                <form method="post" action="{{ path('admin_user_delete', {id: list.id}) }}" style="display: inline-block"
                      onsubmit="return confirm('Voulez-vous vraiment supprimer l\'utilisateur ?')">
                    <input type="hidden" name="_method" value="DELETE">
                    <input type="hidden" name="_token" value="{{ csrf_token('delete' ~ list.id) }}">
                    <button class="btn btn-primary">Supprimer</button>
                </form>
            </TD>
        </TR>
    {% endfor %}
</code>```

Body:
I have a problem when i want to connect. Let me explain, I have two User and Role entities that are linked to a ManyToMany relationship, so I have a dynamic user_role table. I would like to connect with the user who has the ROLE_ADMIN but the problem is that I cannot read the object so that it reads this role. This shows me this error.

Warning: Illegal offset type in isset or empty

I think the problem comes from the line "$ role = $ this-> roles-> toArray ();" in getRoles.

Here is the code for User.php

class User implements UserInterface, \Serializable
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=180, unique=true)
     */
    private $username;

    /**
     * @var string The hashed password
     * @ORM\Column(type="string")
     */
    private $password;

    /**
     * @ORM\Column(type="boolean", nullable=false, options={"default" : 0})
     */
    private $isActive;

    /**
     * @ORM\Column(type="string", unique=true, length=64)
     */
    private $token;

    /**
     * @ORM\Column(type="datetime")
     */
    private $expiresAt;

    /**
     * @ORM\ManyToMany(targetEntity="Role", inversedBy="users", fetch="LAZY")
     * @ORM\JoinTable(name="user_role",
     *     joinColumns={
     *      @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="role_id", referencedColumnName="id")
     *   }
     *  )
     */
    private $role;

    public function __construct()
    {
        //$this->repository = $repository;
        $this->role = new ArrayCollection();
        //$this->roles = new Role();
    }

    /**
     * Add userRoles
     *
     * @param \App\Entity\Role $roles
     * @return User
     */
    public function addRoles(\App\Entity\Role $role)
    {
        $this->role[] = $role;

        return $this;
    }

    /**
     * Remove userRoles
     *
     * @param \App\Entity\Role $roles
     */
    public function removeRoles(\App\Entity\Role $role)
    {
        $this->role->removeElement($role);
    }

    /**
     * Get Role
     */
    public function getRoles() : array //Role return
    {
        //$role = $this->repository->find($this->getId());
        //$role = $role->getName();
        $role = $this->role->toArray();

        //$roles = ['ROLE_ADMIN'];
        //$role = $this->serialize($role);
        var_dump($role);
        //$role = $role[0]['name'];

        if (empty($role)) {
            $role[] = ['ROLE_ADMIN'];
        }
        return array_unique($role);
    }

    public function setRoles($role): self
    {
        //$this->roles = $roles;
        if (is_array($role)) {
            $this->role = $role;
        } else {
            $this->role->clear();
            $this->role->add($role);
        }
        return $this;
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUsername(): string
    {
        return (string)$this->username;
    }

    public function setUsername(string $username): self
    {
        $this->username = $username;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getPassword(): string
    {
        return (string)$this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getSalt()
    {
        // not needed when using the "bcrypt" algorithm in security.yaml
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials()
    {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }

    public function getIsActive(): ?bool
    {
        return $this->isActive;
    }

    public function setIsActive(bool $isActive): self
    {
        $this->isActive = $isActive;

        return $this;
    }

    public function getToken(): ?string
    {
        return $this->token;
    }

    public function setToken(string $token): self
    {
        $this->token = $token;

        return $this;
    }

    public function getExpiresAt(): ?\DateTimeInterface
    {
        return $this->expiresAt;
    }

    public function setExpiresAt(\DateTimeInterface $expiresAt): self
    {
        $this->expiresAt = $expiresAt;

        return $this;
    }

    public function isExpired(): bool
    {
        return $this->getExpiresAt() <= new \DateTime();
    }

    public function createToken()
    {
        return substr(str_replace(['+', '/'], ['-', '_'], base64_encode(random_bytes(50))), 0, 63);
    }

    /**
     * String representation of object
     * @link https://php.net/manual/en/serializable.serialize.php
     * @return string the string representation of the object or null
     * Transform object to string
     */
    public function serialize()
    {
        return serialize([
            $this->id,
            $this->username,
            $this->password,
            $this->isActive,
            $this->token,
            $this->expiresAt
        ]);
    }

    /**
     * @param string $serialized
     * Transform string to object
     */
    public function unserialize($serialized)
    {
        list(
            $this->id,
            $this->username,
            $this->password,
            $this->isActive,
            $this->token,
            $this->expiresAt
            ) = unserialize($serialized, ['allowed_classes' => false]);
    }

}

And here is the code for Role.php

class Role implements \Serializable
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $role;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $description;

    /**
     * @ORM\ManyToMany(targetEntity="User", mappedBy="roles")
     */
    private $users;

    public function __construct()
    {
        $this->users = new ArrayCollection();
    }

    public function getUsers()
    {
        return $this->users;
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getRole(): ?string
    {
        return $this->role;
    }

    public function setRole($role)
    {
        $this->role = $role;

        return $this;
    }

    public function getDescription(): ?string
    {
        return $this->description;
    }

    public function setDescription(string $description): self
    {
        $this->description = $description;

        return $this;
    }

    /*
    * methods for RoleInterface
    */
    /*public function getRoles()
    {
        return $this->getRole();
    }*/

    /**
     * Add users
     *
     * @param \App\Entity\User $users
     * @return Role
     */
    public function addUser(\App\Entity\User $users)
    {
        $this->users[] = $users;

        return $this;
    }

    /**
     * Remove users
     *
     * @param \App\Entity\User $users
     */
    public function removeUser(App\Entity\User $users)
    {
        $this->users->removeElement($users);
    }

    /**
     * String representation of object
     * @link https://php.net/manual/en/serializable.serialize.php
     * @return string the string representation of the object or null
     * Transform object to string
     */
    public function serialize()
    {
        return serialize([
            $this->id,
            $this->role,
            $this->description
        ]);
    }

    /**
     * @param string $serialized
     * Transform string to object
     */
    public function unserialize($serialized)
    {
        list(
            $this->id,
            $this->role,
            $this->description
            ) = unserialize($serialized, ['allowed_classes' => false]);
    }
}

then in my controller I did a findAll

/**
* @Route("/admin/user", name="admin_user_index")
* @return \Symfony\Component\HttpFoundation\Response
*/
public function listUser(UserRepository $user)
{
return $this->render('admin/security_user/list_user.html.twig', ['user' => $user->findAll()]);
}

var_dump($role)

/var/www/api/symfony/src/Entity/User.php:108:
array (size=1)
  0 =>
    object(App\Entity\Role)[423]
      private 'id' => int 2
      private 'role' => string '['ROLE_ADMIN']' (length=14)
      private 'description' => string 'administrateur' (length=14)
      private 'users' =>
        object(Doctrine\ORM\PersistentCollection)[425]
          private 'snapshot' =>
            array (size=0)
              ...
          private 'owner' =>
            &object(App\Entity\Role)[423]
          private 'association' =>
            array (size=16)
              ...
          private 'em' =>
            object(Doctrine\ORM\EntityManager)[205]
              ...
          private 'backRefFieldName' => string 'roles' (length=5)
          private 'typeClass' =>
            object(Doctrine\ORM\Mapping\ClassMetadata)[262]
              ...
          private 'isDirty' => boolean false
          protected 'collection' =>
            object(Doctrine\Common\Collections\ArrayCollection)[426]
              ...
          protected 'initialized' => boolean false

Here is the user list code:

{% extends '/admin/base_admin.html.twig' %}

{% block style %}

{% endblock %}

{% block logout %}
    Deconnexion
{% endblock %}

{% block body %}

Liste des utilisateurs

    {% for message in app.flashes('success') %}

            {{ message }}

    {% endfor %}

        <button id="create" class="btn btn-lg btn-primary">
            Annuler
        </button>

        <button id="create" class="btn btn-lg btn-primary">
            Ajouter
        </button>

            ID
            Utilisateur
            Password
            Rôles
            Actif
            Editer

        {% for list in user %}

                {{ list.id }}
                {{ list.username }}
                {{ list.password }}

                    {% for role in list.roles %}
                        {{ role.name }},
                    {% endfor %}

                {{ list.isActive }}

                    Editer
                    <form method="post" action="{{ path('admin_user_delete', {id: list.id}) }}" style="display: inline-block"
                          onsubmit="return confirm('Voulez-vous vraiment supprimer l\'utilisateur ?')">
                        <input type="hidden" name="_method" value="DELETE">
                        <input type="hidden" name="_token" value="{{ csrf_token('delete' ~ list.id) }}">
                        <button class="btn btn-primary">Supprimer</button>
                    </form>

        {% endfor %}

{% endblock %}

I would like to retrieve the role store in the role table.

If any of you can enlighten me, thank you in advance.

Body:
With little help, Here is the solution

/**
 * Get Role
 * @return array
 */
public function getRoles() : array
{
    $roles = $this->roles;
    $name = $roles;
    $name = $name->first()->getName();

    $roles = $roles->first()->getRole();
    $roles = [$roles, $name];

    //dump($roles);
    if (empty($roles)){
        $roles = ['ROLE_USER'];
    }
    return $roles;
}

And the code for the twig

{% for list in user %}
        <TR>

            <TD>{{ list.id }}</TD>
            <TD>{{ list.username }}</TD>
            <TD>{{ list.password }}</TD>
            <TD>{{ list.roles[1] }}</TD>
            <TD>{{ list.isActive }}</TD>

            <TD>
                <a href="{{ path('admin_user_edit', {id: list.id}) }}" class="btn btn-primary">Editer</a>
                <form method="post" action="{{ path('admin_user_delete', {id: list.id}) }}" style="display: inline-block"
                      onsubmit="return confirm('Voulez-vous vraiment supprimer l\'utilisateur ?')">
                    <input type="hidden" name="_method" value="DELETE">
                    <input type="hidden" name="_token" value="{{ csrf_token('delete' ~ list.id) }}">
                    <button class="btn btn-primary">Supprimer</button>
                </form>
            </TD>
        </TR>
    {% endfor %}


问:
localhost redirected you too many times. laravel
I checked with the guards, but they are set perfectly. The problem I figured out is stated below.
This is custom guard    </p>

```<code>Route::get('user/login', 'user\Authuser\userLoginController@showLoginForm')->name('user.login');  //this works fine

Route::name('user.')->prefix('/user')->namespace('user')->group(function(){
   Route::namespace('Authuser')->group(function(){
    Route::get('/login','userLoginController@showLoginForm')->name('login');  //this give error, localhost redirected you too many times
    });
});
</code>```

答:
After you login , means that you are authenticated, then you should access the rest of your endpoints.

Laravel has an easy implementation for that using Auth middleware.

Having said that your routes should look like:

```<code>Route::get('user/login', 'user\Authuser\userLoginController@showLoginForm')->name('user.login');

Route::group(['middleware' => 'auth'], function () {
    Route::name('user.')->prefix('/user')->namespace('user')->group(function(){
        Route::namespace('Authuser')->group(function(){
            Route::get('/login','userLoginController@showLoginForm')->name('login');  //this give error, localhost redirected you too many times
        });
    });
});
</code>```

Inside this group you can add all your application endpoints, that require authentication.

Body:
I checked with the guards, but they are set perfectly. The problem I figured out is stated below.
This is custom guard

Route::get('user/login', 'user\Authuser\userLoginController@showLoginForm')->name('user.login');  //this works fine

Route::name('user.')->prefix('/user')->namespace('user')->group(function(){
   Route::namespace('Authuser')->group(function(){
    Route::get('/login','userLoginController@showLoginForm')->name('login');  //this give error, localhost redirected you too many times
    });
});

Body:
After you login , means that you are authenticated, then you should access the rest of your endpoints.

Laravel has an easy implementation for that using Auth middleware.

Having said that your routes should look like:

Route::get('user/login', 'user\Authuser\userLoginController@showLoginForm')->name('user.login');

Route::group(['middleware' => 'auth'], function () {
    Route::name('user.')->prefix('/user')->namespace('user')->group(function(){
        Route::namespace('Authuser')->group(function(){
            Route::get('/login','userLoginController@showLoginForm')->name('login');  //this give error, localhost redirected you too many times
        });
    });
});

Inside this group you can add all your application endpoints, that require authentication.


问:
Issues with A* implementation, without a grid, in Unity 3D, in c#
I am making a river generator, and I am using a* pathfinding to make it. Earlier I made one and had a few issues, Custom made a* Path finding isn't working very well. I remade it according to this tutorial https://www.youtube.com/watch?v=alU04hvz6L4 except I didn't use a grid, and used something else. I am sure that this is the cause of my issues, but I don't know the solution. The issue is that there is no path when I use this.
The code

```<code>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class APath
{
    private int StraightCost = 10;
    private int DiagonalStraigtCost = 14;
    public APathNode[,] all;
    public bool[,] pathDraw;
    public List<APathNode> open;
    private List<APathNode> closed;
    private float width;
    private float height;
    public int currentX, currentY;

    public List<APathNode> FindPath(int startX, int startY, int endX, int endY)
    {
       //all nodes
        all = new APathNode[75, 75];
      //start node
        APathNode start = new APathNode(startX,startY);
        //end node
        APathNode end = new APathNode(endX, endY);
       //open list
        open = new List<APathNode> { start };
        //closed list
        closed = new List<APathNode>();

        //intializes all
        for(int x = 0; x < 75; x++)
        {
            for(int y =0; y < 75; y++)
            {
                APathNode pathNode = new APathNode(x, y);

                pathNode.g = int.MaxValue;

                pathNode.f = pathNode.g + pathNode.h;
                pathNode.cameFrom = null;
                all[x, y] = pathNode;

            }
        }
      //intializes start node
        start.g = 0;
        start.h = CalculateH(start,end);
        start.f = start.g + start.h;

        //while loop for algorithm
        while(open.Count > 0)
        {
         //Find lowest value
            APathNode current = LowestF(open);
        //if this is the end value
            if(current == end)
            {

                return CalculatePath(end);
            }
         //add check to closed and remove it from open
            open.Remove(current);
            closed.Add(current);

            //checks neighbors
            foreach (APathNode neighbors in GetNeighbors(current))
            {
                if (closed.Contains(neighbors)) continue;

                int tentativeGCost = (int)current.g + (int)CalculateH(current, neighbors);
                if(tentativeGCost < neighbors.g)
                {
                  //updates neighbor
                    neighbors.cameFrom = current;
                    neighbors.g = tentativeGCost;
                    neighbors.h = CalculateH(neighbors, end);
                    neighbors.f = neighbors.g + neighbors.h;

                    //if neighbor isn't in open
                    if (!open.Contains(neighbors))
                    {//add it
                        open.Add(neighbors);
                    }
                }
            }
        }

        return null;

    }
    private List<APathNode> GetNeighbors (APathNode current)
    {
        //neighbors
        List<APathNode> neighbors = new List<APathNode>();
       //left check
        if(current.selectX -1 >= 0)
        {
           //left
            neighbors.Add(all[current.selectX - 1, current.selectY]);
            //left down
            if (current.selectY - 1 >= 0) neighbors.Add(all[current.selectX - 1, current.selectY - 1]);
            //left up
            if (current.selectY + 1 < 75) neighbors.Add(all[current.selectX - 1, current.selectY + 1]);
        }
       //right check
        if (current.selectX + 1 < 75)
        {
           //right
            neighbors.Add(all[current.selectX + 1, current.selectY]);
            //right down
            if (current.selectY - 1 >= 0) neighbors.Add(all[current.selectX + 1, current.selectY - 1]);
            //right up
            if (current.selectY + 1 < 75) neighbors.Add(all[current.selectX + 1, current.selectY + 1]);
        }
        // up
        if (current.selectY - 1 >= 0) neighbors.Add(all[current.selectX, current.selectY - 1]);
      //down
        if (current.selectY + 1 < 75) neighbors.Add(all[current.selectX, current.selectY + 1]);
        return neighbors;

    }

    private List<APathNode> CalculatePath (APathNode end)
    {
        //path
        List<APathNode> path = new List<APathNode>();
        // adds end
        path.Add(end);
      //updates current
        APathNode current = end;
        //updates path
        pathDraw[current.selectX, current.selectY] = true;
        //while their are still previous nodes
        while (current.cameFrom != null)
        {
            //add to path
            path.Add(current.cameFrom);
            //updates current
            current = current.cameFrom;
         //updates path draw
            pathDraw[current.selectX, current.selectY] = true;
        }
       // reverses path
        path.Reverse();
        return path;
    }
    public int CalculateH (APathNode a, APathNode b)
    {
        //h calculating
        int xDistance = Mathf.Abs(a.selectX - b.selectX);
        int yDistance = Mathf.Abs(a.selectY - a.selectY);
        int remaining = Mathf.Abs(xDistance - yDistance);
        return DiagonalStraigtCost * Mathf.Min(xDistance, yDistance) + StraightCost * remaining;

    }

    private APathNode LowestF (List<APathNode> pathNodeList)
    {
        // gets lowest f
        APathNode lowest = pathNodeList[0];

        for(int i = 1; i < pathNodeList.Count; i++)
        {

            if(pathNodeList[i].f < lowest.f)
            {
                lowest = pathNodeList[i];
            }
        }

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

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Rivers : MonoBehaviour
{
    // Start is called before the first frame update
    public Color[] MakeRiver (Color[] color, int mapHeight, int mapWidth)
    {
        Color[] colorss = color;// makes color[]
        APath path = new APath();
        List<APathNode> p = path.FindPath(0, 0, 16, 2);
        bool[,] rPath = path.pathDraw;
        // gets path from that class
     for(int i = 0; i < p.Count; i++)
        {
            colorss[p[i].selectY * 75 + p[i].selectX] = Color.red;
        }
       // shows the river.
        return colorss;
    }

    }
</code>```

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class APathNode

{
    //x, and y
    public int selectX, selectY;
    //constructor
    public APathNode(int selectX, int selectY)
    {
        this.selectX = selectX;
        this.selectY = selectY;
    }
    //g
    public float g;
   //h
    public float h;

    //f
    public float f;
    public APathNode cameFrom;

}
</code>```

If anyone could help me I would be glad. It would be my weekend's work be worth it. Thank you and have a good day/evening/night.

答: Do you still want to use A* because dynamic navmesh generation works better than A* and gives better results on Unity profiler too</p>

Body:
I am making a river generator, and I am using a* pathfinding to make it. Earlier I made one and had a few issues, Custom made a* Path finding isn't working very well. I remade it according to this tutorial https://www.youtube.com/watch?v=alU04hvz6L4 except I didn't use a grid, and used something else. I am sure that this is the cause of my issues, but I don't know the solution. The issue is that there is no path when I use this.
The code

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class APath
{
    private int StraightCost = 10;
    private int DiagonalStraigtCost = 14;
    public APathNode[,] all;
    public bool[,] pathDraw;
    public List<APathNode> open;
    private List<APathNode> closed;
    private float width;
    private float height;
    public int currentX, currentY;

    public List<APathNode> FindPath(int startX, int startY, int endX, int endY)
    {
       //all nodes
        all = new APathNode[75, 75];
      //start node
        APathNode start = new APathNode(startX,startY);
        //end node
        APathNode end = new APathNode(endX, endY);
       //open list
        open = new List<APathNode> { start };
        //closed list
        closed = new List<APathNode>();

        //intializes all
        for(int x = 0; x < 75; x++)
        {
            for(int y =0; y < 75; y++)
            {
                APathNode pathNode = new APathNode(x, y);

                pathNode.g = int.MaxValue;

                pathNode.f = pathNode.g + pathNode.h;
                pathNode.cameFrom = null;
                all[x, y] = pathNode;

            }
        }
      //intializes start node
        start.g = 0;
        start.h = CalculateH(start,end);
        start.f = start.g + start.h;

        //while loop for algorithm
        while(open.Count > 0)
        {
         //Find lowest value
            APathNode current = LowestF(open);
        //if this is the end value
            if(current == end)
            {

                return CalculatePath(end);
            }
         //add check to closed and remove it from open
            open.Remove(current);
            closed.Add(current);

            //checks neighbors
            foreach (APathNode neighbors in GetNeighbors(current))
            {
                if (closed.Contains(neighbors)) continue;

                int tentativeGCost = (int)current.g + (int)CalculateH(current, neighbors);
                if(tentativeGCost < neighbors.g)
                {
                  //updates neighbor
                    neighbors.cameFrom = current;
                    neighbors.g = tentativeGCost;
                    neighbors.h = CalculateH(neighbors, end);
                    neighbors.f = neighbors.g + neighbors.h;

                    //if neighbor isn't in open
                    if (!open.Contains(neighbors))
                    {//add it
                        open.Add(neighbors);
                    }
                }
            }
        }

        return null;

    }
    private List<APathNode> GetNeighbors (APathNode current)
    {
        //neighbors
        List<APathNode> neighbors = new List<APathNode>();
       //left check
        if(current.selectX -1 >= 0)
        {
           //left
            neighbors.Add(all[current.selectX - 1, current.selectY]);
            //left down
            if (current.selectY - 1 >= 0) neighbors.Add(all[current.selectX - 1, current.selectY - 1]);
            //left up
            if (current.selectY + 1 < 75) neighbors.Add(all[current.selectX - 1, current.selectY + 1]);
        }
       //right check
        if (current.selectX + 1 < 75)
        {
           //right
            neighbors.Add(all[current.selectX + 1, current.selectY]);
            //right down
            if (current.selectY - 1 >= 0) neighbors.Add(all[current.selectX + 1, current.selectY - 1]);
            //right up
            if (current.selectY + 1 < 75) neighbors.Add(all[current.selectX + 1, current.selectY + 1]);
        }
        // up
        if (current.selectY - 1 >= 0) neighbors.Add(all[current.selectX, current.selectY - 1]);
      //down
        if (current.selectY + 1 < 75) neighbors.Add(all[current.selectX, current.selectY + 1]);
        return neighbors;

    }

    private List<APathNode> CalculatePath (APathNode end)
    {
        //path
        List<APathNode> path = new List<APathNode>();
        // adds end
        path.Add(end);
      //updates current
        APathNode current = end;
        //updates path
        pathDraw[current.selectX, current.selectY] = true;
        //while their are still previous nodes
        while (current.cameFrom != null)
        {
            //add to path
            path.Add(current.cameFrom);
            //updates current
            current = current.cameFrom;
         //updates path draw
            pathDraw[current.selectX, current.selectY] = true;
        }
       // reverses path
        path.Reverse();
        return path;
    }
    public int CalculateH (APathNode a, APathNode b)
    {
        //h calculating
        int xDistance = Mathf.Abs(a.selectX - b.selectX);
        int yDistance = Mathf.Abs(a.selectY - a.selectY);
        int remaining = Mathf.Abs(xDistance - yDistance);
        return DiagonalStraigtCost * Mathf.Min(xDistance, yDistance) + StraightCost * remaining;

    }

    private APathNode LowestF (List<APathNode> pathNodeList)
    {
        // gets lowest f
        APathNode lowest = pathNodeList[0];

        for(int i = 1; i < pathNodeList.Count; i++)
        {

            if(pathNodeList[i].f < lowest.f)
            {
                lowest = pathNodeList[i];
            }
        }

        return lowest;
    }
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Rivers : MonoBehaviour
{
    // Start is called before the first frame update
    public Color[] MakeRiver (Color[] color, int mapHeight, int mapWidth)
    {
        Color[] colorss = color;// makes color[]
        APath path = new APath();
        List<APathNode> p = path.FindPath(0, 0, 16, 2);
        bool[,] rPath = path.pathDraw;
        // gets path from that class
     for(int i = 0; i < p.Count; i++)
        {
            colorss[p[i].selectY * 75 + p[i].selectX] = Color.red;
        }
       // shows the river.
        return colorss;
    }

    }

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class APathNode

{
    //x, and y
    public int selectX, selectY;
    //constructor
    public APathNode(int selectX, int selectY)
    {
        this.selectX = selectX;
        this.selectY = selectY;
    }
    //g
    public float g;
   //h
    public float h;

    //f
    public float f;
    public APathNode cameFrom;

}

If anyone could help me I would be glad. It would be my weekend's work be worth it. Thank you and have a good day/evening/night.


问:
Devise methods in helper file?
I have a helper module ModelHelper. I want to use user_signed_in? method inside that helper module. But it shows error. How can I call this method inside helper file.</p>

答:
I think that you can use current_user.present?
Anyway, rails helpers are very ugly and I advise to don't use it at all

Title: Devise methods in helper file?


问:
How can i change it to show user to input in minutes?
I have tried to change the user input in minutes but unfortunately when I tried doing that nothing changed.

What I did was instead of "remseconds" i changed it to remminuts and changed the math as well to "x 60" but nothing happened.

const container = document.querySelector('.counter');
const buttonsDiv = document.querySelector('.buttons');
const secInput = document.getElementById('seconds');

var seconds;
var remseconds;
var minuts;
var toCount = false;

function toSubmit() {
  display('start');
  remove('seconds');
  remove('ok');
  seconds = Number(secInput.value);
  counting();
}

function display(e) {
  document.getElementById(e).style.display = 'block';
}

function remove(e) {
  document.getElementById(e).style.display = 'none';
}

function check(stat) {
  if (stat.id == "start") {
    display("stop");
    remove("start");
    toCount = true;
  } else if (stat.id == "stop") {
    display("continue");
    remove("stop");
    toCount = false
  } else {
    display("stop");
    remove("continue");
    toCount = true;
  }
}

function count() {
  if (seconds > 0) {
    if (toCount == true) {
      seconds--;
      remseconds = seconds % 60;
      minuts = Math.floor(seconds / 60);

      if (minuts < 10) {
        minuts = "0" + minuts;
      }

      if (remseconds < 10) {
        remseconds = "0" + remseconds;
      }

      container.innerHTML = minuts + " : " + remseconds;
    }
  } else {
    container.innerHTML = "DONE!";
    buttonsDiv.style.opacity = "0";
  }
}

function counting() {
  remseconds = seconds % 60;
  minuts = Math.floor(seconds / 60);

  if (remseconds < 10) {
    remseconds = "0" + remseconds;
  }

  container.innerHTML = minuts + " : " + remseconds;
  setInterval(count, 1000);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html class="class2">

<head>
  <title>CountDown</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">
</head>

<body>
  <header>
    <h1>CountDown</h1>
  </header>
  <div class="content">
    <div class="counter"></div>
    <input type="number" id="seconds" placeholder="Seconds">
    <div class="buttons">
      <button class="btn start" id="start" value="1" onclick="check(this)">Start</button>
      <button class="btn start" id="continue" value="1" onclick="check(this)">Continue</button>
      <button class="btn stop" id="stop" value="0" onclick="check(this)">Stop</button>
      <button class="btn start" id="ok" onclick="toSubmit()">Submit</button>
    </div>
  </div>
  <script type="text/javascript" src="main.js"></script>

</body>

</html></code>```

If you have any solutions please let me know.

答:
I edited the answer here for minutes: js seconds countdown

Get minutes and only convert it to seconds by x60 in counting()

const container = document.querySelector('.counter');
const buttonsDiv = document.querySelector('.buttons');
const minInput = document.getElementById('minutes');

var seconds;
var remseconds;
var minuts;
var toCount = false;

function toSubmit() {
  display('start');
  remove('minutes');
  remove('ok');
  minuts= Number(minInput.value);
  counting();
}

function display(e) {
  document.getElementById(e).style.display = 'block';
}

function remove(e) {
  document.getElementById(e).style.display = 'none';
}

function check(stat) {
  if (stat.id == "start") {
    display("stop");
    remove("start");
    toCount = true;
  } else if (stat.id == "stop") {
    display("continue");
    remove("stop");
    toCount = false
  } else {
    display("stop");
    remove("continue");
    toCount = true;
  }
}

function count() {
  if (seconds > 0) {
    if (toCount == true) {
      seconds--;
      remseconds = seconds % 60;
      minuts = Math.floor(seconds / 60);

      if (minuts < 10) {
        minuts = "0" + minuts;
      }

      if (remseconds < 10) {
        remseconds = "0" + remseconds;
      }

      container.innerHTML = minuts + " : " + remseconds;
    }
  } else {
    container.innerHTML = "DONE!";
    buttonsDiv.style.opacity = "0";
  }
}

function counting() {
  seconds = minuts*60;
  remseconds = seconds % 60;
  //minuts = Math.floor(seconds / 60);

  if (remseconds < 10) {
    remseconds = "0" + remseconds;
  }

  container.innerHTML = minuts + " : " + remseconds;
  setInterval(count, 1000);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

html, body{
    height: 100%;
}
body{
    width: 100%;
    height: 100%;
    background: linear-gradient(to left top, #0045D6, #00A9f6);
}

header{
    width: 100%;
    height: 13vh;
    background-color: #fff;
    color: #0045F6;
    display: flex;
    justify-content: center;
    align-items: center;
}

.content{
    width: 100%;
    height: 60vh;
    font-size: 3rem;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}

.content #minutes{
    width: 250px;
    font-size: 2rem;
    padding: 1rem;
    outline: none;
    background: none;
    border: none;
    border-bottom: 3px solid #fff;
    color: #fff;
}

#minutes::placeholder{
    color: #ddd;
    font-size: 1.7rem;
}

.btn{
    background-color: #fff;
    border-radius: 4px;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 0.8rem 1.7rem;
    font-size: 1.2rem;
    font-weight: 700;
}

.start{
    color: #1f0;
}

.stop{
    color: #E00;
}

#start, #stop, #continue{
    display: none;
}

.counter{
    color: #fff;
}</code>```

 <!DOCTYPE html>

    <title>CountDown</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">

CountDown

        <input type="number" id="minutes" placeholder="Minutes">

            <button class="btn start" id="start" value="1" onclick="check(this)">Start</button>
            <button class="btn start" id="continue" value="1" onclick="check(this)">Continue</button>
            <button class="btn stop" id="stop" value="0" onclick="check(this)">Stop</button>
            <button class="btn start" id="ok" onclick="toSubmit()">Submit</button>

```

Body:
I have tried to change the user input in minutes but unfortunately when I tried doing that nothing changed.

What I did was instead of "remseconds" i changed it to remminuts and changed the math as well to "x 60" but nothing happened.

const container = document.querySelector('.counter');
const buttonsDiv = document.querySelector('.buttons');
const secInput = document.getElementById('seconds');

var seconds;
var remseconds;
var minuts;
var toCount = false;

function toSubmit() {
  display('start');
  remove('seconds');
  remove('ok');
  seconds = Number(secInput.value);
  counting();
}

function display(e) {
  document.getElementById(e).style.display = 'block';
}

function remove(e) {
  document.getElementById(e).style.display = 'none';
}

function check(stat) {
  if (stat.id == "start") {
    display("stop");
    remove("start");
    toCount = true;
  } else if (stat.id == "stop") {
    display("continue");
    remove("stop");
    toCount = false
  } else {
    display("stop");
    remove("continue");
    toCount = true;
  }
}

function count() {
  if (seconds > 0) {
    if (toCount == true) {
      seconds--;
      remseconds = seconds % 60;
      minuts = Math.floor(seconds / 60);

      if (minuts < 10) {
        minuts = "0" + minuts;
      }

      if (remseconds < 10) {
        remseconds = "0" + remseconds;
      }

      container.innerHTML = minuts + " : " + remseconds;
    }
  } else {
    container.innerHTML = "DONE!";
    buttonsDiv.style.opacity = "0";
  }
}

function counting() {
  remseconds = seconds % 60;
  minuts = Math.floor(seconds / 60);

  if (remseconds < 10) {
    remseconds = "0" + remseconds;
  }

  container.innerHTML = minuts + " : " + remseconds;
  setInterval(count, 1000);
}

<!DOCTYPE html>

  <title>CountDown</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">

CountDown

    <input type="number" id="seconds" placeholder="Seconds">

      <button class="btn start" id="start" value="1" onclick="check(this)">Start</button>
      <button class="btn start" id="continue" value="1" onclick="check(this)">Continue</button>
      <button class="btn stop" id="stop" value="0" onclick="check(this)">Stop</button>
      <button class="btn start" id="ok" onclick="toSubmit()">Submit</button>

If you have any solutions please let me know.

Body:
I edited the answer here for minutes: js seconds countdown

Get minutes and only convert it to seconds by x60 in counting()

const container = document.querySelector('.counter');
const buttonsDiv = document.querySelector('.buttons');
const minInput = document.getElementById('minutes');

var seconds;
var remseconds;
var minuts;
var toCount = false;

function toSubmit() {
  display('start');
  remove('minutes');
  remove('ok');
  minuts= Number(minInput.value);
  counting();
}

function display(e) {
  document.getElementById(e).style.display = 'block';
}

function remove(e) {
  document.getElementById(e).style.display = 'none';
}

function check(stat) {
  if (stat.id == "start") {
    display("stop");
    remove("start");
    toCount = true;
  } else if (stat.id == "stop") {
    display("continue");
    remove("stop");
    toCount = false
  } else {
    display("stop");
    remove("continue");
    toCount = true;
  }
}

function count() {
  if (seconds > 0) {
    if (toCount == true) {
      seconds--;
      remseconds = seconds % 60;
      minuts = Math.floor(seconds / 60);

      if (minuts < 10) {
        minuts = "0" + minuts;
      }

      if (remseconds < 10) {
        remseconds = "0" + remseconds;
      }

      container.innerHTML = minuts + " : " + remseconds;
    }
  } else {
    container.innerHTML = "DONE!";
    buttonsDiv.style.opacity = "0";
  }
}

function counting() {
  seconds = minuts*60;
  remseconds = seconds % 60;
  //minuts = Math.floor(seconds / 60);

  if (remseconds < 10) {
    remseconds = "0" + remseconds;
  }

  container.innerHTML = minuts + " : " + remseconds;
  setInterval(count, 1000);
}

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

html, body{
    height: 100%;
}
body{
    width: 100%;
    height: 100%;
    background: linear-gradient(to left top, #0045D6, #00A9f6);
}

header{
    width: 100%;
    height: 13vh;
    background-color: #fff;
    color: #0045F6;
    display: flex;
    justify-content: center;
    align-items: center;
}

.content{
    width: 100%;
    height: 60vh;
    font-size: 3rem;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}

.content #minutes{
    width: 250px;
    font-size: 2rem;
    padding: 1rem;
    outline: none;
    background: none;
    border: none;
    border-bottom: 3px solid #fff;
    color: #fff;
}

#minutes::placeholder{
    color: #ddd;
    font-size: 1.7rem;
}

.btn{
    background-color: #fff;
    border-radius: 4px;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 0.8rem 1.7rem;
    font-size: 1.2rem;
    font-weight: 700;
}

.start{
    color: #1f0;
}

.stop{
    color: #E00;
}

#start, #stop, #continue{
    display: none;
}

.counter{
    color: #fff;
}

 <!DOCTYPE html>
<html class="class2">
<head>
    <title>CountDown</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">
</head>
<body>
    <header>
        <h1>CountDown</h1>
    </header>
    <div class="content">
        <div class="counter"></div>
        <input type="number" id="minutes" placeholder="Minutes">
        <div class="buttons">
            <button class="btn start" id="start" value="1" onclick="check(this)">Start</button>
            <button class="btn start" id="continue" value="1" onclick="check(this)">Continue</button>
            <button class="btn stop" id="stop" value="0" onclick="check(this)">Stop</button>
            <button class="btn start" id="ok" onclick="toSubmit()">Submit</button>
        </div>
    </div>
    <script type="text/javascript" src="main.js"></script>

</body>
</html>


问:
NoReverseMatch at ...... in django
I am working on a blog site where you can search for posts by using searching with keywords (basically a normal searchbar).

I have imported Q from django.db.models

The view I created:

```<code>def search(request):
    queryset = Article.objects.all()
    query =  request.GET.get('q')
    if query:
        queryset = queryset.filter(
            Q(title__icontains=query) |
            Q(overview__icontains=query)
        ).distinct()

    context = {
        'queryset': queryset,
    }
    return render(request, 'search_results.html', context)
</code>```

The urlpattern:

```<code>path('search/', search, name='search-results'),
</code>```

The form itself:

```<code><form action="{% url 'search' %}" class="search-form">{% csrf_token %}
              <button type="submit" class="submit"><i class="icon-search"></i></button>
                <div class="form-group">
                  <span class="icon icon-search"></span>
                  <input type="text" class="form-control" name="q" placeholder="Type a keyword and hit enter">
                </div>
              </form>
</code>```

When I want to access the page to which I have put this form in, it says:
Reverse for 'search' not found. 'search' is not a valid view function or pattern name.

Below it also shows this:

```<code>1   <!DOCTYPE html>
2   <html lang="en">
3
4   {% include 'head.html' %}
5
6   <body>
7
8       {% include 'header.html' %}
9
10      {% block content %}
</code>```

I have tried adding/removing csrf_token and the submit button, but the result is always the same. Please help!

答:
I assume the form is a part of the head.html. You don't need the csrf_token since it's not a post form.

In urlpatterns, change your url entry to:

path('search/', views.search, name='search'),
```

At the template, action="{% url 'search' %}" refers to the name of the url ... you could also add role='search' attribute to your form. Hope it helps

Title: NoReverseMatch at ...... in django

Body:
I am working on a blog site where you can search for posts by using searching with keywords (basically a normal searchbar).

I have imported Q from django.db.models

The view I created:

def search(request):
    queryset = Article.objects.all()
    query =  request.GET.get('q')
    if query:
        queryset = queryset.filter(
            Q(title__icontains=query) |
            Q(overview__icontains=query)
        ).distinct()

    context = {
        'queryset': queryset,
    }
    return render(request, 'search_results.html', context)

The urlpattern:

path('search/', search, name='search-results'),

The form itself:

<form action="{% url 'search' %}" class="search-form">{% csrf_token %}
              <button type="submit" class="submit"></button>

                  <input type="text" class="form-control" name="q" placeholder="Type a keyword and hit enter">

              </form>

When I want to access the page to which I have put this form in, it says:
Reverse for 'search' not found. 'search' is not a valid view function or pattern name.

Below it also shows this:

1   <!DOCTYPE html>
2
3
4   {% include 'head.html' %}
5
6
7
8       {% include 'header.html' %}
9
10      {% block content %}

I have tried adding/removing csrf_token and the submit button, but the result is always the same. Please help!

Body:
I assume the form is a part of the head.html. You don't need the csrf_token since it's not a post form.

In urlpatterns, change your url entry to:

path('search/', views.search, name='search'),

At the template, action="{% url 'search' %}" refers to the name of the url ... you could also add role='search' attribute to your form. Hope it helps


问:
PHP can't get post data from jQuery dynamic method
I use .after method in Jquery to insert the html element.

This is my Jquery Code

$('#add_terms').click(function () {
  var i = $('#terms>textarea').length;
  $terms = $('#terms' + i);
  i++;
  console.log($terms);
  $terms.after('

' + i + '.    <textarea id="terms' + i + '" name="terms[]" ' + 'cols="60" rows="2" style="vertical-align:middle;"></textarea>');
})
```

<p>My html:</p>

<pre class="lang-html prettyprint-override"><code> <table width="98%" cellspacing="1" cellpadding="3" style="border-collapse:separate; border-spacing:0px 10px;">
<form method="post" enctype="multipart/form-data" name="form1" id="form1" action='' target="_self">
<tr>
  <td align="center"> terms</td>
  <td id="terms">
    1.
    <textarea id="terms1" name="terms[]" cols="60" rows="2"
      style="vertical-align:middle;"><?php echo $terms1?></textarea>
    <br><br>
    2.
    <textarea id="terms2" name="terms[]" cols="60" rows="2"
      style="vertical-align:middle;"><?php echo $terms2?></textarea>
    <br>

    <input id="add_terms" name="add_terms" type="button" class="bt-add" value="add" style="margin-top:10px">
  </td>
</tr>
<tr>
<td colspan="2" align="center">
<input id="add" name="add" type="submit">
<input id="clear" name="clear" type="reset"  class="bt-return">
</td>
</tr>
</form>
</table>
</code>```

I post the form,then I can get the value of terms1 and terms2 with using

print_r($_POST['terms']);

However, I can't get the value of terms3, terms4.

答:
Hope this help you.</p>

```<code><form method="post" enctype="multipart/form-data" name="form1" id="form1" action='' target="_self">
  <td align="center"> terms</td>
  <td id="terms">
    1.
    <textarea id="terms1" name="terms[]" cols="60" rows="2"
      style="vertical-align:middle;"><?php echo $terms1?></textarea>
    <br><br>
    2.
    <textarea id="terms2" name="terms[]" cols="60" rows="2"
      style="vertical-align:middle;"><?php echo $terms2?></textarea>
    <br>

    <input id="add_terms" name="add_terms" type="submit" class="bt-add" value="add" style="margin-top:10px">
  </td>
</form>
</code>```

Body:
I use .after method in Jquery to insert the html element.

This is my Jquery Code

$('#add_terms').click(function () {
  var i = $('#terms>textarea').length;
  $terms = $('#terms' + i);
  i++;
  console.log($terms);
  $terms.after('

' + i + '.    <textarea id="terms' + i + '" name="terms[]" ' + 'cols="60" rows="2" style="vertical-align:middle;"></textarea>');
})

My html:

<form method="post" enctype="multipart/form-data" name="form1" id="form1" action='' target="_self">

   terms

    1.
    <textarea id="terms1" name="terms[]" cols="60" rows="2"
      style="vertical-align:middle;"><?php echo $terms1?></textarea>

    2.
    <textarea id="terms2" name="terms[]" cols="60" rows="2"
      style="vertical-align:middle;"><?php echo $terms2?></textarea>

    <input id="add_terms" name="add_terms" type="button" class="bt-add" value="add" style="margin-top:10px">

<input id="add" name="add" type="submit">
<input id="clear" name="clear" type="reset"  class="bt-return">

</form>

I post the form,then I can get the value of terms1 and terms2 with using

print_r($_POST['terms']);

However, I can't get the value of terms3, terms4.

Body:
Hope this help you.

<form method="post" enctype="multipart/form-data" name="form1" id="form1" action='' target="_self">
  <td align="center"> terms</td>
  <td id="terms">
    1.
    <textarea id="terms1" name="terms[]" cols="60" rows="2"
      style="vertical-align:middle;"><?php echo $terms1?></textarea>
    <br><br>
    2.
    <textarea id="terms2" name="terms[]" cols="60" rows="2"
      style="vertical-align:middle;"><?php echo $terms2?></textarea>
    <br>

    <input id="add_terms" name="add_terms" type="submit" class="bt-add" value="add" style="margin-top:10px">
  </td>
</form>


问:
remove ON DELETE CASCADE
I have a child table. and foreign key there with ON DELETE CASCADE while creating the table.

There are no records either in child or parent table.

I want the primary key, foreign key to be as they are but want to remove only the CASCADING option from the child table .

is there anyway that i can Alter that child table.

Thank you.

答:
The table:

```SHOW CREATE TABLE table; ```

```<code>CREATE TABLE `table` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `id_departamento` int(11) unsigned DEFAULT NULL,
  `name` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  KEY `id_departamento` (`id_departamento`),
  CONSTRAINT `departamentos_direcciones_pedidos_ibfk_1` FOREIGN KEY (`id_departamento`) REFERENCES `departamentos` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
</code>```

First drop foreign key.

```ALTER TABLE departamentos_direcciones_pedidos DROP CONSTRAINT departamentos_direcciones_pedidos_ibfk_1;```

Second, create the correct foreign key

```ALTER TABLE departamentos_direcciones_pedidos ADD FOREIGN KEY (id_departamento) REFERENCES departamentos(id);```

Title: remove ON DELETE CASCADE

Body:
The table:

SHOW CREATE TABLE table;

CREATE TABLE `table` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `id_departamento` int(11) unsigned DEFAULT NULL,
  `name` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  KEY `id_departamento` (`id_departamento`),
  CONSTRAINT `departamentos_direcciones_pedidos_ibfk_1` FOREIGN KEY (`id_departamento`) REFERENCES `departamentos` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

First drop foreign key.

ALTER TABLE departamentos_direcciones_pedidos DROP CONSTRAINT departamentos_direcciones_pedidos_ibfk_1;

Second, create the correct foreign key

ALTER TABLE departamentos_direcciones_pedidos ADD FOREIGN KEY (id_departamento) REFERENCES departamentos(id);