问:
TempData Cookie Issue. The size of the request headers is too long
In Controller, I save a collection of errors into cookies via TempData

```<code>var messages = new List<Message>();
...
TempData.Put("Errors", messages);
</code>```

TempData.Put is an extension method

```<code>public static class TempDataExtensions
    {

        public static void Put<T>(this ITempDataDictionary tempData, string key, T value) where T : class
        {
            tempData[key] = JsonConvert.SerializeObject(value);
        }

        public static T Get<T>(this ITempDataDictionary tempData, string key) where T : class
        {
            tempData.TryGetValue(key, out object o);
            return o == null ? null : JsonConvert.DeserializeObject<T>((string)o);
        }
    }
</code>```

When HTML is loaded, I see

and several cookies were created (Chrome Developer Tools > Application > Storage > Cookies)

The issue I think, is that total size of Cookies is hitting some Cookie Size limit somewhere.

So I have two questions :
Is it possible to change the cookie size limit (in web.config for example) ?
Is it possible to use session instead of cookies for TempData ?

I tried the second approach and if I change the startup.cs file

```<code>\\ ConfigureServices method

services.AddMvc()
   .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
   .AddSessionStateTempDataProvider();

services.AddSession();

\\ Configure method

app.UseSession();

app.UseMvc(routes =>
{
     routes.MapRoute(
     name: "default",
     template: "{controller=Home}/{action=Index}/{id?}");
});
</code>```

The TempData are still using Cookies, do I forgot some setting somewhere ?

答:
You can use HTTP cookies or session state as storage mechanism for TempData. The cookie-based TempData provider is the default.
You can read more about Choose a TempData provider.

Based on the following example from docs you can enable the session-based TempData provider, by calling AddSessionStateTempDataProvider extension method. The order of middleware is important.

Be aware of DefaultTempDataSerializer limitations pointed out at
bottom of this answer.

Example

Hers is a working deployment using the following setup that I have for Srartup:

```<code>public class Startup
{
    public Startup(IConfiguration configuration) { Configuration = configuration; }
    public IConfiguration Configuration { get; }
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddSessionStateTempDataProvider();
        services.AddSession();
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();
        app.UseSession();
        app.UseMvc(routes => {
            routes.MapRoute(name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
</code>```

The HomeController:

```<code>public class HomeController : Controller
{
    public IActionResult Index()
    {
        TempData["LargeData"] = new string('a', 1 * 1024 * 1024);
        return View();
    }
}
</code>```

And the Index View:

```<code>@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome - @(((string)TempData["LargeData"]).Length)</h1>
    <p>Learn about <a href="https://learn.microsoft.com/aspnet/core">
       building Web apps with ASP.NET Core</a>.</p>
</div>
</code>```

DefaultTempDataSerializer supported types

Be aware of DefaultTempDataSerializer supported type limitations:

```<code>public override bool CanSerializeType(Type type)
{
    if (type == null)
    {
        throw new ArgumentNullException(nameof(type));
    }

    type = Nullable.GetUnderlyingType(type) ?? type;

    return
        type.IsEnum ||
        type == typeof(int) ||
        type == typeof(string) ||
        type == typeof(bool) ||
        type == typeof(DateTime) ||
        type == typeof(Guid) ||
        typeof(ICollection<int>).IsAssignableFrom(type) ||
        typeof(ICollection<string>).IsAssignableFrom(type) ||
        typeof(IDictionary<string, string>).IsAssignableFrom(type);
}
</code>```

Body:
In Controller, I save a collection of errors into cookies via TempData

var messages = new List<Message>();
...
TempData.Put("Errors", messages);

TempData.Put is an extension method

public static class TempDataExtensions
    {

        public static void Put<T>(this ITempDataDictionary tempData, string key, T value) where T : class
        {
            tempData[key] = JsonConvert.SerializeObject(value);
        }

        public static T Get<T>(this ITempDataDictionary tempData, string key) where T : class
        {
            tempData.TryGetValue(key, out object o);
            return o == null ? null : JsonConvert.DeserializeObject<T>((string)o);
        }
    }

When HTML is loaded, I see

and several cookies were created (Chrome Developer Tools > Application > Storage > Cookies)

The issue I think, is that total size of Cookies is hitting some Cookie Size limit somewhere.

So I have two questions :
Is it possible to change the cookie size limit (in web.config for example) ?
Is it possible to use session instead of cookies for TempData ?

I tried the second approach and if I change the startup.cs file

\\ ConfigureServices method

services.AddMvc()
   .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
   .AddSessionStateTempDataProvider();

services.AddSession();

\\ Configure method

app.UseSession();

app.UseMvc(routes =>
{
     routes.MapRoute(
     name: "default",
     template: "{controller=Home}/{action=Index}/{id?}");
});

The TempData are still using Cookies, do I forgot some setting somewhere ?

Body:
You can use HTTP cookies or session state as storage mechanism for TempData. The cookie-based TempData provider is the default.
You can read more about Choose a TempData provider.

Based on the following example from docs you can enable the session-based TempData provider, by calling AddSessionStateTempDataProvider extension method. The order of middleware is important.

Be aware of DefaultTempDataSerializer limitations pointed out at
bottom of this answer.

Example

Hers is a working deployment using the following setup that I have for Srartup:

public class Startup
{
    public Startup(IConfiguration configuration) { Configuration = configuration; }
    public IConfiguration Configuration { get; }
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddSessionStateTempDataProvider();
        services.AddSession();
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();
        app.UseSession();
        app.UseMvc(routes => {
            routes.MapRoute(name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

The HomeController:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        TempData["LargeData"] = new string('a', 1 * 1024 * 1024);
        return View();
    }
}

And the Index View:

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome - @(((string)TempData["LargeData"]).Length)</h1>
    <p>Learn about <a href="https://learn.microsoft.com/aspnet/core">
       building Web apps with ASP.NET Core</a>.</p>
</div>

DefaultTempDataSerializer supported types

Be aware of DefaultTempDataSerializer supported type limitations:

public override bool CanSerializeType(Type type)
{
    if (type == null)
    {
        throw new ArgumentNullException(nameof(type));
    }

    type = Nullable.GetUnderlyingType(type) ?? type;

    return
        type.IsEnum ||
        type == typeof(int) ||
        type == typeof(string) ||
        type == typeof(bool) ||
        type == typeof(DateTime) ||
        type == typeof(Guid) ||
        typeof(ICollection<int>).IsAssignableFrom(type) ||
        typeof(ICollection<string>).IsAssignableFrom(type) ||
        typeof(IDictionary<string, string>).IsAssignableFrom(type);
}


来源: stackexchange

问:
Node JS Proper Content-Type for responses
Is there a reason that I should not be sending my content-type as binary for everything? I am a bit naive about proper http but it seems to work for everything. What are some of the pitfalls I will run into working this way?</p>

答:
If you specify the right content-type, the application/browser requesting the file can handle it properly

For example, if You're downloading a pdf file, the browser knows how to handle the content type "application/pdf" and will open the file directly in the browser, if it doesn't know the type, it will just ask you to download the file

Browser also let you specify a specific program from which you can open a specific type of file, for example, if you download a torrent file, you can tell your browser to open it with uTorrent, and the next time a torrent file is downloaded it will be also opened with uTorrent directly

In Node.js, you can get the content type of a file doing the following:

```<code>type = require('mime').lookup(path);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If you specify the right content-type, the application/browser requesting the file can handle it properly

For example, if You're downloading a pdf file, the browser knows how to handle the content type "application/pdf" and will open the file directly in the browser, if it doesn't know the type, it will just ask you to download the file

Browser also let you specify a specific program from which you can open a specific type of file, for example, if you download a torrent file, you can tell your browser to open it with uTorrent, and the next time a torrent file is downloaded it will be also opened with uTorrent directly

In Node.js, you can get the content type of a file doing the following:

type = require('mime').lookup(path);


问:
INTELIJ terminal only showing directory instead of running a command prompt
Sorry if it is a dumb question, but i was running my code perfectly and the terminal was reacting when i ran my program.

After turning my laptop off and on I cant seem to get it to show my SOP commands in the terminal. All i get is the directory of where my program is saved in.

答:
right click on projet in your case and then
right click on "Lab2" and click 'open in terminal'</p>

ContentLicense: CC BY-SA 4.0


问:
Merge two objects(optimizing)
I have n objects(with some nested structure). In the end, I'm expecting to get one merged object with all fields.

```<code>const result = {
  firstParam: {
    x: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    y: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    z: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    }
  },
  secondParam: {
    x: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    y: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    z: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    }
  },
  thirdParam: {
    x: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    y: {
      uuid1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    z: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    }
  }
}

const newObj1 = {
  firstParam: {
    x: {
      id2: ["somedata1", "somedata2"]
    },
    y: {
      id2: ["somedata1", "somedata2"]
    },
    z: {
      id2: ["somedata1", "somedata2"]
    }
  },
  secondParam: {
    x: {
      id2: ["somedata1", "somedata2"]
    },
    y: {
      id2: ["somedata1", "somedata2"]
    },
    z: {
      id2: ["somedata1", "somedata2"]
    }
  },
  thirdParam: {
    x: {
      id2: ["somedata1", "somedata2"]
    },
    y: {
      id2: ["somedata1", "somedata2"]
    },
    z: {
      id2: ["somedata1", "somedata2"]
    }
  }
}

const merge = (result, newObj) => {
  console.time("test merge")
  Object.keys(result).forEach(key => {
    result[key] = {
      x: {
        ...result[key].x,
        ...newObj[key].x
      },
      y: {
        ...result[key].y,
        ...newObj[key].y
      },
      z: {
        ...result[key].z,
        ...newObj[key].z
      }
    }
  })
  console.timeEnd("test merge")

  return result;
}

merge(result, newObj1);
</code>```

This solution gives me an expected result(I'm getting an obj2, obj3 ... objn and every iteration I'm merging it to result), but when I'm getting more than 500 or 1000 newObj it works pretty slow. Is there any way to optimize it?

答:
I afford make it run in the half time by replacing object keys iteration with for in:

Old:

```<code>results[key] = {
    x: {
        ...results[key].x,
        ...newObject[key].x
    },
    y: {
        ...results[key].y,
        ...newObj1[key].y
        },
    z: {
           ...results[key].z,
           ...newObj1[key].z
        }
    }
})
</code>```

New:

```<code>for (let key in results) {
    results[key] = {
        x: {
            ...results[key].x,
            ...newObj[key].x
        },
        y: {
            ...results[key].y,
            ...newObj[key].y
        },
        z: {
          ...results[key].z,
          ...newObj[key].z
        }
    }
}
</code>```

Title: Merge two objects(optimizing)

Body:
I have n objects(with some nested structure). In the end, I'm expecting to get one merged object with all fields.

const result = {
  firstParam: {
    x: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    y: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    z: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    }
  },
  secondParam: {
    x: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    y: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    z: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    }
  },
  thirdParam: {
    x: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    y: {
      uuid1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    z: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    }
  }
}

const newObj1 = {
  firstParam: {
    x: {
      id2: ["somedata1", "somedata2"]
    },
    y: {
      id2: ["somedata1", "somedata2"]
    },
    z: {
      id2: ["somedata1", "somedata2"]
    }
  },
  secondParam: {
    x: {
      id2: ["somedata1", "somedata2"]
    },
    y: {
      id2: ["somedata1", "somedata2"]
    },
    z: {
      id2: ["somedata1", "somedata2"]
    }
  },
  thirdParam: {
    x: {
      id2: ["somedata1", "somedata2"]
    },
    y: {
      id2: ["somedata1", "somedata2"]
    },
    z: {
      id2: ["somedata1", "somedata2"]
    }
  }
}

const merge = (result, newObj) => {
  console.time("test merge")
  Object.keys(result).forEach(key => {
    result[key] = {
      x: {
        ...result[key].x,
        ...newObj[key].x
      },
      y: {
        ...result[key].y,
        ...newObj[key].y
      },
      z: {
        ...result[key].z,
        ...newObj[key].z
      }
    }
  })
  console.timeEnd("test merge")

  return result;
}

merge(result, newObj1);

This solution gives me an expected result(I'm getting an obj2, obj3 ... objn and every iteration I'm merging it to result), but when I'm getting more than 500 or 1000 newObj it works pretty slow. Is there any way to optimize it?

Body:
I afford make it run in the half time by replacing object keys iteration with for in:

Old:

results[key] = {
    x: {
        ...results[key].x,
        ...newObject[key].x
    },
    y: {
        ...results[key].y,
        ...newObj1[key].y
        },
    z: {
           ...results[key].z,
           ...newObj1[key].z
        }
    }
})

New:

for (let key in results) {
    results[key] = {
        x: {
            ...results[key].x,
            ...newObj[key].x
        },
        y: {
            ...results[key].y,
            ...newObj[key].y
        },
        z: {
          ...results[key].z,
          ...newObj[key].z
        }
    }
}


问:
Using Akka Persistence, How can I persist data into a Oracle Table
Using Akka Persistence, How can I persist data into a Oracle Table.

Akka normally persist data into DB in its standard format. JournalTable in JournalRow format.

But Suppose I want to create an Employee Table with composite primary say combination of emp id, firstname and lastname and other columns like address, city, pincode, etc.

In Spring Hibernate, we create entity which is similar to db table and we persist data by calling save on entity object.

How can we do same in Akka Persistence in Java.

This implementation is not clear to me. Also not the way I want.
A simple example will help.

https://doc.akka.io/docs/akka-persistence-jdbc/3.5.2/index.html#custom-dao-implementation

Reply much appreciated.

Thanks a lot.

答:
Akka Persistence is not a general purpose database abstraction like Hibernate but a library for doing EventSourcing (see for example https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing).

If you want to do general database operations/CRUD you will have to use some other library for that.


问:
Laravel pivot table with multiple columns that needs to insert later
I am having two tables routes and stations and one pivot table route_station. See table details

routes table

```<code>id, number, code
</code>```

stations table

```<code>id, name, code
</code>```

route_station table (pivot)

```<code>id, route_id, station_id, next_station_id, interchange_station_id, sation_order, distance, duration
</code>```

station_id, next_station_id, interchange_station_id all are the satations table id

Schema

Station

```<code>Schema::create(
    'stations',
    function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name')->index();
        $table->string('code')->index();
        $table->text('info');
        $table->string('photo')->nullable();
        $table->timestamps();
    }
);
</code>```

Route

```<code>Schema::create(
    'routes',
    function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->smallInteger('number')->unsigned()->unique();
        $table->string('code')->unique();
        $table->timestamps();

        $table->unique(['number', 'code'], 'routes_unique_columns');
    }
);
</code>```

Route_Station - Pivot

```<code>Schema::create(
    'route_station',
    function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('route_id')->unsigned();
        $table->bigInteger('station_id')->unsigned();
        $table->bigInteger('next_station_id')->unsigned()->nullable();
        $table->bigInteger('interchange_id')->unsigned()->nullable();
        $table->integer('station_order');
        $table->float('distance');
        $table->integer('duration');
        $table->timestamps();

        $table->foreign('route_id')
              ->references('id')
              ->on('routes')
              ->onDelete('restrict');

        $table->foreign('station_id')
              ->references('id')
              ->on('stations')
              ->onDelete('restrict');

        $table->foreign('next_station_id')
              ->references('id')
              ->on('stations')
              ->onDelete('restrict');

        $table->foreign('interchange_id')
              ->references('id')
              ->on('routes')
              ->onDelete('restrict');
    }
);
</code>```

In the admin area, there will be a total of three sections to manage stations and routes.

Stations Page

Routes Page

A Page where I can add stations to route

That means I am not going to insert a record into pivot while creating a station or route but at any time later from the 3rd-page mention above.

I have two models now Station and Route and set the relationship as below.

Station Model

```<code>class Station extends Model
{
    public function routes()
    {
        return $this->belongsToMany('App\Route');
    }

    public function route()
    {
        return $this->belongsTo('App\Route');
    }
}
</code>```

Route Model

```<code>class Route extends Model
{
    public function stations()
    {
        return $this->belongsToMany('App\Station');
    }

    public function station()
    {
        return $this->belongsTo('App\Station');
    }
}
</code>```

So now the problem is that I don't know how to insert a record into the pivot table to fill out all the columns into the role_station table while station and route record already exists.

I have tried to use attach() but it is giving below error

Illuminate/Database/QueryException with message 'SQLSTATE[HY000]:
  General error: 1364 Field 'station_order' doesn't have a default value
  (SQL: insert into route_station (route_id, station_id) values
  (2, 4))'

So I need help with this

Question:

I understood the error that is asking me to set the station_order column value but I don't >know how can I pass values for next_station_id, interchange_station_id, station_order, distance, duration

答:
By default, only the model keys will be present on the pivot object. If your pivot table contains extra attributes, you must specify them when defining the relationship:

```<code>return $this->belongsToMany('App\Route')->withPivot('next_station_id', 'interchange_station_id', 'station_order', 'distance', 'duration');
</code>```

Body:
I am having two tables routes and stations and one pivot table route_station. See table details

routes table

id, number, code

stations table

id, name, code

route_station table (pivot)

id, route_id, station_id, next_station_id, interchange_station_id, sation_order, distance, duration

station_id, next_station_id, interchange_station_id all are the satations table id

Schema

Station

Schema::create(
    'stations',
    function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name')->index();
        $table->string('code')->index();
        $table->text('info');
        $table->string('photo')->nullable();
        $table->timestamps();
    }
);

Route

Schema::create(
    'routes',
    function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->smallInteger('number')->unsigned()->unique();
        $table->string('code')->unique();
        $table->timestamps();

        $table->unique(['number', 'code'], 'routes_unique_columns');
    }
);

Route_Station - Pivot

Schema::create(
    'route_station',
    function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('route_id')->unsigned();
        $table->bigInteger('station_id')->unsigned();
        $table->bigInteger('next_station_id')->unsigned()->nullable();
        $table->bigInteger('interchange_id')->unsigned()->nullable();
        $table->integer('station_order');
        $table->float('distance');
        $table->integer('duration');
        $table->timestamps();

        $table->foreign('route_id')
              ->references('id')
              ->on('routes')
              ->onDelete('restrict');

        $table->foreign('station_id')
              ->references('id')
              ->on('stations')
              ->onDelete('restrict');

        $table->foreign('next_station_id')
              ->references('id')
              ->on('stations')
              ->onDelete('restrict');

        $table->foreign('interchange_id')
              ->references('id')
              ->on('routes')
              ->onDelete('restrict');
    }
);

In the admin area, there will be a total of three sections to manage stations and routes.

Stations Page

Routes Page

A Page where I can add stations to route

That means I am not going to insert a record into pivot while creating a station or route but at any time later from the 3rd-page mention above.

I have two models now Station and Route and set the relationship as below.

Station Model

class Station extends Model
{
    public function routes()
    {
        return $this->belongsToMany('App\Route');
    }

    public function route()
    {
        return $this->belongsTo('App\Route');
    }
}

Route Model

class Route extends Model
{
    public function stations()
    {
        return $this->belongsToMany('App\Station');
    }

    public function station()
    {
        return $this->belongsTo('App\Station');
    }
}

So now the problem is that I don't know how to insert a record into the pivot table to fill out all the columns into the role_station table while station and route record already exists.

I have tried to use attach() but it is giving below error

Illuminate/Database/QueryException with message 'SQLSTATE[HY000]:
  General error: 1364 Field 'station_order' doesn't have a default value
  (SQL: insert into route_station (route_id, station_id) values
  (2, 4))'

So I need help with this

Question:

I understood the error that is asking me to set the station_order column value but I don't >know how can I pass values for next_station_id, interchange_station_id, station_order, distance, duration

Body:
By default, only the model keys will be present on the pivot object. If your pivot table contains extra attributes, you must specify them when defining the relationship:

return $this->belongsToMany('App\Route')->withPivot('next_station_id', 'interchange_station_id', 'station_order', 'distance', 'duration');


问:
Subroutes in Next Js
I´m new to next js, I have created a file called orders.js under pages directory, and I can access it correctly from localhost:3000/orders.

However, I want now to have a subroute, to access the order with id 1 (for example). So I have created a directory 'orders' inside the directory pages, and renamed order.js to index.js, after that, I have created another file inside the orders directory called id.js.

So my current structure is:

```<code>pages/
      orders/
             index.js
             id.js
</code>```

However I cannot access to localhost:3000/orders/1.

Using Nuxt js, this was trivial, how can I achieve the same with next.js ?

Thanks

答:
use

pages/
         orders/
                [dynamic_subroute].js

now catch it with

const router = useRoute();
  const { dynamic_subroute } = router.query;

Now, you can catch the value (any) dynamically from the url which is used instead of dynamic_subroute

like- if the url is pages/orders/1
then value of dynamic_subroute will be 1 in your page

Title: Subroutes in Next Js

Body:
I´m new to next js, I have created a file called orders.js under pages directory, and I can access it correctly from localhost:3000/orders.

However, I want now to have a subroute, to access the order with id 1 (for example). So I have created a directory 'orders' inside the directory pages, and renamed order.js to index.js, after that, I have created another file inside the orders directory called id.js.

So my current structure is:

pages/
      orders/
             index.js
             id.js

However I cannot access to localhost:3000/orders/1.

Using Nuxt js, this was trivial, how can I achieve the same with next.js ?

Thanks


问:
Mongoose Schema with nested optional object with required fields
I'd like to create a Mongoose Schema that validates the object below with the following restrictions:

field2 is optional (0-1 relationship),

field2.type is required if field2 exists (notice that the name of the field is "type" as mongoose reserved word for type definitions),

field2 and the the base object must be in the same document.

Code example

```<code>{
  field1: "data",
  field2: {
    type: "data",
    data: "data"
  }
}
</code>```

Thanks in advance.

答:
@Mina Michael answer didn't worked for me but, when i tweaked a little it worked for me. I tried it like this:</p>

```<code>{
  field1: String,
  field2:{
    type: new Schema({
      nestedField1: {type:Boolean,required:true},
      nestedField2: String,
    }),
    required: false
  }
}
</code>```

Body:
I'd like to create a Mongoose Schema that validates the object below with the following restrictions:

field2 is optional (0-1 relationship),

field2.type is required if field2 exists (notice that the name of the field is "type" as mongoose reserved word for type definitions),

field2 and the the base object must be in the same document.

Code example

{
  field1: "data",
  field2: {
    type: "data",
    data: "data"
  }
}

Thanks in advance.

Body:
@Mina Michael answer didn't worked for me but, when i tweaked a little it worked for me. I tried it like this:

{
  field1: String,
  field2:{
    type: new Schema({
      nestedField1: {type:Boolean,required:true},
      nestedField2: String,
    }),
    required: false
  }
}


问:
How can I change date format for formGroups input element with Angular 7?
When input is of type 'Date', date format is dd/MM/yyyy.
I want to change date format from MM/dd/yyyy to dd/MM/yyyy (Turkish Format and Turkish Calender).

Here is the code.

```<code><form [formGroup]="opportunityForm" (ngSubmit)="updateData(opportunityForm.value)">
 <div class="form-group">
          <label>Oluşturulma Tarihi</label>
          <input  type="date"  class="form-control"  formControlName="createDate" required>
          <div class="alert-danger" *ngIf="!opportunityForm.controls['createDate'].valid && (opportunityForm.controls['createDate'].touched)">
            <div [hidden]="!opportunityForm.controls['createDate'].errors.required">
              Tarih alanı gerekli
            </div>
          </div>
        </div>
 <button type="submit" class="btn btn-primary" [disabled]="!opportunityForm.valid">Güncelle</button>
</form>

constructor(private http: HttpClient,private fb: FormBuilder,private router: Router,private actRoute: ActivatedRoute, private service:OpportunityService) {
    this.opportunityForm=this.fb.group({
      title:['',Validators.required],
      description:['',Validators.required],
      createDate:['',Validators.required],
      expirationDate:['',Validators.required],
      file: new FormControl(null)
    });
</code>```

Suggestions and solutions will be appreciated.

答:
You can manipulate your formControl field 'createDate'.

Use DatePipe provided by angular to change date in any desired format.

Firstly,import DatePipe in your component's ts:

```<code>import { DatePipe } from '@angular/common';
</code>```

Inject date pipe in providers array:

```<code>styleUrls: ['component.css'];
providers: [DatePipe] // like this you inject pipe,services
</code>```

Declare in constructor :

```<code> constructor(
    private datePipe: DatePipe
  ) { }
</code>```

You can either make a function which manipulate date; simply call in updateData(formValue) or directly manipulate date in updateData(formValue) method

// date manipulation using DatePipe

```<code>const datePipe = this.datePipe.transform(this.opportunityForm.get('createDate').value, 'dd-MM-yyyy')
</code>```

Body:
When input is of type 'Date', date format is dd/MM/yyyy.
I want to change date format from MM/dd/yyyy to dd/MM/yyyy (Turkish Format and Turkish Calender).

Here is the code.

<form [formGroup]="opportunityForm" (ngSubmit)="updateData(opportunityForm.value)">

          Oluşturulma Tarihi
          <input  type="date"  class="form-control"  formControlName="createDate" required>

              Tarih alanı gerekli

 <button type="submit" class="btn btn-primary" [disabled]="!opportunityForm.valid">Güncelle</button>
</form>

constructor(private http: HttpClient,private fb: FormBuilder,private router: Router,private actRoute: ActivatedRoute, private service:OpportunityService) {
    this.opportunityForm=this.fb.group({
      title:['',Validators.required],
      description:['',Validators.required],
      createDate:['',Validators.required],
      expirationDate:['',Validators.required],
      file: new FormControl(null)
    });

Suggestions and solutions will be appreciated.

Body:
You can manipulate your formControl field 'createDate'.

Use DatePipe provided by angular to change date in any desired format.

Firstly,import DatePipe in your component's ts:

import { DatePipe } from '@angular/common';

Inject date pipe in providers array:

styleUrls: ['component.css'];
providers: [DatePipe] // like this you inject pipe,services

Declare in constructor :

 constructor(
    private datePipe: DatePipe
  ) { }

You can either make a function which manipulate date; simply call in updateData(formValue) or directly manipulate date in updateData(formValue) method

// date manipulation using DatePipe

const datePipe = this.datePipe.transform(this.opportunityForm.get('createDate').value, 'dd-MM-yyyy')


问:
WPF V4 - MVVM Light V4 (BL16 - Mix11) - RelayCommand - CanExecute doesn't fire
I am trying to use the latest Preview version of MVVM-Light (V4 - BL16 - Mix11) in my WPF v4 app that was using MVVM-light V3 Sp1.

In my ViewModel, I have the following property defined

```<code>    private WifiNetwork _selectedNetwork;
    public WifiNetwork SelectedNetwork
    {
        get
        {
            return _selectedNetwork;
        }
        set
        {
            if (_selectedNetwork == value)
                return;

            _selectedNetwork = value;
            RaisePropertyChanged("SelectedNetwork");
        }
    }
</code>```

This property is binded to ListBox's SelectedItem in the View XAML.

I have the following RelayCommand defined in my viewModel

```<code>    private RelayCommand _connectCommand;
    public RelayCommand ConnectCommand
    {
        get
        {
            if (_connectCommand == null)
            {
                _connectCommand = new RelayCommand(
                    () => ConnectToSpecifiedNetwork(SelectedNetwork),
                    () => SelectedNetwork != null && ! SelectedNetwork.IsConnected);
            }

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

This RelayCommand is binded to my "Connect" button.

When the selected item is not already connected (IsConnected is false), then the connect button should enable.

This worked perfect in MVVM-Light V3 Sp1. But when I use the MIX 11 preview version of MVVM-Light, this doesn't seem to work anymore.

Any suggestions?

I can upload my entire project somewhere if needed..

答:
In order to fix this issue, I had to call "RaiseCanExecuteChanged()" method on my INPC property as shown below

```<code>    private WifiNetwork _selectedNetwork;
    public WifiNetwork SelectedNetwork
    {
        get
        {
            return _selectedNetwork;
        }
        set
        {
            if (_selectedNetwork == value)
                return;

            _selectedNetwork = value;

            RaisePropertyChanged("SelectedNetwork");
            // FIX - raise the CanExecuteChanged on the command.
           _connectCommand.RaiseCanExecuteChanged();
        }
    }
</code>```

I didn't have to do this (manually raise the RaiseCanExecuteChanged on a command) in MVVM-Light V3 Sp1.

Body:
I am trying to use the latest Preview version of MVVM-Light (V4 - BL16 - Mix11) in my WPF v4 app that was using MVVM-light V3 Sp1.

In my ViewModel, I have the following property defined

    private WifiNetwork _selectedNetwork;
    public WifiNetwork SelectedNetwork
    {
        get
        {
            return _selectedNetwork;
        }
        set
        {
            if (_selectedNetwork == value)
                return;

            _selectedNetwork = value;
            RaisePropertyChanged("SelectedNetwork");
        }
    }

This property is binded to ListBox's SelectedItem in the View XAML.

I have the following RelayCommand defined in my viewModel

    private RelayCommand _connectCommand;
    public RelayCommand ConnectCommand
    {
        get
        {
            if (_connectCommand == null)
            {
                _connectCommand = new RelayCommand(
                    () => ConnectToSpecifiedNetwork(SelectedNetwork),
                    () => SelectedNetwork != null && ! SelectedNetwork.IsConnected);
            }

            return _connectCommand;
        }
    }

This RelayCommand is binded to my "Connect" button.

When the selected item is not already connected (IsConnected is false), then the connect button should enable.

This worked perfect in MVVM-Light V3 Sp1. But when I use the MIX 11 preview version of MVVM-Light, this doesn't seem to work anymore.

Any suggestions?

I can upload my entire project somewhere if needed..

Body:
In order to fix this issue, I had to call "RaiseCanExecuteChanged()" method on my INPC property as shown below

    private WifiNetwork _selectedNetwork;
    public WifiNetwork SelectedNetwork
    {
        get
        {
            return _selectedNetwork;
        }
        set
        {
            if (_selectedNetwork == value)
                return;

            _selectedNetwork = value;

            RaisePropertyChanged("SelectedNetwork");
            // FIX - raise the CanExecuteChanged on the command.
           _connectCommand.RaiseCanExecuteChanged();
        }
    }

I didn't have to do this (manually raise the RaiseCanExecuteChanged on a command) in MVVM-Light V3 Sp1.


问:
How to show a link if user_id =1 in HTML with PHP
I am new and learning PHP and HTML. I have one user table where I am displaying data. I want to show Delete button if user_id = 1. else I want to hide it. My current link code is like below

```<code><a href="<?php echo site_url('members/delete/'.$row['user_id']); ?>" class="btn btn-danger" onclick="return confirm('Are you sure to delete?')">delete</a>
</code>```

I have done PHP code for doing achieve my above description

```<code><?php
if ($row['user_id']==1){
echo //// I want a link here
}
?>
</code>```

But since my link have also used some PHP codes, I am confused and not able to properly echo button. I am trying from an hour and not able to fix it. Let me know if someone can help me for do it.

Thanks!

答:
Read about string concatenation in PHP.

Here is a possible solution for your problem:

<?php
if ($row['user_id'] === 1) {
  echo ''.$row['username'].'';
}
```

Body:
I am new and learning PHP and HTML. I have one user table where I am displaying data. I want to show Delete button if user_id = 1. else I want to hide it. My current link code is like below

<a href="<?php echo site_url('members/delete/'.$row['user_id']); ?>" class="btn btn-danger" onclick="return confirm('Are you sure to delete?')">delete

I have done PHP code for doing achieve my above description

<?php
if ($row['user_id']==1){
echo //// I want a link here
}
?>

But since my link have also used some PHP codes, I am confused and not able to properly echo button. I am trying from an hour and not able to fix it. Let me know if someone can help me for do it.

Thanks!

Body:
Read about string concatenation in PHP.

Here is a possible solution for your problem:

<?php
if ($row['user_id'] === 1) {
  echo '<a href="/members/delete/'.$row['user_id'].'">'.$row['username'].'</a>';
}


问:
How to restrict a logon to a specified Ip Address Range using B2C Custom Policy
I use a B2C Custom policy to sign in users. Is it possible to restrict the users so they can only signin from a specified Ip Address (or range)?</p>

答:
Currently there is no such feature in Azure AD B2C. You can submit a feedback on Microsoft Azure Forum.

You can try to implement this by yourself, kindly refer to the idea below.

You can call a REST API and pass it the IP address. The IP address can be resolved using a Claims Resolver. If it’s one IP address then you can do a claim transform in the policy to check if the user ip matches. Otherwise if it needs to check the user ip in an ip range, then you need to do that logic in a REST API.

Similar approach to this:

https://github.com/azure-ad-b2c/samples/tree/master/policies/relying-party-rbac
https://learn.microsoft.com/en-us/azure/active-directory-b2c/claim-resolver-overview


问:
Test the connection to a network drive
I'm making an interface to connect network drives with python (and netuse). A tkinter button runs the connection command, and a textbox shows the connection state.
However, this textbox shows "connected" once the drive is visible in windows explorer, even if we cannot open it (due to a missing network). I have to click "disconnect" manually to make it appear as "disconnected" in my python program. (indeed, this disk isn't in the  win32net.NetUseEnum request anymore)

How can I do to test the disk connection before showing its status ?

Raphael

```<code>import os
import win32net
(_drives, total, resume) = win32net.NetUseEnum (None, 0, 0)
disques = []
for drive in _drives:
    if drive['local']== "V:":
        disques.append("v")
    if drive['local']=="U:":
        disques.append("u")

def monterU():
    if os.system(r"net use u: \\srsedc03\users") == 0:
        os.system(r"net use u: \\srsedc03\users")
        etatU.set("connecté")
</code>```

答:
I found the answer somewhere else:
we can use the following code to check if every disk is reachable.</p>

```<code>import os

for drive in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
    drive += ':'

try:
    os.scandir(drive)
    ok = "accessible"
except Exception:
    ok = "non accessible"

print(drive, os.access(drive, os.R_OK), ok)
</code>```

Title: Test the connection to a network drive

Body:
I'm making an interface to connect network drives with python (and netuse). A tkinter button runs the connection command, and a textbox shows the connection state.
However, this textbox shows "connected" once the drive is visible in windows explorer, even if we cannot open it (due to a missing network). I have to click "disconnect" manually to make it appear as "disconnected" in my python program. (indeed, this disk isn't in the  win32net.NetUseEnum request anymore)

How can I do to test the disk connection before showing its status ?

Raphael

import os
import win32net
(_drives, total, resume) = win32net.NetUseEnum (None, 0, 0)
disques = []
for drive in _drives:
    if drive['local']== "V:":
        disques.append("v")
    if drive['local']=="U:":
        disques.append("u")

def monterU():
    if os.system(r"net use u: \\srsedc03\users") == 0:
        os.system(r"net use u: \\srsedc03\users")
        etatU.set("connecté")

Body:
I found the answer somewhere else:
we can use the following code to check if every disk is reachable.

import os

for drive in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
    drive += ':'

try:
    os.scandir(drive)
    ok = "accessible"
except Exception:
    ok = "non accessible"

print(drive, os.access(drive, os.R_OK), ok)


问:
Retain all columns in original data table when applying a function that returns a data table with multiple columns
Say I have a data table.

# Load package
library(data.table)

# Dummy data table
dt <- data.table(foo = letters[1:10],
                 bar = LETTERS[11:20],
                 val = 100:109)
```

<p>I'd like to run a function on a column of this data table that returns a data table with multiple columns. Let's say it looks like this:</p>

<pre class="lang-r prettyprint-override"><code># Function that returns data table
f <- function(x){
  data.table(stuff = paste0(x, "_stuff"),
             things = paste0("things_", x))
}
</code>```

If I run it on foo from the data table, it returns this:

# Returns only columns from function
dt[, f(foo)]
#>       stuff   things
#>  1: a_stuff things_a
#>  2: b_stuff things_b
#>  3: c_stuff things_c
#>  4: d_stuff things_d
#>  5: e_stuff things_e
#>  6: f_stuff things_f
#>  7: g_stuff things_g
#>  8: h_stuff things_h
#>  9: i_stuff things_i
#> 10: j_stuff things_j
```

<p>Great! Now, I'd like the returned data table to be appended to my original data table. If I wanted to append it to just a few columns from the original data table, I could just name the columns I want to retain like so:  </p>

<pre class="lang-r prettyprint-override"><code># Returns named column and columns from function
dt[, .(foo, f(foo))]
#>     foo   stuff   things
#>  1:   a a_stuff things_a
#>  2:   b b_stuff things_b
#>  3:   c c_stuff things_c
#>  4:   d d_stuff things_d
#>  5:   e e_stuff things_e
#>  6:   f f_stuff things_f
#>  7:   g g_stuff things_g
#>  8:   h h_stuff things_h
#>  9:   i i_stuff things_i
#> 10:   j j_stuff things_j
</code>```

But, I want to keep all columns without having to name them individually. One way would be to use by:

# Retains all columns
dt[, f(foo), by = names(dt)]
#>     foo bar val   stuff   things
#>  1:   a   K 100 a_stuff things_a
#>  2:   b   L 101 b_stuff things_b
#>  3:   c   M 102 c_stuff things_c
#>  4:   d   N 103 d_stuff things_d
#>  5:   e   O 104 e_stuff things_e
#>  6:   f   P 105 f_stuff things_f
#>  7:   g   Q 106 g_stuff things_g
#>  8:   h   R 107 h_stuff things_h
#>  9:   i   S 108 i_stuff things_i
#> 10:   j   T 109 j_stuff things_j
```

Created on 2020-02-18 by the reprex package (v0.3.0)

This gives me the desired result for this test case, but clearly this only makes sense if rows are unique.

I've tried to use something like dt[, .(names(dt), f(foo))], but this doesn't work as names returns a vector of strings which is then added as a column.

The obvious solution is to use := like so: dt[, c("One", "Two") := f(foo)]. This gives the desired result but I have to name the added columns myself, whereas I'd like to retain the column names returned by the function.

Another solution might be cbind(dt, dt[, foo(f)]), but this seems cludgy.

What is the correct way to achieve this result?

答:
Another option, if you don't need to do anything with i or by= in your processing would be to make dt an argument to your function and then use set() inside your function, as shown below.

```<code>
f <- function(x, dt){
  set(dt, j = "stuff", value = paste0(dt[[x]], "_stuff"))
  set(dt, j = "things", value = paste0("things_", dt[[x]]))
}

f("foo", dt)
</code>```

Output:

```<code>> dt
    foo bar val   stuff   things
 1:   a   K 100 a_stuff things_a
 2:   b   L 101 b_stuff things_b
 3:   c   M 102 c_stuff things_c
 4:   d   N 103 d_stuff things_d
 5:   e   O 104 e_stuff things_e
 6:   f   P 105 f_stuff things_f
 7:   g   Q 106 g_stuff things_g
 8:   h   R 107 h_stuff things_h
 9:   i   S 108 i_stuff things_i
10:   j   T 109 j_stuff things_j
</code>```

Body:
Say I have a data table.

# Load package
library(data.table)

# Dummy data table
dt <- data.table(foo = letters[1:10],
                 bar = LETTERS[11:20],
                 val = 100:109)

I'd like to run a function on a column of this data table that returns a data table with multiple columns. Let's say it looks like this:

# Function that returns data table
f <- function(x){
  data.table(stuff = paste0(x, "_stuff"),
             things = paste0("things_", x))
}

If I run it on foo from the data table, it returns this:

# Returns only columns from function
dt[, f(foo)]
#>       stuff   things
#>  1: a_stuff things_a
#>  2: b_stuff things_b
#>  3: c_stuff things_c
#>  4: d_stuff things_d
#>  5: e_stuff things_e
#>  6: f_stuff things_f
#>  7: g_stuff things_g
#>  8: h_stuff things_h
#>  9: i_stuff things_i
#> 10: j_stuff things_j

Great! Now, I'd like the returned data table to be appended to my original data table. If I wanted to append it to just a few columns from the original data table, I could just name the columns I want to retain like so:

# Returns named column and columns from function
dt[, .(foo, f(foo))]
#>     foo   stuff   things
#>  1:   a a_stuff things_a
#>  2:   b b_stuff things_b
#>  3:   c c_stuff things_c
#>  4:   d d_stuff things_d
#>  5:   e e_stuff things_e
#>  6:   f f_stuff things_f
#>  7:   g g_stuff things_g
#>  8:   h h_stuff things_h
#>  9:   i i_stuff things_i
#> 10:   j j_stuff things_j

But, I want to keep all columns without having to name them individually. One way would be to use by:

# Retains all columns
dt[, f(foo), by = names(dt)]
#>     foo bar val   stuff   things
#>  1:   a   K 100 a_stuff things_a
#>  2:   b   L 101 b_stuff things_b
#>  3:   c   M 102 c_stuff things_c
#>  4:   d   N 103 d_stuff things_d
#>  5:   e   O 104 e_stuff things_e
#>  6:   f   P 105 f_stuff things_f
#>  7:   g   Q 106 g_stuff things_g
#>  8:   h   R 107 h_stuff things_h
#>  9:   i   S 108 i_stuff things_i
#> 10:   j   T 109 j_stuff things_j

Created on 2020-02-18 by the reprex package (v0.3.0)

This gives me the desired result for this test case, but clearly this only makes sense if rows are unique.

I've tried to use something like dt[, .(names(dt), f(foo))], but this doesn't work as names returns a vector of strings which is then added as a column.

The obvious solution is to use := like so: dt[, c("One", "Two") := f(foo)]. This gives the desired result but I have to name the added columns myself, whereas I'd like to retain the column names returned by the function.

Another solution might be cbind(dt, dt[, foo(f)]), but this seems cludgy.

What is the correct way to achieve this result?

Body:
Another option, if you don't need to do anything with i or by= in your processing would be to make dt an argument to your function and then use set() inside your function, as shown below.

f <- function(x, dt){
  set(dt, j = "stuff", value = paste0(dt[[x]], "_stuff"))
  set(dt, j = "things", value = paste0("things_", dt[[x]]))
}

f("foo", dt)

Output:

> dt
    foo bar val   stuff   things
 1:   a   K 100 a_stuff things_a
 2:   b   L 101 b_stuff things_b
 3:   c   M 102 c_stuff things_c
 4:   d   N 103 d_stuff things_d
 5:   e   O 104 e_stuff things_e
 6:   f   P 105 f_stuff things_f
 7:   g   Q 106 g_stuff things_g
 8:   h   R 107 h_stuff things_h
 9:   i   S 108 i_stuff things_i
10:   j   T 109 j_stuff things_j


问:
Display system+client in Eclipse ADT tab description?
We have just switched to Eclipse ADT in our SAP ABAP development environment, and now we are developing in client 100 and test in client 200, so we have opened two tabs with the same source in different SAP clients.

In the project pane we see

The problem is that you cannot see the client in the tab description, currently I only see

[D10] Z_WEB_COMPONENT | COMPONENTCONTROLLER

or something like this

but I would like to see something like

[D10 - 100] Z_WEB_COMPONENT | COMPONENTCONTROLLER

or

[D10 - 200] Z_WEB_COMPONENT | COMPONENTCONTROLLER

This is quite confusing if to work with a several tabs of the same systems without knowing client.

Is this possible? If yes, where is this setting?

答:
Seems to be impossible now by standard ADT tools.

Try this plugin that allows changing coloring in editor.

If to set up different colors for different projects, it should fulfill exactly what you need: one project is E50_100, another is E50_200 and you can differentiate them by color


问:
How to pass variable to later in program / Inputting double to dialog box
I'm trying to create a dialog box at the start of my program that allows the user to input a number that is then used in another function (actually in another C file) much later on in the program.

```<code>void function()
{
double variable;
char buf[256] = "400";
sprintf( buf, "%d", variable);
#ifdef WIN32
edit_dialog(NULL,"Enter variable", "Please enter the variable:", buf,260);
#endif
variable = atof(buf);
}
</code>```

I'd like to pass 'variable' into another function later on in the program. The problem is, I don't need the variable until much later. I don't want to pass it between each and every function until it gets to the right part of the program. How do I do this?

Also when I launch this, I get the dialog box as I'd expect but the number in the box is not 400, as I would expect. Instead it is 2089881670(!) I assume I am handling memory incorrectly but don't understand why.

答:
"I'd like to pass 'variable' into
  another function later on in the
  program. The problem is, I don't need
  the variable until much later. I don't
  want to pass it between each and every
  function until it gets to the right
  part of the program. How do I do this?"

This is a pure program design problem, and has nothing to do with language syntax. If your user input is handled in main(), and then processed by some file that handles data processing, why would you need to "pass it between each and every function"? Pass it to the function that should handle it, end of story. You don't need no global variables.

Body:
I'm trying to create a dialog box at the start of my program that allows the user to input a number that is then used in another function (actually in another C file) much later on in the program.

void function()
{
double variable;
char buf[256] = "400";
sprintf( buf, "%d", variable);
#ifdef WIN32
edit_dialog(NULL,"Enter variable", "Please enter the variable:", buf,260);
#endif
variable = atof(buf);
}

I'd like to pass 'variable' into another function later on in the program. The problem is, I don't need the variable until much later. I don't want to pass it between each and every function until it gets to the right part of the program. How do I do this?

Also when I launch this, I get the dialog box as I'd expect but the number in the box is not 400, as I would expect. Instead it is 2089881670(!) I assume I am handling memory incorrectly but don't understand why.


问:
cluster doesn't have a stable controlPlaneEndpoint address
When I join a new node as a master to my cluster. I get the error. my cluster version is 1.17.0 . The command I exec on the node is:
kubeadm join 192.168.1.120:6443 --token 5hbl78.99jlbgerstlkecss     --discovery-token-ca-cert-hash sha256:0beb43185fa6a346fe57bd97cbb22afb128e6267bb80403ba2e7f388588e3256 --control-plane --certificate-key a056ad6f0ba73e736401027a1f078d7195b1aadaf2ac2eca6d773edc98d01483

I receive the following errors:

```<code>[preflight] Running pre-flight checks
[preflight] Reading configuration from the cluster...
[preflight] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -oyaml'
error execution phase preflight:
One or more conditions for hosting a new control plane instance is not satisfied.

unable to add a new control plane instance a cluster that doesn't have a stable controlPlaneEndpoint address

Please ensure that:
* The cluster has a stable controlPlaneEndpoint address.
* The certificates that must be shared among control plane instances are provided.

To see the stack trace of this error execute with --v=5 or higher
</code>```

The kubeadm config on the master node is:

```<code>root@k8s-master01:kubernetes#kubectl -n kube-system get cm kubeadm-config -oyaml
apiVersion: v1
data:
  ClusterConfiguration: |
    apiServer:
      certSANs:
      - 192.168.1.120
      - 192.168.1.121
      - 192.168.1.122
      extraArgs:
        authorization-mode: Node,RBAC
      timeoutForControlPlane: 4m0s
    apiVersion: kubeadm.k8s.io/v1beta2
    certificatesDir: /etc/kubernetes/pki
    clusterName: kubernetes
    controllerManager: {}
    dns:
      type: CoreDNS
    etcd:
      external:
        caFile: /work/deploy/kubernetes/security/ca.pem
        certFile: /work/deploy/kubernetes/security/etcd.pem
        endpoints:
        - https://192.168.1.120:2379
        - https://192.168.1.121:2379
        - https://192.168.1.122:2379
        keyFile: /work/deploy/kubernetes/security/etcd.key
    imageRepository: registry.aliyuncs.com/google_containers
    kind: ClusterConfiguration
    kubernetesVersion: v1.17.0
    networking:
      dnsDomain: cluster.local
      podSubnet: 192.168.0.0/16
      serviceSubnet: 10.10.0.0/16
    scheduler: {}
  ClusterStatus: |
    apiEndpoints:
      k8s-master01:
        advertiseAddress: 192.168.1.120
        bindPort: 6443
    apiVersion: kubeadm.k8s.io/v1beta2
    kind: ClusterStatus
kind: ConfigMap
metadata:
  creationTimestamp: "2020-02-20T05:27:10Z"
  name: kubeadm-config
  namespace: kube-system
  resourceVersion: "8315"
  selfLink: /api/v1/namespaces/kube-system/configmaps/kubeadm-config
  uid: a32b2f9b-41c3-4822-b8cb-c30c922fbddb
</code>```

This problem has been mentioned in StackOverflow, but has not been solved

I reset my cluster, And clean up the etcd data. Then i configtured a VIP with keepalive, And I configtured the VIP load balancing to two node(which i plan to be as two master node ) by haproxy. After that i configtured the kubeadm-config.yaml.  modify the controlPlaneEndpoint value to be the LB's VIP:PORT. then I exec the "kubeadm init --config kubeadm.conf --upload-certs". I receive the following errors:

```<code>[control-plane] Creating static Pod manifest for "kube-scheduler"
W0221 10:58:26.827277   18370 manifests.go:214] the default kube-apiserver authorization-mode is "Node,RBAC"; using "Node,RBAC"
[wait-control-plane] Waiting for the kubelet to boot up the control plane as static Pods from directory "/etc/kubernetes/manifests". This can take up to 4m0s
[kubelet-check] Initial timeout of 40s passed.

Unfortunately, an error has occurred:
    timed out waiting for the condition

This error is likely caused by:
    - The kubelet is not running
    - The kubelet is unhealthy due to a misconfiguration of the node in some way (required cgroups disabled)

If you are on a systemd-powered system, you can try to troubleshoot the error with the following commands:
    - 'systemctl status kubelet'
    - 'journalctl -xeu kubelet'

Additionally, a control plane component may have crashed or exited when started by the container runtime.
To troubleshoot, list all containers using your preferred container runtimes CLI, e.g. docker.
Here is one example how you may list all Kubernetes containers running in docker:
    - 'docker ps -a | grep kube | grep -v pause'
    Once you have found the failing container, you can inspect its logs with:
    - 'docker logs CONTAINERID'
error execution phase wait-control-plane: couldn't initialize a Kubernetes cluster
To see the stack trace of this error execute with --v=5 or higher
**root@k8s-master01:kubernetes#journalctl -xeu kubelet**
2月 21 11:05:04 k8s-master01 kubelet[22546]: E0221 11:05:04.698260   22546 reflector.go:156] k8s.io/kubernetes/pkg/kubelet/kubelet.go:449: Failed to list *v1.Service: Get https://192.168.1.121:6443/api/v1/services?limit=500&resour
2月 21 11:05:04 k8s-master01 kubelet[22546]: E0221 11:05:04.781676   22546 kubelet.go:2263] node "k8s-master01" not found
2月 21 11:05:04 k8s-master01 kubelet[22546]: E0221 11:05:04.881928   22546 kubelet.go:2263] node "k8s-master01" not found
2月 21 11:05:04 k8s-master01 kubelet[22546]: E0221 11:05:04.895805   22546 reflector.go:156] k8s.io/kubernetes/pkg/kubelet/kubelet.go:458: Failed to list *v1.Node: Get https://192.168.1.121:6443/api/v1/nodes?fieldSelector=metadata
2月 21 11:05:04 k8s-master01 kubelet[22546]: E0221 11:05:04.983615   22546 kubelet.go:2263] node "k8s-master01" not found
2月 21 11:05:05 k8s-master01 kubelet[22546]: E0221 11:05:05.084247   22546 kubelet.go:2263] node "k8s-master01" not found
2月 21 11:05:05 k8s-master01 kubelet[22546]: E0221 11:05:05.106561   22546 reflector.go:156] k8s.io/kubernetes/pkg/kubelet/config/apiserver.go:46: Failed to list *v1.Pod: Get https://192.168.1.121:6443/api/v1/pods?fieldSelector=sp
2月 21 11:05:05 k8s-master01 kubelet[22546]: E0221 11:05:05.184665   22546 kubelet.go:2263] node "k8s-master01" not found
2月 21 11:05:05 k8s-master01 kubelet[22546]: E0221 11:05:05.284792   22546 kubelet.go:2263] node "k8s-master01" not found
</code>```

Other info:
My VIP's endpoint is: 192.168.1.200:6001 . And the haproxy LB the VIP' endpoint to the two master apiserver endpoint(192.168.1.120:6443, 192.168.1.121:6443)

答:
When you setup the first master node using kubeadm you should have run below command :

```<code>sudo kubeadm init --config kubeadm-config.yaml --upload-certs
</code>```

Check the content of kubeadm-config.yaml file. It should have controlPlaneEndpoint. The value should be LOAD_BALANCER_DNS:LOAD_BALANCER_PORT.

Now if you don't have a Loadabalancer in front of your Kubernetes API Server which is recommended you can set this to public IP of the master node.

The --upload-certs flag should take care of the error related to certificate.

Also you can edit the ConfigMap and add controlPlaneEndpoint.

The content of kubeadm-config.yaml should look like

```<code>    apiVersion: kubeadm.k8s.io/v1beta2
    kind: ClusterConfiguration
    kubernetesVersion: stable
    controlPlaneEndpoint: "192.168.1.200:6001"
    apiServer:
      certSANs:
      - 192.168.1.120
      - 192.168.1.121
      - 192.168.1.122
      - 192.168.1.200
      extraArgs:
        authorization-mode: Node,RBAC
    etcd:
      external:
        endpoints:
        - https://192.168.1.120:2379
        - https://192.168.1.121:2379
        - https://192.168.1.122:2379
        caFile: /work/deploy/kubernetes/security/ca.pem
        certFile: /work/deploy/kubernetes/security/etcd.pem
        keyFile: /work/deploy/kubernetes/security/etcd.key
    networking:
      dnsDomain: cluster.local
      podSubnet: 192.168.0.0/16
      serviceSubnet: 10.10.0.0/16
</code>```

Body:
When I join a new node as a master to my cluster. I get the error. my cluster version is 1.17.0 . The command I exec on the node is:
kubeadm join 192.168.1.120:6443 --token 5hbl78.99jlbgerstlkecss     --discovery-token-ca-cert-hash sha256:0beb43185fa6a346fe57bd97cbb22afb128e6267bb80403ba2e7f388588e3256 --control-plane --certificate-key a056ad6f0ba73e736401027a1f078d7195b1aadaf2ac2eca6d773edc98d01483

I receive the following errors:

[preflight] Running pre-flight checks
[preflight] Reading configuration from the cluster...
[preflight] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -oyaml'
error execution phase preflight:
One or more conditions for hosting a new control plane instance is not satisfied.

unable to add a new control plane instance a cluster that doesn't have a stable controlPlaneEndpoint address

Please ensure that:
* The cluster has a stable controlPlaneEndpoint address.
* The certificates that must be shared among control plane instances are provided.

To see the stack trace of this error execute with --v=5 or higher

The kubeadm config on the master node is:

root@k8s-master01:kubernetes#kubectl -n kube-system get cm kubeadm-config -oyaml
apiVersion: v1
data:
  ClusterConfiguration: |
    apiServer:
      certSANs:
      - 192.168.1.120
      - 192.168.1.121
      - 192.168.1.122
      extraArgs:
        authorization-mode: Node,RBAC
      timeoutForControlPlane: 4m0s
    apiVersion: kubeadm.k8s.io/v1beta2
    certificatesDir: /etc/kubernetes/pki
    clusterName: kubernetes
    controllerManager: {}
    dns:
      type: CoreDNS
    etcd:
      external:
        caFile: /work/deploy/kubernetes/security/ca.pem
        certFile: /work/deploy/kubernetes/security/etcd.pem
        endpoints:
        - https://192.168.1.120:2379
        - https://192.168.1.121:2379
        - https://192.168.1.122:2379
        keyFile: /work/deploy/kubernetes/security/etcd.key
    imageRepository: registry.aliyuncs.com/google_containers
    kind: ClusterConfiguration
    kubernetesVersion: v1.17.0
    networking:
      dnsDomain: cluster.local
      podSubnet: 192.168.0.0/16
      serviceSubnet: 10.10.0.0/16
    scheduler: {}
  ClusterStatus: |
    apiEndpoints:
      k8s-master01:
        advertiseAddress: 192.168.1.120
        bindPort: 6443
    apiVersion: kubeadm.k8s.io/v1beta2
    kind: ClusterStatus
kind: ConfigMap
metadata:
  creationTimestamp: "2020-02-20T05:27:10Z"
  name: kubeadm-config
  namespace: kube-system
  resourceVersion: "8315"
  selfLink: /api/v1/namespaces/kube-system/configmaps/kubeadm-config
  uid: a32b2f9b-41c3-4822-b8cb-c30c922fbddb

This problem has been mentioned in StackOverflow, but has not been solved

I reset my cluster, And clean up the etcd data. Then i configtured a VIP with keepalive, And I configtured the VIP load balancing to two node(which i plan to be as two master node ) by haproxy. After that i configtured the kubeadm-config.yaml.  modify the controlPlaneEndpoint value to be the LB's VIP:PORT. then I exec the "kubeadm init --config kubeadm.conf --upload-certs". I receive the following errors:

[control-plane] Creating static Pod manifest for "kube-scheduler"
W0221 10:58:26.827277   18370 manifests.go:214] the default kube-apiserver authorization-mode is "Node,RBAC"; using "Node,RBAC"
[wait-control-plane] Waiting for the kubelet to boot up the control plane as static Pods from directory "/etc/kubernetes/manifests". This can take up to 4m0s
[kubelet-check] Initial timeout of 40s passed.

Unfortunately, an error has occurred:
    timed out waiting for the condition

This error is likely caused by:
    - The kubelet is not running
    - The kubelet is unhealthy due to a misconfiguration of the node in some way (required cgroups disabled)

If you are on a systemd-powered system, you can try to troubleshoot the error with the following commands:
    - 'systemctl status kubelet'
    - 'journalctl -xeu kubelet'

Additionally, a control plane component may have crashed or exited when started by the container runtime.
To troubleshoot, list all containers using your preferred container runtimes CLI, e.g. docker.
Here is one example how you may list all Kubernetes containers running in docker:
    - 'docker ps -a | grep kube | grep -v pause'
    Once you have found the failing container, you can inspect its logs with:
    - 'docker logs CONTAINERID'
error execution phase wait-control-plane: couldn't initialize a Kubernetes cluster
To see the stack trace of this error execute with --v=5 or higher
**root@k8s-master01:kubernetes#journalctl -xeu kubelet**
2月 21 11:05:04 k8s-master01 kubelet[22546]: E0221 11:05:04.698260   22546 reflector.go:156] k8s.io/kubernetes/pkg/kubelet/kubelet.go:449: Failed to list *v1.Service: Get https://192.168.1.121:6443/api/v1/services?limit=500&resour
2月 21 11:05:04 k8s-master01 kubelet[22546]: E0221 11:05:04.781676   22546 kubelet.go:2263] node "k8s-master01" not found
2月 21 11:05:04 k8s-master01 kubelet[22546]: E0221 11:05:04.881928   22546 kubelet.go:2263] node "k8s-master01" not found
2月 21 11:05:04 k8s-master01 kubelet[22546]: E0221 11:05:04.895805   22546 reflector.go:156] k8s.io/kubernetes/pkg/kubelet/kubelet.go:458: Failed to list *v1.Node: Get https://192.168.1.121:6443/api/v1/nodes?fieldSelector=metadata
2月 21 11:05:04 k8s-master01 kubelet[22546]: E0221 11:05:04.983615   22546 kubelet.go:2263] node "k8s-master01" not found
2月 21 11:05:05 k8s-master01 kubelet[22546]: E0221 11:05:05.084247   22546 kubelet.go:2263] node "k8s-master01" not found
2月 21 11:05:05 k8s-master01 kubelet[22546]: E0221 11:05:05.106561   22546 reflector.go:156] k8s.io/kubernetes/pkg/kubelet/config/apiserver.go:46: Failed to list *v1.Pod: Get https://192.168.1.121:6443/api/v1/pods?fieldSelector=sp
2月 21 11:05:05 k8s-master01 kubelet[22546]: E0221 11:05:05.184665   22546 kubelet.go:2263] node "k8s-master01" not found
2月 21 11:05:05 k8s-master01 kubelet[22546]: E0221 11:05:05.284792   22546 kubelet.go:2263] node "k8s-master01" not found

Other info:
My VIP's endpoint is: 192.168.1.200:6001 . And the haproxy LB the VIP' endpoint to the two master apiserver endpoint(192.168.1.120:6443, 192.168.1.121:6443)

Body:
When you setup the first master node using kubeadm you should have run below command :

sudo kubeadm init --config kubeadm-config.yaml --upload-certs

Check the content of kubeadm-config.yaml file. It should have controlPlaneEndpoint. The value should be LOAD_BALANCER_DNS:LOAD_BALANCER_PORT.

Now if you don't have a Loadabalancer in front of your Kubernetes API Server which is recommended you can set this to public IP of the master node.

The --upload-certs flag should take care of the error related to certificate.

Also you can edit the ConfigMap and add controlPlaneEndpoint.

The content of kubeadm-config.yaml should look like

    apiVersion: kubeadm.k8s.io/v1beta2
    kind: ClusterConfiguration
    kubernetesVersion: stable
    controlPlaneEndpoint: "192.168.1.200:6001"
    apiServer:
      certSANs:
      - 192.168.1.120
      - 192.168.1.121
      - 192.168.1.122
      - 192.168.1.200
      extraArgs:
        authorization-mode: Node,RBAC
    etcd:
      external:
        endpoints:
        - https://192.168.1.120:2379
        - https://192.168.1.121:2379
        - https://192.168.1.122:2379
        caFile: /work/deploy/kubernetes/security/ca.pem
        certFile: /work/deploy/kubernetes/security/etcd.pem
        keyFile: /work/deploy/kubernetes/security/etcd.key
    networking:
      dnsDomain: cluster.local
      podSubnet: 192.168.0.0/16
      serviceSubnet: 10.10.0.0/16


答:
I think you want to add variables in string:

```<code><?php
if ($row['user_id']==1){
echo '<a href="'.site_url('members/delete/'.$row['user_id']).'" class="btn btn-danger" onclick="return confirm(\'Are you sure to delete?\')">delete</a>';
}
?>
</code>```

Use . to combine strings & variables:

```<code> 'string'.$var
</code>```

Title: How to show a link if user_id =1 in HTML with PHP

Body:
I think you want to add variables in string:

<?php
if ($row['user_id']==1){
echo '<a href="'.site_url('members/delete/'.$row['user_id']).'" class="btn btn-danger" onclick="return confirm(\'Are you sure to delete?\')">delete</a>';
}
?>

Use . to combine strings & variables:

 'string'.$var


答:
here an an example...</p>

```<code><?php if ($row['user_id']==1){ ?>
<a href="<?php echo site_url('members/delete/'.$row['user_id']); ?>" class="btn btn-danger" onclick="return confirm('Are you sure to delete?')">delete</a>
<?php } ?>
</code>```

Body:
here an an example...

<?php if ($row['user_id']==1){ ?>
<a href="<?php echo site_url('members/delete/'.$row['user_id']); ?>" class="btn btn-danger" onclick="return confirm('Are you sure to delete?')">delete</a>
<?php } ?>


问:
After getting all documents in collection can't add field to ArrayList, Android Studio, Java, Firebase Firestore
Hi guys I have a problem as I am getting the whole collection from Firebase Firestore and want get the field "topic name" in each document and add it into an ArrayList to then display this topics in a ListView. It is gonna be a part of Forum part of my application.

BUT!

It seems that it gets the documents, and reads their fields as I can see in the Logs

```<code>Log.d(TAG, document.getId() + " => " + document.get("topic_name"));
</code>```

_

```<code>D/TAG: 6EvC4SqqDxR4TYelLOKM => Topic 1
KpXLBDzSkAb2u96knG8L => Topic 4
SY49j4RqcOI1v79EIVME => Topic 3
xS0Hw4Rj5KPGj1G7vy7T => Topic 2
</code>```

it doesn't add it to the ArrayList or it is in some way gone because the device do not display the list.

At First I thought it is because the ArrayList when it is accessed from within inner class needs to be declared final but that is not the case, as I added a test topics to check that assumption.  (Test Topic 123-Test to Topic 125) and it displays them normally, so that is not the case with ArrayList being final.

I tried putting the whole code responsible for ListView inside the onComplete method but it doesn't seem to work, because the Adapter becomes full of errors, I would like some help if possible or maybe an alternate idea on how to do it. If I replicated the topic I am sorry I tried looking for answer but was unable to find it.

The code is below:

```<code>public class Forum extends Activity {

public static final String TAG = "TAG";
FirebaseFirestore db;

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

    db = FirebaseFirestore.getInstance();
    final ArrayList<String> forumTopics = new ArrayList<>();

    db.collection("forum_topics")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {

                    if (task.isSuccessful()) {
                        int count = 0;
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            forumTopics.add(count, document.getString("topic_name"));
                            count += 1;
                            Log.d(TAG, document.getId() + " => " + document.get("topic_name"));
                        }

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

    String test_string = "Test Topic 123";
    forumTopics.add(0,test_string);
    forumTopics.add(1,"Test Topic 124");
    forumTopics.add(2,"Test Topic 125");
    forumTopics.add(3,"Test Topic 126");

    ListAdapter forumAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, forumTopics);
    ListView forumListView =  findViewById(R.id.ForumListView);
    forumListView.setAdapter(forumAdapter);

    forumListView.setOnItemClickListener(
            new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String topic = String.valueOf(parent.getItemAtPosition(position));
                    Toast.makeText(Forum.this, topic, Toast.LENGTH_LONG).show();
                }
            }
    );
}
</code>```

This is the output on the device

Thank you very much.

答:
Try with this</p>

```<code>db.collection("forum_topics")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {

                    if (task.isSuccessful()) {
                        int count = 0;
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            forumTopics.add(count, document.getString("topic_name"));
                            count += 1;
                             forumTopics.add(document.get("topic_name"));
                        }
                        forumAdapter.notifyDataSetChanged()
                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });

    ListAdapter forumAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, forumTopics);
    ListView forumListView =  findViewById(R.id.ForumListView);
    forumListView.setAdapter(forumAdapter);
</code>```

Body:
Hi guys I have a problem as I am getting the whole collection from Firebase Firestore and want get the field "topic name" in each document and add it into an ArrayList to then display this topics in a ListView. It is gonna be a part of Forum part of my application.

BUT!

It seems that it gets the documents, and reads their fields as I can see in the Logs

Log.d(TAG, document.getId() + " => " + document.get("topic_name"));

_

D/TAG: 6EvC4SqqDxR4TYelLOKM => Topic 1
KpXLBDzSkAb2u96knG8L => Topic 4
SY49j4RqcOI1v79EIVME => Topic 3
xS0Hw4Rj5KPGj1G7vy7T => Topic 2

it doesn't add it to the ArrayList or it is in some way gone because the device do not display the list.

At First I thought it is because the ArrayList when it is accessed from within inner class needs to be declared final but that is not the case, as I added a test topics to check that assumption.  (Test Topic 123-Test to Topic 125) and it displays them normally, so that is not the case with ArrayList being final.

I tried putting the whole code responsible for ListView inside the onComplete method but it doesn't seem to work, because the Adapter becomes full of errors, I would like some help if possible or maybe an alternate idea on how to do it. If I replicated the topic I am sorry I tried looking for answer but was unable to find it.

The code is below:

public class Forum extends Activity {

public static final String TAG = "TAG";
FirebaseFirestore db;

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

    db = FirebaseFirestore.getInstance();
    final ArrayList<String> forumTopics = new ArrayList<>();

    db.collection("forum_topics")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {

                    if (task.isSuccessful()) {
                        int count = 0;
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            forumTopics.add(count, document.getString("topic_name"));
                            count += 1;
                            Log.d(TAG, document.getId() + " => " + document.get("topic_name"));
                        }

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

    String test_string = "Test Topic 123";
    forumTopics.add(0,test_string);
    forumTopics.add(1,"Test Topic 124");
    forumTopics.add(2,"Test Topic 125");
    forumTopics.add(3,"Test Topic 126");

    ListAdapter forumAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, forumTopics);
    ListView forumListView =  findViewById(R.id.ForumListView);
    forumListView.setAdapter(forumAdapter);

    forumListView.setOnItemClickListener(
            new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String topic = String.valueOf(parent.getItemAtPosition(position));
                    Toast.makeText(Forum.this, topic, Toast.LENGTH_LONG).show();
                }
            }
    );
}

This is the output on the device

Thank you very much.

Body:
Try with this

db.collection("forum_topics")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {

                    if (task.isSuccessful()) {
                        int count = 0;
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            forumTopics.add(count, document.getString("topic_name"));
                            count += 1;
                             forumTopics.add(document.get("topic_name"));
                        }
                        forumAdapter.notifyDataSetChanged()
                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });

    ListAdapter forumAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, forumTopics);
    ListView forumListView =  findViewById(R.id.ForumListView);
    forumListView.setAdapter(forumAdapter);


问:
IN operator in SQL Statement Does not work?
In SQL Server, I have a table MyTable, with the following 3 columns, P(bigint), F(bigint), D(bigint).

Now what I need to do is to group all records by same P value, then in each group, calculate the following value:

```<code>V = ABS((P & 0xFFFFFFFF) * 256 - F)
</code>```

for each record, and delete all records in the group, except for the one with the minimum value of V.

So I write the SQL statement as follows:

```<code>DELETE FROM MyTable WHERE (P, ABS((P & 0xFFFFFFFF) * 256 - F)) NOT IN (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) FROM MyTable GROUP BY P HAVING COUNT(*) > 1)
</code>```

But in SQL Server, I will get the following error:

```<code>Msg 4145 SQL Server An expression of non-boolean type specified in a context where a condition is expected,near ','
</code>```

Why? Also whether bitwise and & works in SQL Server 2005? I only have SQL Server 2008 R2 and the online document at https://learn.microsoft.com/en-us/sql/t-sql/language-elements/bitwise-and-transact-sql?view=sql-server-ver15 does not indicate whether it support 2005 & 2008.

Update1

P, F, D are all bigint type.

Update2

With the helps of others, I finally write a query with NOT EXISTS, as follows:

Method 1: DELETE t FROM MyTable t WHERE NOT EXISTS (SELECT 1 FROM (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) as minpf
  FROM MyTable GROUP BY P) tt WHERE tt.P = t.P AND tt.minpf = ABS((t.P & 0xFFFFFFFF) * 256 - t.F))

Note: I remove the HAVE COUNT(*) > 1, otherwise, the statement will also delete those records who are in a group with only one record.

Though it works, I doubt its performance. Since in most of the groups(group by P), there will only be one record, while calculating the minpf in such a group and then delete the record with the calculated value <> minpf is wasting time(no records are deleted in such a group). So just wonder if there are better way to do the same thing?

Update 3

I test the performance of my method(method 1) with the two methods Gordon provided(with minor revision)

Method 2:

DELETE t
    FROM MyTable t LEFT JOIN
         (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) as minpf
          FROM MyTable
          GROUP BY P
         ) tt
         ON tt.p = t.p AND tt.minpf = (tt.P & 0xFFFFFFFF) * 256 - tt.F)
    WHERE tt.P IS NULL;

Method 3:

DELETE t FROM (SELECT t.*,
                 ROW_NUMBER() OVER (PARTITION BY P ORDER BY ABS((P & 0xFFFFFFFF) * 256 - F)) as seqnum
          FROM MyTable t
         ) t
     WHERE seqnum > 1;

The performance data are below:

First Test:

(22721 rows affected)
Method 1:16094

(22721 rows affected)
Method 2:17156

(22721 rows affected)
Method 3:12188

Second Test:

(22721 rows affected)
Method 1:26297

(22721 rows affected)
Method 2:27562

(22721 rows affected)
Method 3:11625

3rd Test:

(22721 rows affected)
Method 1:26297

(22721 rows affected)
Method 2:27359

(22721 rows affected)
Method 3:11578

So based on the test, method 3 has the best performance.

答:
Try this :</p>

```<code>DELETE FROM MyTable
WHERE concat(P, ABS((P & 0xFFFFFFFF) * 256 - F)) NOT IN (SELECT concat( P, MIN(ABS((P &
0xFFFFFFFF) * 256 - F))) FROM MyTable GROUP BY P HAVING COUNT(*) > 1)
</code>```

Body:
In SQL Server, I have a table MyTable, with the following 3 columns, P(bigint), F(bigint), D(bigint).

Now what I need to do is to group all records by same P value, then in each group, calculate the following value:

V = ABS((P & 0xFFFFFFFF) * 256 - F)

for each record, and delete all records in the group, except for the one with the minimum value of V.

So I write the SQL statement as follows:

DELETE FROM MyTable WHERE (P, ABS((P & 0xFFFFFFFF) * 256 - F)) NOT IN (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) FROM MyTable GROUP BY P HAVING COUNT(*) > 1)

But in SQL Server, I will get the following error:

Msg 4145 SQL Server An expression of non-boolean type specified in a context where a condition is expected,near ','

Why? Also whether bitwise and & works in SQL Server 2005? I only have SQL Server 2008 R2 and the online document at https://learn.microsoft.com/en-us/sql/t-sql/language-elements/bitwise-and-transact-sql?view=sql-server-ver15 does not indicate whether it support 2005 & 2008.

Update1

P, F, D are all bigint type.

Update2

With the helps of others, I finally write a query with NOT EXISTS, as follows:

Method 1: DELETE t FROM MyTable t WHERE NOT EXISTS (SELECT 1 FROM (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) as minpf
  FROM MyTable GROUP BY P) tt WHERE tt.P = t.P AND tt.minpf = ABS((t.P & 0xFFFFFFFF) * 256 - t.F))

Note: I remove the HAVE COUNT(*) > 1, otherwise, the statement will also delete those records who are in a group with only one record.

Though it works, I doubt its performance. Since in most of the groups(group by P), there will only be one record, while calculating the minpf in such a group and then delete the record with the calculated value <> minpf is wasting time(no records are deleted in such a group). So just wonder if there are better way to do the same thing?

Update 3

I test the performance of my method(method 1) with the two methods Gordon provided(with minor revision)

Method 2:

DELETE t
    FROM MyTable t LEFT JOIN
         (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) as minpf
          FROM MyTable
          GROUP BY P
         ) tt
         ON tt.p = t.p AND tt.minpf = (tt.P & 0xFFFFFFFF) * 256 - tt.F)
    WHERE tt.P IS NULL;

Method 3:

DELETE t FROM (SELECT t.*,
                 ROW_NUMBER() OVER (PARTITION BY P ORDER BY ABS((P & 0xFFFFFFFF) * 256 - F)) as seqnum
          FROM MyTable t
         ) t
     WHERE seqnum > 1;

The performance data are below:

First Test:

(22721 rows affected)
Method 1:16094

(22721 rows affected)
Method 2:17156

(22721 rows affected)
Method 3:12188

Second Test:

(22721 rows affected)
Method 1:26297

(22721 rows affected)
Method 2:27562

(22721 rows affected)
Method 3:11625

3rd Test:

(22721 rows affected)
Method 1:26297

(22721 rows affected)
Method 2:27359

(22721 rows affected)
Method 3:11578

So based on the test, method 3 has the best performance.

Body:
Try this :

DELETE FROM MyTable
WHERE concat(P, ABS((P & 0xFFFFFFFF) * 256 - F)) NOT IN (SELECT concat( P, MIN(ABS((P &
0xFFFFFFFF) * 256 - F))) FROM MyTable GROUP BY P HAVING COUNT(*) > 1)


问:
Laravel Error: Too few arguments to function, 0 passed and exactly 1 expected
Using Laravel-5.8, I have this code:

```<code>public function manager_employee_list(Request $request)
{

    $employees = HrEmployee::paginate(6);

    return view('appraisal.appraisal_goals.manager_employee_list')->with('employees', $employees);
}
</code>```

And it render this view: manager_employee_list

```<code>      <div class="row d-flex align-items-stretch">
          @if (count($employees))
          @foreach($employees as $key => $employee)
        <div class="col-12 col-sm-6 col-md-4 d-flex align-items-stretch">
          <div class="card bg-light">
            <div class="card-header text-muted border-bottom-0">
              {{isset($employee->designation) ? $employee->designation->designation_name : ''}}
            </div>
            <div class="card-body pt-0">
              <div class="row">
                <div class="col-7">
                  <h2 class="lead"><b>Staff ID: {{$employee->employee_code}}</b></h2>
                  <h2 class="lead"><b>{{$employee->first_name}} {{$employee->last_name}}</b></h2>

                  <h6 class="lead"><b>Employee Department: </b>{{isset($employee->department) ? $employee->department->dept_name : ''}}</h6>
                </div>
                <div class="col-5 text-center">
                            @if($employee->emp_image != '')
                                <img src="{{ URL::to('/') }}/public/storage/employees/image/{{ $employee->emp_image }}" class="img-circle img-fluid" />

                            @else
                                <img class="profile-user-img img-fluid img-circle" src="{{asset('theme/adminlte3/dist/img/default.png')}}" alt="" class="img-circle img-fluid">
                            @endif
                </div>
              </div>
            </div>
            <div class="card-footer">
              <div class="text-right">
                <a href="{{ route('appraisal.appraisal_goals.manager_employee_goal', ['id'=>$employee->id]) }}" class="btn btn-sm btn-primary">
                  <i class="fas fa-user"></i> View Goal
                </a>
              </div>
            </div>
          </div>
        </div>
        @endforeach
        @else
        <h4 style="text-align:center;">No matching records found</h4>
        @endif
      </div>
</code>```

I want to pass the parameter

['id'=>$employee->id]

from above to another controller action:

```<code>public function manager_employee_goal($id)
{

    $goals = AppraisalGoal::where('employee_id', $id)->get();

    return view('appraisal.appraisal_goals.manager_employee_goal')->with('goals', $goals);
}
</code>```

It utilizes it here:

$goals = AppraisalGoal::where('employee_id', $id)->get();

When I clicked on

```<code><a href="{{ route('appraisal.appraisal_goals.manager_employee_goal', ['id'=>$employee->id]) }}" class="btn btn-sm btn-primary">
     <i class="fas fa-user"></i> View Goal
</a>
</code>```

I got this error:

Too few arguments to function App\Http\Controllers\Appraisal\AppraisalGoalsController::manager_employee_goal(), 0 passed and exactly 1 expected

and this is underlined:

public function manager_employee_goal($id)

route/web.php

```<code>Route::get('appraisal_goals/manager_employee_list', 'Appraisal\AppraisalGoalsController@manager_employee_list')->name('appraisal.appraisal_goals.manager_employee_list');
Route::get('appraisal_goals/manager_employee_goal', 'Appraisal\AppraisalGoalsController@manager_employee_goal')->name('appraisal.appraisal_goals.manager_employee_goal');
</code>```

How do I resolve it?

Thank you.

答:
You need to change in your web.php file. add {id} in URL.

otherwise, all are fine as now your get method will be like 'appraisal_goals/manager_employee_goal/{id}'

```<code>Route::get('appraisal_goals/manager_employee_goal/{id}','Appraisal\AppraisalGoalsController@manager_employee_goal')->name('appraisal.appraisal_goals.manager_employee_goal');
</code>```

Body:
Using Laravel-5.8, I have this code:

public function manager_employee_list(Request $request)
{

    $employees = HrEmployee::paginate(6);

    return view('appraisal.appraisal_goals.manager_employee_list')->with('employees', $employees);
}

And it render this view: manager_employee_list

          @if (count($employees))
          @foreach($employees as $key => $employee)

              {{isset($employee->designation) ? $employee->designation->designation_name : ''}}

Staff ID: {{$employee->employee_code}}

{{$employee->first_name}} {{$employee->last_name}}

Employee Department: {{isset($employee->department) ? $employee->department->dept_name : ''}}

                            @if($employee->emp_image != '')
                                emp_image }}" class="img-circle img-fluid" />

                            @else

                            @endif

                $employee->id]) }}" class="btn btn-sm btn-primary">
                   View Goal

        @endforeach
        @else

No matching records found

        @endif

I want to pass the parameter

['id'=>$employee->id]

from above to another controller action:

public function manager_employee_goal($id)
{

    $goals = AppraisalGoal::where('employee_id', $id)->get();

    return view('appraisal.appraisal_goals.manager_employee_goal')->with('goals', $goals);
}

It utilizes it here:

$goals = AppraisalGoal::where('employee_id', $id)->get();

When I clicked on

$employee->id]) }}" class="btn btn-sm btn-primary">
      View Goal

I got this error:

Too few arguments to function App\Http\Controllers\Appraisal\AppraisalGoalsController::manager_employee_goal(), 0 passed and exactly 1 expected

and this is underlined:

public function manager_employee_goal($id)

route/web.php

Route::get('appraisal_goals/manager_employee_list', 'Appraisal\AppraisalGoalsController@manager_employee_list')->name('appraisal.appraisal_goals.manager_employee_list');
Route::get('appraisal_goals/manager_employee_goal', 'Appraisal\AppraisalGoalsController@manager_employee_goal')->name('appraisal.appraisal_goals.manager_employee_goal');

How do I resolve it?

Thank you.

Body:
You need to change in your web.php file. add {id} in URL.

otherwise, all are fine as now your get method will be like 'appraisal_goals/manager_employee_goal/{id}'

Route::get('appraisal_goals/manager_employee_goal/{id}','Appraisal\AppraisalGoalsController@manager_employee_goal')->name('appraisal.appraisal_goals.manager_employee_goal');


问:
onmouseover and onmouseleave triggering randomnly on image map
I'm having an issue with onmouseover and onmouseleave event. This code only works maybe 5% of the time and I don't understand why. Just looking at the console when I hover over the image map. It triggers the onmouseover then the onmouseleave and then onmouseover again. If I comment out the bootstrap modal show and hide then the image just swaps and triggers events normally. I don't know if this is an issue with bootstrap modals or what but I have two call to action buttons on the same page that trigger normally. Any help is greatly appreciated.

Here is my jquery

```<code>  function openAutomation(){
    console.log("openAutomation");
    $('#image-map').attr('src', automation);
    $('#automationModal').modal('show');
  };

  function openIntegration() {
    console.log("openIntegration");
    $('#image-map').attr('src', integration);
    $('#integrationModal').modal('show');
  };

  function closeAutomation(){
    console.log("closeAutomation");
    $('#image-map').attr('src', original);
    $('#automationModal').modal('hide');
  };

  function closeIntegration() {
    console.log("closeIntegration");
    $('#image-map').attr('src', original);
    $('
</code>```

Here is my HTML Code:

```<code><map name="image-map" class="image-map-class">

<area class="automation-map" onmouseover="openAutomation()" onmouseleave="closeAutomation()" coords="304,559,1011,148,1143,229,1518,447,1516,485,1463,497,1444,510,1436,522,1241,636,1159,716,1076,762,959,801,813,884,494,696,304,589" shape="poly">

<area class="integration-map" onmouseover="openIntegration()" onmouseleave="closeIntegration()" coords="1571,477,1456,494,1418,566,1088,756,871,881,868,916,1006,993,1229,1074,1274,1063,1348,1021,1483,944,1629,856,1793,761,1848,732,1881,701,1879,686,1703,551" shape="poly">

</map>

</code>```

答:
I would have used an svg image instead of png for that and group elements into interactive areas :

```<code><svg viewBox=""><g class="interactive-map">your svg code (path,circle,rect)</g></svg>
</code>```

In this way you will have responsive and interactive areas.

Body:
I'm having an issue with onmouseover and onmouseleave event. This code only works maybe 5% of the time and I don't understand why. Just looking at the console when I hover over the image map. It triggers the onmouseover then the onmouseleave and then onmouseover again. If I comment out the bootstrap modal show and hide then the image just swaps and triggers events normally. I don't know if this is an issue with bootstrap modals or what but I have two call to action buttons on the same page that trigger normally. Any help is greatly appreciated.

Here is my jquery

  function openAutomation(){
    console.log("openAutomation");
    $('#image-map').attr('src', automation);
    $('#automationModal').modal('show');
  };

  function openIntegration() {
    console.log("openIntegration");
    $('#image-map').attr('src', integration);
    $('#integrationModal').modal('show');
  };

  function closeAutomation(){
    console.log("closeAutomation");
    $('#image-map').attr('src', original);
    $('#automationModal').modal('hide');
  };

  function closeIntegration() {
    console.log("closeIntegration");
    $('#image-map').attr('src', original);
    $('

Here is my HTML Code:

<map name="image-map" class="image-map-class">

<area class="automation-map" onmouseover="openAutomation()" onmouseleave="closeAutomation()" coords="304,559,1011,148,1143,229,1518,447,1516,485,1463,497,1444,510,1436,522,1241,636,1159,716,1076,762,959,801,813,884,494,696,304,589" shape="poly">

<area class="integration-map" onmouseover="openIntegration()" onmouseleave="closeIntegration()" coords="1571,477,1456,494,1418,566,1088,756,871,881,868,916,1006,993,1229,1074,1274,1063,1348,1021,1483,944,1629,856,1793,761,1848,732,1881,701,1879,686,1703,551" shape="poly">

</map>

Body:
I would have used an svg image instead of png for that and group elements into interactive areas :

<svg viewBox=""><g class="interactive-map">your svg code (path,circle,rect)</g></svg>

In this way you will have responsive and interactive areas.


问:
How to get discriminated union behavior with overloading
I have function overloading

```<code>function MyFunc(values: IFirst, type: MyEnum.FIRST): number
function MyFunc(values: ISecond, type: MyEnum.SECOND): number
function MyFunc(values: (IFirst | ISecond), type: (MyEnum.FIRST | MyEnum.SECOND)): number {
  if(type === MyEnum.FIRST) {
    values.
  }
  ...
}
</code>```

Why my values inside if statement is conjunction of IFirst and ISecond ?

How to get discriminated union behavior here? Without adding type string to interfaces, but with type argument.

I want my values to be IFirst in if statement.

答:
You could wrap parameters in object, so they can be discriminated:</p>

```<code>enum MyEnum {
    FIRST,
    SECOND
}

interface IFirst {
    first: number;
}

interface ISecond {
    second: number;
}

function MyFunc(param: { value: IFirst, type: MyEnum.FIRST }): number
function MyFunc(param: { value: ISecond, type: MyEnum.SECOND }): number
function MyFunc(param: { value: IFirst, type: MyEnum.FIRST } | { value: ISecond, type: MyEnum.SECOND }): number {
    if (param.type === MyEnum.FIRST) {
        return param.value.first;
    } else {
        return param.value.second;
    }
}
</code>```

Body:
I have function overloading

function MyFunc(values: IFirst, type: MyEnum.FIRST): number
function MyFunc(values: ISecond, type: MyEnum.SECOND): number
function MyFunc(values: (IFirst | ISecond), type: (MyEnum.FIRST | MyEnum.SECOND)): number {
  if(type === MyEnum.FIRST) {
    values.
  }
  ...
}

Why my values inside if statement is conjunction of IFirst and ISecond ?

How to get discriminated union behavior here? Without adding type string to interfaces, but with type argument.

I want my values to be IFirst in if statement.

Body:
You could wrap parameters in object, so they can be discriminated:

enum MyEnum {
    FIRST,
    SECOND
}

interface IFirst {
    first: number;
}

interface ISecond {
    second: number;
}

function MyFunc(param: { value: IFirst, type: MyEnum.FIRST }): number
function MyFunc(param: { value: ISecond, type: MyEnum.SECOND }): number
function MyFunc(param: { value: IFirst, type: MyEnum.FIRST } | { value: ISecond, type: MyEnum.SECOND }): number {
    if (param.type === MyEnum.FIRST) {
        return param.value.first;
    } else {
        return param.value.second;
    }
}