问:
Unable to build my app cause ConfigureServices returns error
I'm new in ASP.NET and on making all of these things working right.

I want to get data from my MSSQL database, and pass it to my Angular web application, you know like simple Frontend <-> Backend communication so I made Data model looking like this::

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebAPI_1.Models
{
    public class Users
    {

        public int id { get; set; }
        public string Imie { get; set; }
        public string Nazwisko { get; set; }
        public string Login { get; set; }
        public string Haslo { get; set; }
    }
}
</code>```

Also I had a DataContext file looking like this:

```<code>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebAPI_1.Models;

namespace WebAPI_1.Data
{
    public class DataContext: DbContext
    {
        public DataContext(DbContextOptions<DataContext> options) : base(options) { } //wywołuje konst bazowy i przekazuje opcje

        public DbSet<Users> Users { get ; set; }
    }
}
</code>```

Everything in that files working i guess fine, but i have only one CS0161 Error in the Startup.cs file:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using WebAPI_1.Data;
using Microsoft.EntityFrameworkCore;
using System.Data.Sql;

namespace WebAPI_1
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public object ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DataContext>(s => s.UseSqlServer("ConnectionString"));

            services.AddControllers();

            services.AddMvc(services => services.EnableEndpointRouting = false);

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseMvc();
        }
    }
}
</code>```

The error description from my IDE (VS 2019):

*Severity   Code    Description Project File    Line    Suppression State
Error   CS0161  'Startup.ConfigureServices(IServiceCollection)': not all code paths return a value  WebAPI_1    C:\Users\Michal\source\repos\WebAPI_1\WebAPI_1\Startup.cs   29  Active
*

What i already know:

I don't undrstand why i got this error

It's because  services.AddDbContext(s => s.UseSqlServer("ConnectionString")); doesen't return anything

In conclusion, i want to ask you for help and possible sollutions.

答: Your ConfigureServices method wants to return an object. I guess it should not return anything (void).

Body:
I'm new in ASP.NET and on making all of these things working right.

I want to get data from my MSSQL database, and pass it to my Angular web application, you know like simple Frontend <-> Backend communication so I made Data model looking like this::

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebAPI_1.Models
{
    public class Users
    {

        public int id { get; set; }
        public string Imie { get; set; }
        public string Nazwisko { get; set; }
        public string Login { get; set; }
        public string Haslo { get; set; }
    }
}

Also I had a DataContext file looking like this:

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebAPI_1.Models;

namespace WebAPI_1.Data
{
    public class DataContext: DbContext
    {
        public DataContext(DbContextOptions<DataContext> options) : base(options) { } //wywołuje konst bazowy i przekazuje opcje

        public DbSet<Users> Users { get ; set; }
    }
}

Everything in that files working i guess fine, but i have only one CS0161 Error in the Startup.cs file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using WebAPI_1.Data;
using Microsoft.EntityFrameworkCore;
using System.Data.Sql;

namespace WebAPI_1
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public object ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DataContext>(s => s.UseSqlServer("ConnectionString"));

            services.AddControllers();

            services.AddMvc(services => services.EnableEndpointRouting = false);

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseMvc();
        }
    }
}

The error description from my IDE (VS 2019):

*Severity   Code    Description Project File    Line    Suppression State
Error   CS0161  'Startup.ConfigureServices(IServiceCollection)': not all code paths return a value  WebAPI_1    C:\Users\Michal\source\repos\WebAPI_1\WebAPI_1\Startup.cs   29  Active
*

What i already know:

I don't undrstand why i got this error

It's because  services.AddDbContext(s => s.UseSqlServer("ConnectionString")); doesen't return anything

In conclusion, i want to ask you for help and possible sollutions.


来源: stackexchange

问:
Breakpoint not hitting
I ported an application from VC6 to VS 2008. I rebuilt the application in release build.  The Pdb file is available in the folder where exe is located.  But when I loaded the application and put break point I am getting the following message

"The breakpoint will not currently be hit.No symbols have been loaded for this document"

What would be the cause of the issue?

答:
The debugger could not find either the application or the PDBs.

When you start the program, exactly which binaries are loaded are shown in the Output window.  Make sure the right files are being loaded.  When everything loads properly, the output looks something like this:

'hacks_vs10.exe': Loaded
  'C:\Users\john\Documents\Visual Studio
  2010\Projects\hacks_vs10\x64\Debug\hacks_vs10.exe',
  Symbols loaded.

When the PDB is not found, instead of saying "Symbols loaded" it says:

Cannot find or open the PDB file

Make sure that you are first running the correct version of your application (check the running path), and then make sure that the PDB is in that directory. You can change where the PDB is generated to by tweaking "Project>Properties...>Linker>Generate Program Database File"

ContentLicense: CC BY-SA 3.0

Title: Breakpoint not hitting


问:
How to remove jerky movement on chrome
I'm a developer for my fathers website. Yesterday, I made this custom cursor with vanilla Javascript and CSS : https://codepen.io/ZellRDesign/pen/PoqzgZX

After development, I tested it on my webapp.

Firefox : no problem, the code works very well and it is pretty awesome.

On Chrome : here I got my first problem, sometimes the custom cursor is jerky and I don't know how to reproduce this bug...
I got this bug only one time, but today, I share my code to friends and one of them say me "look the code is bugging"

Example of bug : https://i.imgur.com/PW3zCb1.gifv

So now, I have two questions :

how to patch the bug ?

and

how to improve the code to make it better ?

Thanks for help

const cursor = document.querySelector('.cursor');

document.addEventListener('mousemove', e => {
  cursor.setAttribute("style", "top: " + (e.pageY - 10) + "px; left: " + (e.pageX - 10) + "px;")
})

document.addEventListener('click', () => {
  cursor.classList.add("expand");

  setTimeout(() => {
    cursor.classList.remove("expand");
  }, 500)
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
  height: 100vh;
  //cursor: none;
  background: rgb(27, 27, 27);
}

.cursor {
  width: 20px;
  height: 20px;
  border: 1px solid #FAB313;
  ;
  border-radius: 50%;
  position: absolute;
  transition-duration: 200ms;
  transition-timing-function: ease-out;
  animation: cursorAnim .5s infinite alternate;
  pointer-events: none;
}

.cursor::after {
  content: "";
  width: 20px;
  height: 20px;
  position: absolute;
  border: 8px solid #FAB313;
  ;
  border-radius: 50%;
  opacity: .5;
  top: -8px;
  left: -8px;
  animation: cursorAnim2 .5s infinite alternate;
}

@keyframes cursorAnim {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(.7);
  }
}

@keyframes cursorAnim2 {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(.4);
  }
}

@keyframes cursorAnim3 {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(3);
  }
  100% {
    transform: scale(1);
    opacity: 0;
  }
}

.expand {
  animation: cursorAnim3 .5s forwards;
  border: 1px solid #1E2648;
}</code>```

```

答:
I modified your pen a little, it probably works as you need: https://codepen.io/bhoodream/pen/yLNJWEj

The main point you have problems with is moving with the top/left. There is a transform for such tasks, in your case you need translate3d. Here is an article on the topic: Animating movement with translate3d.

ContentLicense: CC BY-SA 4.0

Title: How to remove jerky movement on chrome

Body:
I'm a developer for my fathers website. Yesterday, I made this custom cursor with vanilla Javascript and CSS : https://codepen.io/ZellRDesign/pen/PoqzgZX

After development, I tested it on my webapp.

Firefox : no problem, the code works very well and it is pretty awesome.

On Chrome : here I got my first problem, sometimes the custom cursor is jerky and I don't know how to reproduce this bug...
I got this bug only one time, but today, I share my code to friends and one of them say me "look the code is bugging"

Example of bug : https://i.imgur.com/PW3zCb1.gifv

So now, I have two questions :

how to patch the bug ?

and

how to improve the code to make it better ?

Thanks for help

const cursor = document.querySelector('.cursor');

document.addEventListener('mousemove', e => {
  cursor.setAttribute("style", "top: " + (e.pageY - 10) + "px; left: " + (e.pageX - 10) + "px;")
})

document.addEventListener('click', () => {
  cursor.classList.add("expand");

  setTimeout(() => {
    cursor.classList.remove("expand");
  }, 500)
})

body {
  margin: 0;
  height: 100vh;
  //cursor: none;
  background: rgb(27, 27, 27);
}

.cursor {
  width: 20px;
  height: 20px;
  border: 1px solid #FAB313;
  ;
  border-radius: 50%;
  position: absolute;
  transition-duration: 200ms;
  transition-timing-function: ease-out;
  animation: cursorAnim .5s infinite alternate;
  pointer-events: none;
}

.cursor::after {
  content: "";
  width: 20px;
  height: 20px;
  position: absolute;
  border: 8px solid #FAB313;
  ;
  border-radius: 50%;
  opacity: .5;
  top: -8px;
  left: -8px;
  animation: cursorAnim2 .5s infinite alternate;
}

@keyframes cursorAnim {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(.7);
  }
}

@keyframes cursorAnim2 {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(.4);
  }
}

@keyframes cursorAnim3 {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(3);
  }
  100% {
    transform: scale(1);
    opacity: 0;
  }
}

.expand {
  animation: cursorAnim3 .5s forwards;
  border: 1px solid #1E2648;
}


问:
Difference between window (browser) and global (Node.js) objects
I am trying to understand how Javascript works under the hood so I've been playing around a bit. For example, the following code generates different outputs when in Chrome's console or when in Node.js:

```<code>var length = 10;
function fn () {
  console.log (this.length);
}
fn();
</code>```

In Chrome, I get the value 10 logged, while in Node, this is undefined. Is it because in the window object, global variables are treated as properties of window, while in Node, the global object has a different behavior? If so, what is happening in the global object, and how could I get a similar behavior to window, without declaring global.length?
I am doing this just as an exercise, there is no other purpose than understanding.

答:
The reason for the difference is that the top-level scope in a browser script is the global scope, but the top-level scope in a Node.js file is module scope. (By default it's an old-style Node.js module which is in loose mode, but in modern versions of Node.js you can opt into JavaScript standard module scope, which is in strict mode.)

At global scope, var creates a property on the global object, which you can access via the window global, via this at global scope, or via this in a loose-mode function you call without doing anything specific to set this. Your call to fn above is that last category: a loose-mode function called without setting this.

But at Node.js module scope, var just creates a var in the module, it doesn't create a global or a property on the global object. It's like doing this:

(function() { // The wrapper Node.js provides node-style modules
    // This is "module" scope
    var foo = 10;
    function fn () {
      console.log (this.foo);
    }
    fn();
})();         // End of the wrapper```
</div>
</div>
</p>

<p>(Why did I change <code>length</code> to <code>foo</code>? Because by default, <code>window</code> has a <code>length</code> property [the number of frames the window contains], which confused matters. :-) )</p>

<p>So it's just a difference in scope.</p>

<hr>

<p>You can also use module scope on modern browsers, including Chrome, via <code>type="module"</code> on the <code>script</code> tag. But since JavaScript standard modules are always in strict mode, the <code>this</code> inside the call to <code>fn</code> would be <code>undefined</code>, causing an error:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="module">
var length = 10;
function fn () {
  console.log(this);        // undefined
  console.log(this.length); // TypeError
}
fn();
</script></code>```

Body:
I am trying to understand how Javascript works under the hood so I've been playing around a bit. For example, the following code generates different outputs when in Chrome's console or when in Node.js:

var length = 10;
function fn () {
  console.log (this.length);
}
fn();

In Chrome, I get the value 10 logged, while in Node, this is undefined. Is it because in the window object, global variables are treated as properties of window, while in Node, the global object has a different behavior? If so, what is happening in the global object, and how could I get a similar behavior to window, without declaring global.length?
I am doing this just as an exercise, there is no other purpose than understanding.

Body:
The reason for the difference is that the top-level scope in a browser script is the global scope, but the top-level scope in a Node.js file is module scope. (By default it's an old-style Node.js module which is in loose mode, but in modern versions of Node.js you can opt into JavaScript standard module scope, which is in strict mode.)

At global scope, var creates a property on the global object, which you can access via the window global, via this at global scope, or via this in a loose-mode function you call without doing anything specific to set this. Your call to fn above is that last category: a loose-mode function called without setting this.

But at Node.js module scope, var just creates a var in the module, it doesn't create a global or a property on the global object. It's like doing this:

(function() { // The wrapper Node.js provides node-style modules
    // This is "module" scope
    var foo = 10;
    function fn () {
      console.log (this.foo);
    }
    fn();
})();         // End of the wrapper

(Why did I change length to foo? Because by default, window has a length property [the number of frames the window contains], which confused matters. :-) )

So it's just a difference in scope.

You can also use module scope on modern browsers, including Chrome, via type="module" on the script tag. But since JavaScript standard modules are always in strict mode, the this inside the call to fn would be undefined, causing an error:

<script type="module">
var length = 10;
function fn () {
  console.log(this);        // undefined
  console.log(this.length); // TypeError
}
fn();
</script>


问:
Hiding multiple tag with same name or class
I have using prototype 1.5. Can you please tell me, how can i hide/show the div tag with same name or class. </p>

```<code>Element.hide('indicate')
</code>```

<p>But, the above line only satisfy to hide the first element only. "indicate" is the id. </p>

答:
As pointed out, the $$ function is required. It returns an array so you need to invoke hide on all items.

```<code>$$('.indicate').invoke('hide');
</code>```

Or, for bonus showing off points, you can use the function directly as an object:

```<code>var hideFunc = Element.hide;
$$('.indicate').each(hideFunc);
</code>```

The advantage of this technique means you can easily swap the function for another, such as a Scriptaculous effect.

```<code>hideFunc = Effect.SwitchOff;
</code>```

Body:
I have using prototype 1.5. Can you please tell me, how can i hide/show the div tag with same name or class.

Element.hide('indicate')

But, the above line only satisfy to hide the first element only. "indicate" is the id.

Body:
As pointed out, the $$ function is required. It returns an array so you need to invoke hide on all items.

$$('.indicate').invoke('hide');

Or, for bonus showing off points, you can use the function directly as an object:

var hideFunc = Element.hide;
$$('.indicate').each(hideFunc);

The advantage of this technique means you can easily swap the function for another, such as a Scriptaculous effect.

hideFunc = Effect.SwitchOff;


问:
moq: When using Setup(), how is equality of method parameters determined?
I'm using the Setup() method to set up the behaviour of a mocked instance of an interface.

The method I'm setting up (let's call it DoSomething()) accepts an instance of a class (let's call the class Foo).

```<code>Foo foo = // Existing foo instance
Mock<IMyInterface> mock = new Mock<IMyInterface>();
mock.Setup(x => x.DoSomething(foo)).Returns(1);
</code>```

The problem I'm having is that when I use the mock, it never matches the setup, so never returns 1.

Can anyone help? How does Moq determine whether the parameters provided to a set up method are equal or not?

答:
For a slightly more detailed answer, Moq uses the ConstantMatcher (link is to current latest version 4.13.1). The implementation of that matcher is

Use object.Equals

If object.Equals failed and value implements IEnumerable use SequenceEqual<object> (which uses object.Equals for each element)

If both of the above failed return false

Body:
I'm using the Setup() method to set up the behaviour of a mocked instance of an interface.

The method I'm setting up (let's call it DoSomething()) accepts an instance of a class (let's call the class Foo).

Foo foo = // Existing foo instance
Mock<IMyInterface> mock = new Mock<IMyInterface>();
mock.Setup(x => x.DoSomething(foo)).Returns(1);

The problem I'm having is that when I use the mock, it never matches the setup, so never returns 1.

Can anyone help? How does Moq determine whether the parameters provided to a set up method are equal or not?


问:
C# StreamWriter writes extra bytes to the Stream
```<code>var memStream = new MemoryStream();
using (var sw = new StreamWriter(memStream, Encoding.UTF8, 4194304 /* 4 MiB */, leaveOpen: true))
{
     var str = new string(Enumerable.Repeat(' ', 10240 /* 10 * KiB */).ToArray());
     Console.WriteLine(str.Length);
     Console.WriteLine(Encoding.UTF8.GetBytes(str).Length);
     sw.Write(str);
     sw.Flush();
     Console.WriteLine(memStream.Length);
}
// Output
// ---------
// 10240
// 10240
// 10243

// Output which I was expecting
// ---------
// 10240
// 10240
// 10240
</code>```

I checked the StreamWriter.Write(String) documentation on MSDN but I didn't find anything which mentions that this API can write extra bytes to the stream.
(MSDN Doc StreamWriter.Write).
I am using .NET Core 3.1, but I am guessing this behavior also holds for Core 2.0 and Framework although I have not explicitly tested my hypothesis for them. I read the StreamWriter documentation thoroughly, I don't find any mention of such a behavior. Is this a bug or expected behavior or am I missing something ?

答:
When I run this locally i get

10240

  10240

  10243

On further inspection the extra 3 bytes appear to be at the beginning of the stream 239 187 191 or EF BB BF in hex. This is the Byte Order Mark (BOM) https://en.wikipedia.org/wiki/Byte_order_mark

To remove these extra characters from the ouptut use new UTF8Encoding(false) to omit the BOM, instead of Encoding.UTF8 in the creation of the StreamWriter

using (var sw = new StreamWriter(memStream, new UTF8Encoding(false), 4194304 /* 4 MiB */, leaveOpen: true))
```

Body:
var memStream = new MemoryStream();
using (var sw = new StreamWriter(memStream, Encoding.UTF8, 4194304 /* 4 MiB */, leaveOpen: true))
{
     var str = new string(Enumerable.Repeat(' ', 10240 /* 10 * KiB */).ToArray());
     Console.WriteLine(str.Length);
     Console.WriteLine(Encoding.UTF8.GetBytes(str).Length);
     sw.Write(str);
     sw.Flush();
     Console.WriteLine(memStream.Length);
}
// Output
// ---------
// 10240
// 10240
// 10243

// Output which I was expecting
// ---------
// 10240
// 10240
// 10240

I checked the StreamWriter.Write(String) documentation on MSDN but I didn't find anything which mentions that this API can write extra bytes to the stream.
(MSDN Doc StreamWriter.Write).
I am using .NET Core 3.1, but I am guessing this behavior also holds for Core 2.0 and Framework although I have not explicitly tested my hypothesis for them. I read the StreamWriter documentation thoroughly, I don't find any mention of such a behavior. Is this a bug or expected behavior or am I missing something ?


问:
Translator Text API 3.0: Transliterate
I have followed this document and tried in postman to check for output by giving these parameters and headers

```<code>Headers:
Ocp-Apim-Subscription-Key:****************
Content-Type:application/json
Content-Length:32

Query Params:
api-version:3.0
language:hi
fromScript:Deva
toScript:Latn

body :
[
    {"Text":"मैं हूँ ना"}
]
</code>```

{"error":{"code":400000,"message":"One of the request inputs is not
  valid."}}

I'm not able to get the output. can anyone pls help me here.

答: Your body is an invalid json object. Try remove the square brackets from your body.</p>

Title: Translator Text API 3.0: Transliterate

Body:
I have followed this document and tried in postman to check for output by giving these parameters and headers

Headers:
Ocp-Apim-Subscription-Key:****************
Content-Type:application/json
Content-Length:32

Query Params:
api-version:3.0
language:hi
fromScript:Deva
toScript:Latn

body :
[
    {"Text":"मैं हूँ ना"}
]

{"error":{"code":400000,"message":"One of the request inputs is not
  valid."}}

I'm not able to get the output. can anyone pls help me here.


问:
Array loop always returning last value
I have the following loop:

```<code>var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

var html = "";

for (let i = 0; i < array.length; i++) {
  var html = "<div class='group' data-department='"+array[i]+"'>";
  html += "<div class='title'>" + textArray[i] + "</div>";
  html += "</div>";
}
</code>```

The output of this JS is:

```<code><div class="group" data-department="Value 3">
   <div class="title">Text 3</div>
</div>

<div class="group" data-department="Value 3">
   <div class="title">Text 3</div>
</div>

<div class="group" data-department="Value 3">
   <div class="title">Text 3</div>
</div>
</code>```

What I'm after is:

```<code><div class="group" data-department="Value 1">
   <div class="title">Text 1</div>
</div>

<div class="group" data-department="Value 2">
   <div class="title">Text 2</div>
</div>

<div class="group" data-department="Value 3">
   <div class="title">Text 3</div>
</div>
</code>```

A console.log("Value: " + array[i]); returns:

```<code>Value: Value 1
Value: Value 2
Value: Value 3
</code>```

And a console.log("Text: " + textArray[i]); returns:

```<code>Text: Text 1
Text: Text 2
Text: Text 3
</code>```

So unsure why my markup is being rendered based on the last item in the array?

Following the removal of var from with the loop, I'm getting the following results (container divs get nested within each other):

var html = "";

for (let i = 0; i < array.length; i++) {
  html += "
";
  html += "
" + textArray[i] + "
";
  html += "
";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="group" data-department="Value 1">
  <div class="title">Text 1</div>
  <div class="group" data-department="Value 2">
    <div class="title">Text 2</div>
    <div class="group" data-department="Value 3">
      <div class="title">Text 3</div>
    </div>
  </div>
</div></code>```

答:
Try to avoid using innerHTML, use document.createElement ad than set up the attributes you need. use appendChild to put one element into another

var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

for (let i = 0; i < array.length; i++) {
  const div1 = document.createElement('div')
  div1.dataset.department = array[i]
  div1.classList.add(`group`)

  const div2 = document.createElement('div')
  div2.classList.add(`title`)
  div2.innerText = textArray[i]

  div1.appendChild(div2)
  document.querySelector(`.parent`).appendChild(div1)
} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
</div></code>```

Title: Array loop always returning last value

Body:
I have the following loop:

var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

var html = "";

for (let i = 0; i < array.length; i++) {
  var html = "
";
  html += "
" + textArray[i] + "
";
  html += "
";
}

The output of this JS is:

Text 3

Text 3

Text 3

What I'm after is:

Text 1

Text 2

Text 3

A console.log("Value: " + array[i]); returns:

Value: Value 1
Value: Value 2
Value: Value 3

And a console.log("Text: " + textArray[i]); returns:

Text: Text 1
Text: Text 2
Text: Text 3

So unsure why my markup is being rendered based on the last item in the array?

Following the removal of var from with the loop, I'm getting the following results (container divs get nested within each other):

var html = "";

for (let i = 0; i < array.length; i++) {
  html += "
";
  html += "
" + textArray[i] + "
";
  html += "
";
}

Text 1

Text 2

Text 3

Body:
Try to avoid using innerHTML, use document.createElement ad than set up the attributes you need. use appendChild to put one element into another

var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

for (let i = 0; i < array.length; i++) {
  const div1 = document.createElement('div')
  div1.dataset.department = array[i]
  div1.classList.add(`group`)

  const div2 = document.createElement('div')
  div2.classList.add(`title`)
  div2.innerText = textArray[i]

  div1.appendChild(div2)
  document.querySelector(`.parent`).appendChild(div1)
}

<div class="parent">
</div>


问:
How can I use REST API authentication in Mendix?
I have designed an API REST service (with Bonita) to which I can perfectly connect with Postman, with the following parameters:

By the way, the x-www-form-urlencoded option that is selected comes from the Content-type application/x-www-form-urlencoded header that is not displayed in my screenshot. The official Bonita specification states that this header is needed and I always get a 200-OK status code as an answer.

How can I specify an equivalent request with the body part in a Mendix Call REST service in a microflow? Here is what I have so far:

I guess the body part should be specified in the Request tab, but I just don't know how to do it properly. I always get the following error message for my connector, which means that, whatever I specify, the username is not taken into account:

An error has occurred while handling the request. [User 'Anonymous_69a378ed-bb56-4183-ae71-c9ead783db1f' with session id '5fefb6ad-XXXX-XXXX-XXXX-XXXXXXXXb34f' and roles 'Administrator']

答:
I finally found that the proxy setting was the actual problem. It was set at the project scope and simply clicking on No proxy in the General tab did the trick! (both services are hosted on my local machine so far)

I just had to fill in the dedicated Authentication field in the HTTP Headers tab then, with the correct credentials, to eventually log in my Bonita service.


问:
Regex in android for email,username & mobile number
I want to use regex in my android application to validate some field.

User Name :

1 Capital Letter[A-Z], 2 digit[0-9], 1 Special Character any and then followed by small character[a-z] and lenth would be 10 character max.

Email Address :

Must contain @google.com in last

Mobile :

Must be +91 and after that 10 digit.

How can I form my regex pattern for all three fields..?

答:
You can use Patterns class for validating factors such as email,mobile no etc.
Here's how:

```<code>public static boolean isValidEmail(CharSequence target) {
    return (!TextUtils.isEmpty(target) && Patterns.EMAIL_ADDRESS.matcher(target).matches());
}

public static boolean isValidMobile(CharSequence target) {
    return (!TextUtils.isEmpty(target) && Patterns.PHONE.matcher(target).matches());
}
</code>```

Hope it'll help you.

Body:
You can use Patterns class for validating factors such as email,mobile no etc.
Here's how:

public static boolean isValidEmail(CharSequence target) {
    return (!TextUtils.isEmpty(target) && Patterns.EMAIL_ADDRESS.matcher(target).matches());
}

public static boolean isValidMobile(CharSequence target) {
    return (!TextUtils.isEmpty(target) && Patterns.PHONE.matcher(target).matches());
}

Hope it'll help you.


问:
Is it possible to replace app in google play console with different programming language used?
Is it possible to replace the released app(apk) in google play console?
The app is already downloadable in the google play.
However, the released app is a Hybrid App(Web-Based) and
the plan is that the app will be migrated to Flutter.

Thank you in advance.

答: I had a similar issue: wrote an app in Java and then translated it into Kotlin. I just uploaded new apk as an update/new version of the app, and it worked!</p>


问:
Select value from dataframe based on other dataframe
i try to calculate the position of an object based on a timestamp. For this I have two dataframes in pandas. One for the measurement data and one for the position. All the movement is a straightforward acceleration.

Dataframe 1 contains the measurement data:

```<code>        ms        force   ...    ...    ...
1      5           20
2      10          20
3      15          25
4      20          30
5      25          20
..... (~ 6000 lines)
</code>```

Dataframe 2 contains "positioning data"

```<code>        ms        speed (m/s)
1      0           0.66
2      4500        0.66
3      8000        1.3
4      16000       3.0
5      20000       3.0
.....(~300 lines)
</code>```

Now I want to calculate the position of the first dataframe with the data from secound dataframe
In Excel I solved the problem by using an array formular but now I have to use Python/Pandas and I cant find a way how to select the correct row from dataframe 2.

My idea is to make something like this: if

In the end I want to display a graph "force <-> way" and not "force <-> time"

Thank you in andvance

==========================================================================
Update:
In the meantime I could almost solve my issue. Now my Data look like this:

Dataframe 2 (Speed Data):

```<code>        pos       v         a         t      t-end    t-start
0    -3.000    0.666667  0.000000  4.500000   4.500000   0.000000
1     0.000    0.666667  0.187037  0.071287   4.571287   4.500000
2     0.048    0.680000  0.650794  0.010244   4.581531   4.571287
3     0.055    0.686667  0.205432  0.064904   4.646435   4.581531
...
15    0.055    0.686667  0.5       0.064904     23.0     20.0
...
28    0.055    0.686667  0.6       0.064904     35.0     34.0
...
30    0.055    0.686667  0.9       0.064904     44.0     39.0
</code>```

And Dataframe 1 (time based measurement):

```<code>        Fx     Fy     Fz      abs_t               expected output ('a' from DF1)
0      -13.9  170.3   45.0   0.005                            0.000000
1      -14.1  151.6   38.2   0.010                            0.000000
...
200    -14.1  131.4   30.4   20.015                           0.5
...
300    -14.3  111.9   21.1   34.01                            0.6
...
400    -14.5   95.6   13.2   40.025
</code>```

So i want to check the time(abs_t) from DF1 and search for the corract 'a' in DF2
So somthing like this (pseudo code):

```<code>if (DF1['t_abs'] between (DF2['t-start'], DF2['t-end']):
    DF1['a'] = DF2['a']
</code>```

I could make two for loops but it looks like the wrong way and is very very slow.

I hope you understand my problem; to provide a running sample is very hard.
In Excel I did like this:

答:
I found a very slow solution but atleast its working :(</p>

```<code>df1['a'] = 0
for index, row in df2.iterrows():
    start = row['t-start']
    end = row ['t-end']
    a = row ['a']

    df1.loc[(df1['tabs']>start)&(df1['tabs']<end), 'a'] = a
</code>```

Body:
i try to calculate the position of an object based on a timestamp. For this I have two dataframes in pandas. One for the measurement data and one for the position. All the movement is a straightforward acceleration.

Dataframe 1 contains the measurement data:

        ms        force   ...    ...    ...
1      5           20
2      10          20
3      15          25
4      20          30
5      25          20
..... (~ 6000 lines)

Dataframe 2 contains "positioning data"

        ms        speed (m/s)
1      0           0.66
2      4500        0.66
3      8000        1.3
4      16000       3.0
5      20000       3.0
.....(~300 lines)

Now I want to calculate the position of the first dataframe with the data from secound dataframe
In Excel I solved the problem by using an array formular but now I have to use Python/Pandas and I cant find a way how to select the correct row from dataframe 2.

My idea is to make something like this: if

In the end I want to display a graph "force <-> way" and not "force <-> time"

Thank you in andvance

==========================================================================
Update:
In the meantime I could almost solve my issue. Now my Data look like this:

Dataframe 2 (Speed Data):

        pos       v         a         t      t-end    t-start
0    -3.000    0.666667  0.000000  4.500000   4.500000   0.000000
1     0.000    0.666667  0.187037  0.071287   4.571287   4.500000
2     0.048    0.680000  0.650794  0.010244   4.581531   4.571287
3     0.055    0.686667  0.205432  0.064904   4.646435   4.581531
...
15    0.055    0.686667  0.5       0.064904     23.0     20.0
...
28    0.055    0.686667  0.6       0.064904     35.0     34.0
...
30    0.055    0.686667  0.9       0.064904     44.0     39.0

And Dataframe 1 (time based measurement):

        Fx     Fy     Fz      abs_t               expected output ('a' from DF1)
0      -13.9  170.3   45.0   0.005                            0.000000
1      -14.1  151.6   38.2   0.010                            0.000000
...
200    -14.1  131.4   30.4   20.015                           0.5
...
300    -14.3  111.9   21.1   34.01                            0.6
...
400    -14.5   95.6   13.2   40.025

So i want to check the time(abs_t) from DF1 and search for the corract 'a' in DF2
So somthing like this (pseudo code):

if (DF1['t_abs'] between (DF2['t-start'], DF2['t-end']):
    DF1['a'] = DF2['a']

I could make two for loops but it looks like the wrong way and is very very slow.

I hope you understand my problem; to provide a running sample is very hard.
In Excel I did like this:

Body:
I found a very slow solution but atleast its working :(

df1['a'] = 0
for index, row in df2.iterrows():
    start = row['t-start']
    end = row ['t-end']
    a = row ['a']

    df1.loc[(df1['tabs']>start)&(df1['tabs']<end), 'a'] = a


问:
Multiple calls of Application.Run in WPF
I'm trying to run a window, close it, and then run a second window, in a similar way that seems to work with Windows Forms.

```<code>namespace WpfApplication1
{

public partial class App : Application
{
    [STAThread]
    public static void Main()
    {
        Application app = new Application();
        //windowMain.Show();
        app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
        MainWindow windowMain = new MainWindow();
        app.Run(windowMain);
        Window1 window1 = new Window1();
        window1.Show();
        app.Run(window1);
    }
}
}
</code>```

I've set the Build Action in the App.xaml properties from ApplicationDefinition to Page, but the programme throws an exception when window1 is initialised. What am I doing wrong?

Edit: I've modified the xaml in App.xaml as suggested by first answer and edited main as suggested by the comment.

```<code><Application x:Class="WpfApplication1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml"
ShutdownMode="OnExplicitShutdown">
<Application.Resources>
</Application.Resources>
</Application>
</code>```

but I'm still getting the exception.

答:
OK this is what I've divined so far. The Solution Builder looks for a Main() function. Why its not a WinMain() function I'm still not a hundred per cent clear on. If there is no Main(), you get an error. You can have more than one Main() as long as the Project properties: "Application" page/tab: property: "StartUp Object" is set to point to one of the main()s. This is done from an automatically created drop down list.

When a “WPF Application” project is created, Visual Studio(VS) create an xaml file called “App.xaml”.  This is a class declaration where “App” is derived from the “Application” Class. VS also automatically generates hidden files for an xaml file. It creates a “name.g.i.cs” file, when the xaml file is created. It creates a “name.g.cs” file the first time the project is built after the creation of the xaml file. In this case it creates “App.g.cs” and “App.g.i.cs”. These files are hidden by default. To view them, press the “Show all files” button at the top of the Solution Explorer, they can be found in “\ obj\86\Debug” folder.  When you delete an xaml file the “name.g.i.cs” and the “name.g.cs” files remain and are not deleted.

The “App.xaml” file’s “build Action” property is set to “Application Definition” when created by VS. When this property is set to “Application Definition” a Main() function is automatically created in “name.g.i.cs”:

```<code>    [System.STAThreadAttribute()]
    [System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static void Main()
{
    WpfApplication8.App app = new WpfApplication8.App();
    app.InitializeComponent();
    app.Run();
}
</code>```

When this property is set to “Page”, the Main() function is automatically removed by VS. You can create new “Application” derived classes in code or in xaml. I haven’t found a neat way to do it in xaml. There doesn’t seem to be a template for an xaml “Application” derived class. I created a “.cs” code file and then renamed it to an .xaml file. For some reason VS won’t allow you to have more than one xaml “Application” declaration file set to “Application Build”, it doesn’t even give you the option of choosing one in the "Project: Properties: Application": “Startup Object” property.

As you can see in the hidden Main(), an instance of “App” is instantiated and run. If using your own Main() function: an instance of, the base “Application” class, or an “Application” derived class (whether declared in code or in xaml), can be declared and run. The “Application” class should only be instantiated once and should only be run once.  If the “Application” derived class is declared in xaml then a simple application can be run by using the StartUpUri property in the xaml file: StartupUri="Windowname.xaml".  Alternatively the top level UI programme logic can be placed in a Startup event handler.  If  “Startup="Application_Startup" is placed in the “App.xaml”  file then an event handler can be written:

```<code>private void Application_Startup(object sender, StartupEventArgs e)
{
    MainWindow windowMain = new MainWindow();
    windowMain.ShowDialog();
    Window1 window1 = new Window1();
    window1.ShowDialog();
    Shutdown();
}
</code>```

You have to use ShowDialog() here, because it blocks until the window is closed. If you used Show() instead, it would show one window, then immediately show the other one and shutdown the application. In this case there's no need to call the Run() method yourself, that's done automatically.
The “Application” class instance can be run in code whether its declared in code or in xaml. You can then perform initialisation code prior to calling Run(). This would be placed in the Application_ Startup() event handler using the other way. However, if the “Application.Run” call is ever made in the programme, then no windows should be opened (using show() or ShowDialog()) in Main() or anywhere outside of the Application Class or within events and functions called from those events, called during “Application.Run()”.

The Application class has a ShutdownMode property (Application.ShutdownMode). The default for this is: “OnMainWindowClose”. This property can also be set to “OnLastWindowClose” or “OnExplicitShutdown” in code or in the xaml. You will need to reset this if you don't want the programme to close down when the MainWindow is closed.

I think for my purposes it is better not to use the Application class at all and just call the windows using Show() and “ShowDialog()”. This way I can use WPF pages but I could also call Windows Forms, or DirectX screens, as long as they are not open at the same time, or have no UI at all, if the programme is running remotely.  Is there any reason for not doing it this way?

Body:
I'm trying to run a window, close it, and then run a second window, in a similar way that seems to work with Windows Forms.

namespace WpfApplication1
{

public partial class App : Application
{
    [STAThread]
    public static void Main()
    {
        Application app = new Application();
        //windowMain.Show();
        app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
        MainWindow windowMain = new MainWindow();
        app.Run(windowMain);
        Window1 window1 = new Window1();
        window1.Show();
        app.Run(window1);
    }
}
}

I've set the Build Action in the App.xaml properties from ApplicationDefinition to Page, but the programme throws an exception when window1 is initialised. What am I doing wrong?

Edit: I've modified the xaml in App.xaml as suggested by first answer and edited main as suggested by the comment.

<Application x:Class="WpfApplication1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml"
ShutdownMode="OnExplicitShutdown">
<Application.Resources>
</Application.Resources>
</Application>

but I'm still getting the exception.

Body:
OK this is what I've divined so far. The Solution Builder looks for a Main() function. Why its not a WinMain() function I'm still not a hundred per cent clear on. If there is no Main(), you get an error. You can have more than one Main() as long as the Project properties: "Application" page/tab: property: "StartUp Object" is set to point to one of the main()s. This is done from an automatically created drop down list.

When a “WPF Application” project is created, Visual Studio(VS) create an xaml file called “App.xaml”.  This is a class declaration where “App” is derived from the “Application” Class. VS also automatically generates hidden files for an xaml file. It creates a “name.g.i.cs” file, when the xaml file is created. It creates a “name.g.cs” file the first time the project is built after the creation of the xaml file. In this case it creates “App.g.cs” and “App.g.i.cs”. These files are hidden by default. To view them, press the “Show all files” button at the top of the Solution Explorer, they can be found in “\ obj\86\Debug” folder.  When you delete an xaml file the “name.g.i.cs” and the “name.g.cs” files remain and are not deleted.

The “App.xaml” file’s “build Action” property is set to “Application Definition” when created by VS. When this property is set to “Application Definition” a Main() function is automatically created in “name.g.i.cs”:

    [System.STAThreadAttribute()]
    [System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static void Main()
{
    WpfApplication8.App app = new WpfApplication8.App();
    app.InitializeComponent();
    app.Run();
}

When this property is set to “Page”, the Main() function is automatically removed by VS. You can create new “Application” derived classes in code or in xaml. I haven’t found a neat way to do it in xaml. There doesn’t seem to be a template for an xaml “Application” derived class. I created a “.cs” code file and then renamed it to an .xaml file. For some reason VS won’t allow you to have more than one xaml “Application” declaration file set to “Application Build”, it doesn’t even give you the option of choosing one in the "Project: Properties: Application": “Startup Object” property.

As you can see in the hidden Main(), an instance of “App” is instantiated and run. If using your own Main() function: an instance of, the base “Application” class, or an “Application” derived class (whether declared in code or in xaml), can be declared and run. The “Application” class should only be instantiated once and should only be run once.  If the “Application” derived class is declared in xaml then a simple application can be run by using the StartUpUri property in the xaml file: StartupUri="Windowname.xaml".  Alternatively the top level UI programme logic can be placed in a Startup event handler.  If  “Startup="Application_Startup" is placed in the “App.xaml”  file then an event handler can be written:

private void Application_Startup(object sender, StartupEventArgs e)
{
    MainWindow windowMain = new MainWindow();
    windowMain.ShowDialog();
    Window1 window1 = new Window1();
    window1.ShowDialog();
    Shutdown();
}

You have to use ShowDialog() here, because it blocks until the window is closed. If you used Show() instead, it would show one window, then immediately show the other one and shutdown the application. In this case there's no need to call the Run() method yourself, that's done automatically.
The “Application” class instance can be run in code whether its declared in code or in xaml. You can then perform initialisation code prior to calling Run(). This would be placed in the Application_ Startup() event handler using the other way. However, if the “Application.Run” call is ever made in the programme, then no windows should be opened (using show() or ShowDialog()) in Main() or anywhere outside of the Application Class or within events and functions called from those events, called during “Application.Run()”.

The Application class has a ShutdownMode property (Application.ShutdownMode). The default for this is: “OnMainWindowClose”. This property can also be set to “OnLastWindowClose” or “OnExplicitShutdown” in code or in the xaml. You will need to reset this if you don't want the programme to close down when the MainWindow is closed.

I think for my purposes it is better not to use the Application class at all and just call the windows using Show() and “ShowDialog()”. This way I can use WPF pages but I could also call Windows Forms, or DirectX screens, as long as they are not open at the same time, or have no UI at all, if the programme is running remotely.  Is there any reason for not doing it this way?


问:
Axios promise value render always 'undefined'
Inside a componentDiMount function of a child component, I'm using an external function (getResults) to populate a state value. This getResults function, call an external API with axios.

Here is my code:

```<code>  componentDidMount() {
    const cluster = '...';
    const index= '...';
    const field= '...';
    const paragraphs = uuids.map(uuid => {
      // Get the results.
      getResults(cluster, index, field, uuid, 'source')
        .then(results => {
        // Get value with console.log OK.
        console.log(results);
        // Return a undefined value...
        return results;
      })
      .catch(error => {
        console.error(error);
      });
    });
</code>```

After reading many, many posts I see that my problem seems to be the axios delay to generate the results. To resolve my problem, I have tested many solutions without success: check the rendered value in the render section...

How can I resolve this problem? Do I modify an element in the componentDiMount function or directly in the external getResults function ?

Thanks for your help.

答:
Normally, in an axios request, the data comes in results.data

Also, because you don't return anything inside .map, it will just be an array of undefined.

You need to return inside .map

```<code>componentDidMount() {
    const cluster = '...';
    const index= '...';
    const field= '...';
    const paragraphs = uuids.map(uuid => {
      // Get the results.
      // ADDED RETURN INSIDE .map
      return getResults(cluster, index, field, uuid, 'source')
        .then(results => {
        // Get value with console.log OK.
        console.log(results);
        // Return a undefined value...
        return results;
      })
      .catch(error => {
        console.error(error);
      });
  });
</code>```

And if you want to get the data from paragraphs, you need to use Promise.all or async/await for it to work.

Body:
Inside a componentDiMount function of a child component, I'm using an external function (getResults) to populate a state value. This getResults function, call an external API with axios.

Here is my code:

  componentDidMount() {
    const cluster = '...';
    const index= '...';
    const field= '...';
    const paragraphs = uuids.map(uuid => {
      // Get the results.
      getResults(cluster, index, field, uuid, 'source')
        .then(results => {
        // Get value with console.log OK.
        console.log(results);
        // Return a undefined value...
        return results;
      })
      .catch(error => {
        console.error(error);
      });
    });

After reading many, many posts I see that my problem seems to be the axios delay to generate the results. To resolve my problem, I have tested many solutions without success: check the rendered value in the render section...

How can I resolve this problem? Do I modify an element in the componentDiMount function or directly in the external getResults function ?

Thanks for your help.

Body:
Normally, in an axios request, the data comes in results.data

Also, because you don't return anything inside .map, it will just be an array of undefined.

You need to return inside .map

componentDidMount() {
    const cluster = '...';
    const index= '...';
    const field= '...';
    const paragraphs = uuids.map(uuid => {
      // Get the results.
      // ADDED RETURN INSIDE .map
      return getResults(cluster, index, field, uuid, 'source')
        .then(results => {
        // Get value with console.log OK.
        console.log(results);
        // Return a undefined value...
        return results;
      })
      .catch(error => {
        console.error(error);
      });
  });

And if you want to get the data from paragraphs, you need to use Promise.all or async/await for it to work.


问:
Array of objects how do i check for deeply nested text string duplicates & remove from array?
I have an array of objects
Deep inside those objects is a text string
I want to check if other objects in the same array have the same text string / are duplicates.
Then i need a new array with those duplicates removed.

I thought this would be quite simple but it's been testing my intellect for two days now.

```<code>const arr = [
   {..obj 1}
   {..obj 2}
   {..obj 3}
   {
      id: 4,
      uid: 24872-2847-249249892842,
      tags: ['some', 'stuff'],
      type: "blogpage",
      href: "https://link-to-stuff",
      first_publication_date: "2020-02-12T16:05:04+0000",
      last_publication_date: "2020-02-18T21:52:06+0000",
      data: {
            ...some stuff
                  heading: [
                        { type: "heading1", text: "Here Is My Text I Need To Check Duplicates
                   Of"}
                  ]
      }

   }
   {..obj 5}
   {..obj 6}
   {..obj 7}
   {..obj 8}
   {..obj 9}
   {..obj 10}
]

I figured something like:

</code>```

filterOutDuplicates = (blogIndexContent) => {

```<code>let arr = blogIndexContent.pages;

let results = [];

arr.map(each => {
  if (!results || !results.length) {
    results.push(each);
  } else {
    for (let i = 0; i < results.length; i++) {
      const headline = results[i].data.heading[0].text;
      if (headline === each.data.heading[0].text) {
        return;
      } else {
        return results.push(each);
      }
    }
  }
})

console.log('Results :', results); // <-- this just gives me the same 9 blog stories again, no duplicates removed.
</code>```

}

```<code>
What am i doing wrong guys?
</code>```

答:
Slight changes to your code

1) remove using map, have loop over array.

2) Build the uniq object with keys. (Here headline is what we want)

3) Add to results array only when key is not in uniq

```<code>let arr = blogIndexContent.pages;

let results = [];

const uniq = {};

for (let i = 0; i < arr.length; i++) {
  const headline = arr[i].data.heading[0].text;
  if (!(headline in uniq)) {
    results.push(each);
    uniq[each] = 1;
  }
}

console.log("Results :", results);
</code>```

Body:
I have an array of objects
Deep inside those objects is a text string
I want to check if other objects in the same array have the same text string / are duplicates.
Then i need a new array with those duplicates removed.

I thought this would be quite simple but it's been testing my intellect for two days now.

const arr = [
   {..obj 1}
   {..obj 2}
   {..obj 3}
   {
      id: 4,
      uid: 24872-2847-249249892842,
      tags: ['some', 'stuff'],
      type: "blogpage",
      href: "https://link-to-stuff",
      first_publication_date: "2020-02-12T16:05:04+0000",
      last_publication_date: "2020-02-18T21:52:06+0000",
      data: {
            ...some stuff
                  heading: [
                        { type: "heading1", text: "Here Is My Text I Need To Check Duplicates
                   Of"}
                  ]
      }

   }
   {..obj 5}
   {..obj 6}
   {..obj 7}
   {..obj 8}
   {..obj 9}
   {..obj 10}
]

I figured something like:

filterOutDuplicates = (blogIndexContent) => {

let arr = blogIndexContent.pages;

let results = [];

arr.map(each => {
  if (!results || !results.length) {
    results.push(each);
  } else {
    for (let i = 0; i < results.length; i++) {
      const headline = results[i].data.heading[0].text;
      if (headline === each.data.heading[0].text) {
        return;
      } else {
        return results.push(each);
      }
    }
  }
})

console.log('Results :', results); // <-- this just gives me the same 9 blog stories again, no duplicates removed.

}

What am i doing wrong guys?

Body:
Slight changes to your code

1) remove using map, have loop over array.

2) Build the uniq object with keys. (Here headline is what we want)

3) Add to results array only when key is not in uniq

let arr = blogIndexContent.pages;

let results = [];

const uniq = {};

for (let i = 0; i < arr.length; i++) {
  const headline = arr[i].data.heading[0].text;
  if (!(headline in uniq)) {
    results.push(each);
    uniq[each] = 1;
  }
}

console.log("Results :", results);


问:
How to load an DLL based on the Version?
I am using an external library whose DLL versions are from v2014 to v2020.
Issue is i am currently linking v2020  DLL in my application. if i load any lower version file it will show an warning message and it will upgrade that to new version format, but the conversion time is more if the size of that file big.

I know which version of file i am importing based on it i need to load that particular version DLL.

i need an approach to achieve this. i have seen some examples on boost interprocess communication , #loadLibrary approach.

答: You do that naming library direct with version or versioning your code inside library.</p>


问:
Cant connect to superset using athena database
I am new to superset.
Going to Sources > Databases for a new connection to my athena.

I have downloaded JDBC driver and writing following connection line:

awsathena+jdbc://AKIAJ2PKWTZYAPBYKRMQ:xxxxxxxxxxxxxxx@athena.us-east-1.amazonaws.com:443/default?s3_staging_dir='s3://aws-athena-query-results-831083831535-us-east-1/' as SQLAlchemy URI. First parameter being access key and 2nd being secret key(Modified a bit for privacy)

I am getting the error:

ERROR: {"error": "Connection failed!\n\nThe error message returned was:\nCan't load plugin: sqlalchemy.dialects:awsathena.jdbc"}

I really wish to explore the open source visualisation using superset on my databases.

答:
In my case problem was with the special characters in the aws_secret_key and s3_staging_dir. I solved it by putting the output of quote_plus methods into the URI. No quotes were required.

```<code>from urllib.parse import quote_plus
secretkey = quote_plus(aws_secret_access_key)
loc = quote_plus(s3_staging_dir)
</code>```

Further, make sure the schema_name (i.e. database name) already exists in the s3 path. Hope it helps!

Body:
In my case problem was with the special characters in the aws_secret_key and s3_staging_dir. I solved it by putting the output of quote_plus methods into the URI. No quotes were required.

from urllib.parse import quote_plus
secretkey = quote_plus(aws_secret_access_key)
loc = quote_plus(s3_staging_dir)

Further, make sure the schema_name (i.e. database name) already exists in the s3 path. Hope it helps!


问:
The POST Method Is Not Supported For This Route. Supported methods: GET, HEAD In laravel 5.8
I'm saving my data to the user table in laravel using ajax. I create API and it's run in the post it gives a success message. But when I'm trying to save data using Ajax it gives this message

"The POST method is not supported for this route. Supported methods: GET, HEAD."

My Controller Code is

```<code>public function register(Request $request)
{
    $validator = Validator::make($request->all(), [
        'name' => 'required',
        'email' => 'required|email',
        'password' => 'required',
        'phone' => 'required',
        'country' => 'required',
        'state' => 'required',
        'purpose' => 'required',
        'package' => 'required',
        'months' => 'required',
        'quantity' => 'required',
        'amount' => 'required',
        'user_status' => 'required',
    ]);
    if ($validator->fails()) {
        return response()->json(['error'=>$validator->errors()], 401);
    }
    $input = $request->all();
    $input['password'] = bcrypt($input['password']);
    $user = User::create($input);
    $success['token'] =  $user->createToken('MyApp')-> accessToken;
    $success['name'] =  $user->name;
    return response()->json(['success'=>$success], $this-> successStatus);
}
</code>```

My route is

```<code>Route::post('register', 'API\UserController@register');
</code>```

Blade file code is

```<code><form id="frmAddTask" action="#" method="post" enctype="multipart/form-data" action="javascript:void(0)">
         @csrf
        <h2>Order Information</h2>
            <div class="row">

                <div class="col-md-3">

                    <div class="form-group">
                        <label class="control-label required" for="package">Package</label>
                        <select id="package" name="package" class="form-control">
                            <option value="basic" selected="selected">Basic</option>
                            <option value="regular">Regular</option>
                            <option value="infinite">Infinite</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label class="control-label required" for="months">Months</label>
                        <select id="months" name="months" class="form-control">
                            <option value="1" selected="">1 months</option>
                            <option value="4">4 months</option>
                            <option value="12">12 months</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label class="control-label required" for="quantity">Quantity</label>
                        <select id="quantity" name="quantity" class="form-control">
                            <option value="1" selected="selected">1</option>
                            <option value="2">2</option><option value="3">3</option>
                            <option value="4">4</option><option value="5">5</option>
                            <option value="6">6</option><option value="7">7</option>
                            <option value="8">8</option><option value="9">9</option>
                            <option value="10">10</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-3 ">
                    <label class="control-label required" for="amount">Amount</label>
                    <div class="input-group">
                        <span class="input-group-addon">INR</span>
                        <select id="amount" name="amount" class="form-control">
                            <option value="1" selected="">2500</option>
                            <option value="4">4000</option>
                            <option value="12">7000</option>
                        </select>
                    </div>
                </div>
                </div>
            </div>
         <hr>
         <h2>Billing Information</h2>
         <div class="row">
          <div class="col-md-6 form-group">
            <label for="name">Name:</label>
            <input type="text" class="form-control" name="name" id="name">
          </div>
          <div class="col-md-6 form-group">
            <label for="email">Email:</label>
            <input type="text" class="form-control" name="email" id="email">
          </div>
          <div class="col-md-6 form-group">
            <label for="confirm">Confirm Email:</label>
            <input type="text" class="form-control" name="confirm" id="confirm">
          </div>
          <div class="col-md-6 form-group">
            <label for="phone">Phone:</label>
            <input type="text" class="form-control" name="phone" id="phone">
          </div>
          <div class="col-md-6 form-group">
            <label for="country">Country:</label>
            <input type="text" class="form-control" name="country" id="country">
          </div>
          <div class="col-md-6 form-group">
            <label for="state">State:</label>
            <input type="text" class="form-control" name="state" id="state">
          </div>
          <div class="col-md-6 form-group">
            <label for="phone">Address:</label>
            <textarea class="form-control"></textarea>
          </div>
          <div class="col-md-6 form-group">
            <label for="purpose">Purpose</label>
            <select id="purpose" name="purpose" value="" class="form-control ">
            <option>Select Purpose</option>
            <option value="parent">Parent</option>
            <option value="employmee">Employmee</option>
            </select>
          </div>
          <div class="col-md-12 form-group">
            <input id="btn-add" type="submit" value="Make Payment" class="btn-success">
          </div>
          <!--button type="submit" class="btn btn-default">Submit</button--->
         </div>
        </form>
</code>```

My ajax request is

```<code><script>
  $(document).ready(function(){
  $('#btn-add').click(function(e){
  e.preventDefault();

  $.ajaxSetup({
  headers: {

      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
  }
 });
 $('#btn-add').html('Sending..');
 /* Submit form data using ajax*/
 $.ajax({
  url: "http://localhost:8000/api/register",
  method: 'post',
  data: $('#frmAddTask').serialize(),
  success: function(response){
      $('#exampleModalCenter').modal('hide')
  }});
 });
});
</script>
</code>```

Please suggest me where I'm wrong and try to help me to solve my issue.

Thanks in advance

答:
You can try this code in ajax</p>

```<code>url:"{{url('/register')}},
</code>```

Body:
I'm saving my data to the user table in laravel using ajax. I create API and it's run in the post it gives a success message. But when I'm trying to save data using Ajax it gives this message

"The POST method is not supported for this route. Supported methods: GET, HEAD."

My Controller Code is

public function register(Request $request)
{
    $validator = Validator::make($request->all(), [
        'name' => 'required',
        'email' => 'required|email',
        'password' => 'required',
        'phone' => 'required',
        'country' => 'required',
        'state' => 'required',
        'purpose' => 'required',
        'package' => 'required',
        'months' => 'required',
        'quantity' => 'required',
        'amount' => 'required',
        'user_status' => 'required',
    ]);
    if ($validator->fails()) {
        return response()->json(['error'=>$validator->errors()], 401);
    }
    $input = $request->all();
    $input['password'] = bcrypt($input['password']);
    $user = User::create($input);
    $success['token'] =  $user->createToken('MyApp')-> accessToken;
    $success['name'] =  $user->name;
    return response()->json(['success'=>$success], $this-> successStatus);
}

My route is

Route::post('register', 'API\UserController@register');

Blade file code is

<form id="frmAddTask" action="#" method="post" enctype="multipart/form-data" action="javascript:void(0)">
         @csrf

Order Information

                        Package
                        <select id="package" name="package" class="form-control">
                            <option value="basic" selected="selected">Basic</option>
                            <option value="regular">Regular</option>
                            <option value="infinite">Infinite</option>
                        </select>

                        Months
                        <select id="months" name="months" class="form-control">
                            <option value="1" selected="">1 months</option>
                            <option value="4">4 months</option>
                            <option value="12">12 months</option>
                        </select>

                        Quantity
                        <select id="quantity" name="quantity" class="form-control">
                            <option value="1" selected="selected">1</option>
                            <option value="2">2</option><option value="3">3</option>
                            <option value="4">4</option><option value="5">5</option>
                            <option value="6">6</option><option value="7">7</option>
                            <option value="8">8</option><option value="9">9</option>
                            <option value="10">10</option>
                        </select>

                    Amount

                        INR
                        <select id="amount" name="amount" class="form-control">
                            <option value="1" selected="">2500</option>
                            <option value="4">4000</option>
                            <option value="12">7000</option>
                        </select>

Billing Information

            Name:
            <input type="text" class="form-control" name="name" id="name">

            Email:
            <input type="text" class="form-control" name="email" id="email">

            Confirm Email:
            <input type="text" class="form-control" name="confirm" id="confirm">

            Phone:
            <input type="text" class="form-control" name="phone" id="phone">

            Country:
            <input type="text" class="form-control" name="country" id="country">

            State:
            <input type="text" class="form-control" name="state" id="state">

            Address:
            <textarea class="form-control"></textarea>

            Purpose
            <select id="purpose" name="purpose" value="" class="form-control ">
            <option>Select Purpose</option>
            <option value="parent">Parent</option>
            <option value="employmee">Employmee</option>
            </select>

            <input id="btn-add" type="submit" value="Make Payment" class="btn-success">

        </form>

My ajax request is

Please suggest me where I'm wrong and try to help me to solve my issue.

Thanks in advance

Body:
You can try this code in ajax

url:"{{url('/register')}},


问:
Spring boot:connection oracle database
i'am using spring boot with oracle V11.2.0.4.0 database to develop a microservice,
But my pringBootApplication failed to run due to this following error:

```<code>2020-02-18 15:24:12.943  INFO 16476 --- [           main] com.zaxxer.hikari.HikariDataSource       :
HikariPool-1 - Starting...
2020-02-18 15:24:13.041  INFO 16476 --- [           main] com.zaxxer.hikari.pool.PoolBase          :
HikariPool-1 - Driver does not support get/set network timeout for connections.
(oracle.jdbc.driver.T4CConnection.getNetworkTimeout()I)
2020-02-18 15:24:13.045  INFO 16476 --- [           main] com.zaxxer.hikari.HikariDataSource       :
HikariPool-1 - Start completed.
2020-02-18 15:24:13.058  INFO 16476 --- [           main] org.hibernate.dialect.Dialect            :
HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
2020-02-18 15:24:13.205 **ERROR** 16476 --- [           main] o.h.e.j.e.internal.JdbcEnvironmentImpl   :
Could not fetch the SequenceInformation from the database
2020-02-18 15:24:13.662  WARN 16476 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   :
SQL Error: 17026, SQLState: 99999
2020-02-18 15:24:13.662 ERROR 16476 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   :
Numeric Overflow
2020-02-18 15:24:13.668  WARN 16476 --- [           main] ConfigServletWebServerApplicationContext :
Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'entityManagerFactory' defined in class path resource
[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init
method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default]
Unable to build Hibernate SessionFactory; nested exception is
org.hibernate.exception.GenericJDBCException: Unable to build DatabaseInformation
2020-02-18 15:24:13.668  INFO 16476 --- [           main] com.zaxxer.hikari.HikariDataSource       :

Error starting ApplicationContext. To display the conditions report re-run your application with
'debug' enabled.
2020-02-18 15:24:13.702 ERROR 16476 --- [           main] o.s.boot.SpringApplication               :
Application run failed

java.sql.SQLException: Numeric Overflow
at oracle.jdbc.driver.NumberCommonAccessor.throwOverflow(NumberCommonAccessor.java:4170) ~[ojdbc6-
11.2.0.4.0.jar:12.1.0.1.0]
</code>```

Here is my pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-
     4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.4.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>ibbl.lu</groupId>
<artifactId>microservice_lims</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>microservice_lims</name>
<description>Demo project for Spring Boot</description>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- ojdbc6.jar example -->
    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>11.2.0.4.0</version>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

here is my application.properties

```<code>spring.jpa.hibernate.ddl-auto=update
spring.datasource.url= jdbc:oracle:thin:@Oracle-dev.xxx.xx.xx:1521:LBVT
spring.datasource.username=xxxx
spring.datasource.password=xxx!
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.jpa.show-sql=true
</code>```

Someone have an idea about this issue ?
I already download the ojdbc6.jar and use maven command to install the driver
any clue will be helpful

答:
The problem is due to MAX_VALUE to large in All_sequence,
That's why i had this error

```<code>java.sql.SQLException: Numeric Overflow
</code>```

I fixed this issue as follows:
I created a Custom class which extends Oracle10gDialect and redefined MIN_VALUE, MAX_VALUE in ALL_SEQUENCES,
Here is my class

```<code>package ibbl.lu.microservice_lims.config;

import org.hibernate.dialect.Oracle10gDialect;

public class CustomOracleDialect extends Oracle10gDialect {

    @Override
    public String getQuerySequencesString() {
        return "SELECT SEQUENCE_OWNER, SEQUENCE_NAME,
                greatest(MIN_VALUE,-9223372036854775807) MIN_VALUE,\n" +
                "Least(MAX_VALUE, 9223372036854775808) MAX_VALUE,
                INCREMENT_BY,CYCLE_FLAG, ORDER_FLAG, CACHE_SIZE,\n" +
                "Least(greatest(LAST_NUMBER, -9223372036854775807),
                9223372036854775808) LAST_NUMBER from ALL_SEQUENCES";
    }
}
</code>```

In the application.properties file referred to a dialect implementation

```<code>spring.jpa.properties.hibernate.dialect=ibbl.lu.microservice_lims.config.CustomOracleDialect
</code>```

Title: Spring boot:connection oracle database

Body:
i'am using spring boot with oracle V11.2.0.4.0 database to develop a microservice,
But my pringBootApplication failed to run due to this following error:

2020-02-18 15:24:12.943  INFO 16476 --- [           main] com.zaxxer.hikari.HikariDataSource       :
HikariPool-1 - Starting...
2020-02-18 15:24:13.041  INFO 16476 --- [           main] com.zaxxer.hikari.pool.PoolBase          :
HikariPool-1 - Driver does not support get/set network timeout for connections.
(oracle.jdbc.driver.T4CConnection.getNetworkTimeout()I)
2020-02-18 15:24:13.045  INFO 16476 --- [           main] com.zaxxer.hikari.HikariDataSource       :
HikariPool-1 - Start completed.
2020-02-18 15:24:13.058  INFO 16476 --- [           main] org.hibernate.dialect.Dialect            :
HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
2020-02-18 15:24:13.205 **ERROR** 16476 --- [           main] o.h.e.j.e.internal.JdbcEnvironmentImpl   :
Could not fetch the SequenceInformation from the database
2020-02-18 15:24:13.662  WARN 16476 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   :
SQL Error: 17026, SQLState: 99999
2020-02-18 15:24:13.662 ERROR 16476 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   :
Numeric Overflow
2020-02-18 15:24:13.668  WARN 16476 --- [           main] ConfigServletWebServerApplicationContext :
Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'entityManagerFactory' defined in class path resource
[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init
method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default]
Unable to build Hibernate SessionFactory; nested exception is
org.hibernate.exception.GenericJDBCException: Unable to build DatabaseInformation
2020-02-18 15:24:13.668  INFO 16476 --- [           main] com.zaxxer.hikari.HikariDataSource       :

Error starting ApplicationContext. To display the conditions report re-run your application with
'debug' enabled.
2020-02-18 15:24:13.702 ERROR 16476 --- [           main] o.s.boot.SpringApplication               :
Application run failed

java.sql.SQLException: Numeric Overflow
at oracle.jdbc.driver.NumberCommonAccessor.throwOverflow(NumberCommonAccessor.java:4170) ~[ojdbc6-
11.2.0.4.0.jar:12.1.0.1.0]

Here is my pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-
     4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.4.RELEASE</version>
    <relativePath/>
</parent>
<groupId>ibbl.lu</groupId>
<artifactId>microservice_lims</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>microservice_lims</name>
<description>Demo project for Spring Boot</description>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>11.2.0.4.0</version>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

here is my application.properties

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url= jdbc:oracle:thin:@Oracle-dev.xxx.xx.xx:1521:LBVT
spring.datasource.username=xxxx
spring.datasource.password=xxx!
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.jpa.show-sql=true

Someone have an idea about this issue ?
I already download the ojdbc6.jar and use maven command to install the driver
any clue will be helpful

Body:
The problem is due to MAX_VALUE to large in All_sequence,
That's why i had this error

java.sql.SQLException: Numeric Overflow

I fixed this issue as follows:
I created a Custom class which extends Oracle10gDialect and redefined MIN_VALUE, MAX_VALUE in ALL_SEQUENCES,
Here is my class

package ibbl.lu.microservice_lims.config;

import org.hibernate.dialect.Oracle10gDialect;

public class CustomOracleDialect extends Oracle10gDialect {

    @Override
    public String getQuerySequencesString() {
        return "SELECT SEQUENCE_OWNER, SEQUENCE_NAME,
                greatest(MIN_VALUE,-9223372036854775807) MIN_VALUE,\n" +
                "Least(MAX_VALUE, 9223372036854775808) MAX_VALUE,
                INCREMENT_BY,CYCLE_FLAG, ORDER_FLAG, CACHE_SIZE,\n" +
                "Least(greatest(LAST_NUMBER, -9223372036854775807),
                9223372036854775808) LAST_NUMBER from ALL_SEQUENCES";
    }
}

In the application.properties file referred to a dialect implementation

spring.jpa.properties.hibernate.dialect=ibbl.lu.microservice_lims.config.CustomOracleDialect


问:
Iterate through template parameter
I have a function that receives a template parameter.

```<code>template<class Container>
void function(const Container& object)
{
     //here i want to iterate through object and print them
}

int main()
{
     function(std::vector<int>{1,3,6,7});
     function(std::vector<std::vector<int>>{{1,2,3},{2,5,7}});
}
</code>```

Is it possible to do this in one function? Suppose the container argument will be integer.

答:
This should work for your case. Note that I'm using a trait as implemented here in this amazing solution by @Jarod42 https://stackoverflow.com/a/29634934/8192043.</p>

```<code>template<template<typename ...> typename C, typename D, typename ... Others>
void function(const C<D, Others...> &object)
{
    if constexpr(is_iterable<D>::value)
    {
       for(const auto& v : object)
       {
           for (const auto& w : v)
           {...}
       }
    }
    else
    {
       for (const auto& w : object)
       {...}
    }
}
</code>```

Title: Iterate through template parameter

Body:
I have a function that receives a template parameter.

template<class Container>
void function(const Container& object)
{
     //here i want to iterate through object and print them
}

int main()
{
     function(std::vector<int>{1,3,6,7});
     function(std::vector<std::vector<int>>{{1,2,3},{2,5,7}});
}

Is it possible to do this in one function? Suppose the container argument will be integer.

Body:
This should work for your case. Note that I'm using a trait as implemented here in this amazing solution by @Jarod42 https://stackoverflow.com/a/29634934/8192043.

template<template<typename ...> typename C, typename D, typename ... Others>
void function(const C<D, Others...> &object)
{
    if constexpr(is_iterable<D>::value)
    {
       for(const auto& v : object)
       {
           for (const auto& w : v)
           {...}
       }
    }
    else
    {
       for (const auto& w : object)
       {...}
    }
}


问:
Parsing Push Notification Data in swift
I am getting push notification and they are getting displayed on iPhone very nicely. But for some reason I want to parse the following result that I am receiving in didReceivedRemoteNotification method for push notification.

```<code> func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    print("FFTF", "didReceiveRemoteNotification", userInfo)
  }
</code>```

Following is what I get when I print the userInfo

```<code>    [AnyHashable("FcmNotificationStatus"): 3, AnyHashable("ListItemIds"): ["42D890C4-0804-4434-B137-0EECDEFEC319"], AnyHashable("UserId"): 15, AnyHashable("gcm.message_id"): 1582109***6, AnyHashable("Title"): MY App, AnyHashable("body"): Welcome., AnyHashable("aps"): {
    "content-available" = 1;
}, AnyHashable("google.c.sender.id"): 589****85]
</code>```

This is response I am getting and from it I want to get the following fields that have specific types

content-available  (Int)

FcmNotificationStatus  (Int)

ListItemIds  (String Array)

UserId   (Int)

And I tried many things but I am getting my application crash. Is there anything that I can do to parse it easily? Please let me know how to do it.

答:
What you have there is a dictionary. Parsing should be fairly straight forward.

```<code>let status = userInfo["FcmNotificationStatus"] as? Int
let ids = userInfo["ListItemIds"] as? [Int]
let title = userInfo["Title"] as? String
let body = userInfo["body"] as? String
</code>```

I cannot give a more detailed answer as to why you are getting these errors without you showing your code and explaining what errors your getting

This guide explains some of the concepts. An excert...

```<code>@available(iOS 10, *)

extension AppDelegate : UNUserNotificationCenterDelegate {

  // Receive displayed notifications for iOS 10 devices.
  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification,
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)

    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
      print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([])
  }

  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse,
                              withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
      print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    completionHandler()
  }
}
</code>```

You will not always receive notifications in didReceiveRemoteNotification, you should use the delegate methods mentioned in the linked article.

Title: Parsing Push Notification Data in swift

Body:
I am getting push notification and they are getting displayed on iPhone very nicely. But for some reason I want to parse the following result that I am receiving in didReceivedRemoteNotification method for push notification.

 func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    print("FFTF", "didReceiveRemoteNotification", userInfo)
  }

Following is what I get when I print the userInfo

    [AnyHashable("FcmNotificationStatus"): 3, AnyHashable("ListItemIds"): ["42D890C4-0804-4434-B137-0EECDEFEC319"], AnyHashable("UserId"): 15, AnyHashable("gcm.message_id"): 1582109***6, AnyHashable("Title"): MY App, AnyHashable("body"): Welcome., AnyHashable("aps"): {
    "content-available" = 1;
}, AnyHashable("google.c.sender.id"): 589****85]

This is response I am getting and from it I want to get the following fields that have specific types

content-available  (Int)

FcmNotificationStatus  (Int)

ListItemIds  (String Array)

UserId   (Int)

And I tried many things but I am getting my application crash. Is there anything that I can do to parse it easily? Please let me know how to do it.

Body:
What you have there is a dictionary. Parsing should be fairly straight forward.

let status = userInfo["FcmNotificationStatus"] as? Int
let ids = userInfo["ListItemIds"] as? [Int]
let title = userInfo["Title"] as? String
let body = userInfo["body"] as? String

I cannot give a more detailed answer as to why you are getting these errors without you showing your code and explaining what errors your getting

This guide explains some of the concepts. An excert...

@available(iOS 10, *)

extension AppDelegate : UNUserNotificationCenterDelegate {

  // Receive displayed notifications for iOS 10 devices.
  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification,
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)

    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
      print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([])
  }

  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse,
                              withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
      print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    completionHandler()
  }
}

You will not always receive notifications in didReceiveRemoteNotification, you should use the delegate methods mentioned in the linked article.