问:
Render list of Element from an Object in React
I need to render dynamically key-values pair from an object. For example:

```<code>export default class App extends Component {
  state = {
    num: {
      cheese: 1,
      meat: 2,
      salad: 3,
    }
  }

  render() {
    const numLIst = Object.keys(this.state.num).map(key => {
      return [...Array(this.state.num[key])].map(() => {
        return <SmallComp content={key}/>
      } )
    })
</code>```

So I want to render cheese 1 times, meat 2 times, and salad 3 times. The above code is from the instructor from the course and I have no idea what it is doing from

```<code>return [...Array(this.state.num[key])].map(() => {
        return <SmallComp content={key}/>
      } )
</code>```

The code works, but is there a more elegant way to do this ?

答:
You can loop over the Object.keys alone...

There is no eleganter way, there are just other ways...

```<code>  render() {
      const numList = Object.keys(this.state.num).map((name, index) => {
             return (new Array(index + )).map((_, subindex) => <SmallComp content={`${key}_${subindex}`}/>)
      });

      ....
    })
</code>```

Object.keys(this.state.num) // Get the array ['cheese', 'meat', 'salad'];

(new Array(index + )) // Create an array of (index + 1) length

So you loop over an array with n elements to render...

Body:
I need to render dynamically key-values pair from an object. For example:

export default class App extends Component {
  state = {
    num: {
      cheese: 1,
      meat: 2,
      salad: 3,
    }
  }

  render() {
    const numLIst = Object.keys(this.state.num).map(key => {
      return [...Array(this.state.num[key])].map(() => {
        return <SmallComp content={key}/>
      } )
    })

So I want to render cheese 1 times, meat 2 times, and salad 3 times. The above code is from the instructor from the course and I have no idea what it is doing from

return [...Array(this.state.num[key])].map(() => {
        return <SmallComp content={key}/>
      } )

The code works, but is there a more elegant way to do this ?

Body:
You can loop over the Object.keys alone...

There is no eleganter way, there are just other ways...

  render() {
      const numList = Object.keys(this.state.num).map((name, index) => {
             return (new Array(index + )).map((_, subindex) => <SmallComp content={`${key}_${subindex}`}/>)
      });

      ....
    })

Object.keys(this.state.num) // Get the array ['cheese', 'meat', 'salad'];

(new Array(index + )) // Create an array of (index + 1) length

So you loop over an array with n elements to render...


来源: stackexchange

问:
Is C# a high level language?
Is C# a high level language? I see it as more like medium level, but I am still unsure about this. Would you consider it as high level as some of the popular scripting languages?

Or does it accommodate more than one level?

答: "A programming language is low level when its programs require attention to the irrelevant." --Alan Perlis</p>

OwnerDisplayName: Joan Venge

ContentLicense: CC BY-SA 2.5

Title: Is C# a high level language?

OwnerDisplayName: Ken


问:
Include GLib into CLion (Windows, Msys2)
I am trying to include GLib2 in my CLion C project on Windows. I have installed glib2.0 via pacman on Msys2. The include (#include <glib-2.0/glib.h>) get's recognized by CLion.

My problem is that the include's in the glib.h are not getting recognized.

Error:

```<code>C:/msys64/mingw64/include/glib-2.0/glib.h:30:10: fatal error: glib/galloca.h: No such file or directory
   30 | #include <glib/galloca.h>
      |          ^~~~~~~~~~~~~~~~
compilation terminated.
</code>```

But these 2 files exist on the filesystem:

```<code>glib-2.0/glib.h
glib-2.0/glib/galloca.h
</code>```

CMakeLists.txt

```<code>cmake_minimum_required(VERSION 3.16)
project(task_2 C)

set(CMAKE_C_STANDARD 99)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/bin)

include_directories(BEFORE "C:/msys64/mingw64/include/glib-2.0" "C:/msys64/mingw64/lib/glib-2.0/include")

add_executable(main src/main.c)
target_link_libraries(main ws2_32)
</code>```

答:
The best way to get the compiler and linker flags for glib2 is via pkg-config, which is also available in MSYS2.
Please see: How do I make clion work with following make and pkg-config?</p>

ContentLicense: CC BY-SA 4.0

Body:
I am trying to include GLib2 in my CLion C project on Windows. I have installed glib2.0 via pacman on Msys2. The include (#include <glib-2.0/glib.h>) get's recognized by CLion.

My problem is that the include's in the glib.h are not getting recognized.

Error:

C:/msys64/mingw64/include/glib-2.0/glib.h:30:10: fatal error: glib/galloca.h: No such file or directory
   30 | #include <glib/galloca.h>
      |          ^~~~~~~~~~~~~~~~
compilation terminated.

But these 2 files exist on the filesystem:

glib-2.0/glib.h
glib-2.0/glib/galloca.h

CMakeLists.txt

cmake_minimum_required(VERSION 3.16)
project(task_2 C)

set(CMAKE_C_STANDARD 99)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/bin)

include_directories(BEFORE "C:/msys64/mingw64/include/glib-2.0" "C:/msys64/mingw64/lib/glib-2.0/include")

add_executable(main src/main.c)
target_link_libraries(main ws2_32)


问:
Could not find an implementation of the query pattern for source tpe "Task<List<Stocks>> StockList" select not found
I tried to improve my desktop application by Adding Async/Await querying a database here is my code

```<code>public async Task<List<Stocks>> StockListAsync()
    {
        List<Stocks> stocks = new List<Stocks>();
        {
            conn = await App_Code.DbConnection.InitializeConnectionAsync();
            string cnt = "SELECT * FROM tblStock";
            cmd = new SqlCommand(cnt, conn);
            rd = cmd.ExecuteReader();
            if (rd.HasRows == true)
            {
                while (await rd.ReadAsync())
                {
                    var rm = new Stocks
                    {
                        ID = Convert.ToInt32(rd["ID"]),
                        Supplier = Convert.ToInt32(rd["Supplier"]),
                        StockCode = rd["StockCode"].ToString(),
                        StockName = rd["StockName"].ToString(),
                        Description = rd["Description"].ToString(),
                        UnitMeasure = rd["Measurement"].ToString(),
                        Quantity = Convert.ToInt32(rd["Quantity"]),
                        OrderQty = Convert.ToInt32(rd["OrderQty"]),
                        Cost = Convert.ToDouble(rd["Cost"]),
                    };
                    stocks.Add(rm);
                }
            }
            return stocks;
        }

        //}
    }
</code>```

This code above is a separate class called Stocks then I the windows form I want to display the result I have created an instance of the stock class like this * readonly Stocks stock = new Stocks();* and I also have a method GetStock below is the code

```<code> void GetStocks()
    {
        var list = stock.StockListAsync();
            var result = from g in list
                         select g;
            GrdFood.Rows.Clear();
            foreach (var item in result)
            {
                GrdFood.Rows.Add(GrdFood.RowCount + 1, item.Supplier, item.StockName,
                    item.Description, item.Quantity.ToString("N2"), item.OrderQty.ToString("N2"),
                    Convert.ToDouble(item.Cost).ToString("N2"), item.ID);

            }
    }
</code>```

Then on the FormLoad event I called GetStocks The problem is that the List in the code below  is reporting an error Could not find an implementation of the query pattern for source type Task> StockList select not found

```<code> var list = stock.StockListAsync();
            var result = from g in list
                         select g;
</code>```

Everything was working fine before I made it Async Task, please how do I correct this implementation thanks.

答:
Change the method to async and await the call stock.StockListAsync.
Something like this

```<code>async void GetStocks()
{
    var list = await stock.StockListAsync();
        var result = from g in list
                     select g;
        GrdFood.Rows.Clear();
        foreach (var item in result)
        {
            GrdFood.Rows.Add(GrdFood.RowCount + 1, item.Supplier, item.StockName,
                item.Description, item.Quantity.ToString("N2"), item.OrderQty.ToString("N2"),
                Convert.ToDouble(item.Cost).ToString("N2"), item.ID);

        }
}
</code>```

StockListAsync() is returning Task<List<Stocks>> not List<Stocks> to apply query hence the error.

Body:
I tried to improve my desktop application by Adding Async/Await querying a database here is my code

public async Task<List<Stocks>> StockListAsync()
    {
        List<Stocks> stocks = new List<Stocks>();
        {
            conn = await App_Code.DbConnection.InitializeConnectionAsync();
            string cnt = "SELECT * FROM tblStock";
            cmd = new SqlCommand(cnt, conn);
            rd = cmd.ExecuteReader();
            if (rd.HasRows == true)
            {
                while (await rd.ReadAsync())
                {
                    var rm = new Stocks
                    {
                        ID = Convert.ToInt32(rd["ID"]),
                        Supplier = Convert.ToInt32(rd["Supplier"]),
                        StockCode = rd["StockCode"].ToString(),
                        StockName = rd["StockName"].ToString(),
                        Description = rd["Description"].ToString(),
                        UnitMeasure = rd["Measurement"].ToString(),
                        Quantity = Convert.ToInt32(rd["Quantity"]),
                        OrderQty = Convert.ToInt32(rd["OrderQty"]),
                        Cost = Convert.ToDouble(rd["Cost"]),
                    };
                    stocks.Add(rm);
                }
            }
            return stocks;
        }

        //}
    }

This code above is a separate class called Stocks then I the windows form I want to display the result I have created an instance of the stock class like this * readonly Stocks stock = new Stocks();* and I also have a method GetStock below is the code

 void GetStocks()
    {
        var list = stock.StockListAsync();
            var result = from g in list
                         select g;
            GrdFood.Rows.Clear();
            foreach (var item in result)
            {
                GrdFood.Rows.Add(GrdFood.RowCount + 1, item.Supplier, item.StockName,
                    item.Description, item.Quantity.ToString("N2"), item.OrderQty.ToString("N2"),
                    Convert.ToDouble(item.Cost).ToString("N2"), item.ID);

            }
    }

Then on the FormLoad event I called GetStocks The problem is that the List in the code below  is reporting an error Could not find an implementation of the query pattern for source type Task> StockList select not found

 var list = stock.StockListAsync();
            var result = from g in list
                         select g;

Everything was working fine before I made it Async Task, please how do I correct this implementation thanks.

Body:
Change the method to async and await the call stock.StockListAsync.
Something like this

async void GetStocks()
{
    var list = await stock.StockListAsync();
        var result = from g in list
                     select g;
        GrdFood.Rows.Clear();
        foreach (var item in result)
        {
            GrdFood.Rows.Add(GrdFood.RowCount + 1, item.Supplier, item.StockName,
                item.Description, item.Quantity.ToString("N2"), item.OrderQty.ToString("N2"),
                Convert.ToDouble(item.Cost).ToString("N2"), item.ID);

        }
}

StockListAsync() is returning Task<List<Stocks>> not List<Stocks> to apply query hence the error.


问:
Strategies for deleting a logged-in user in ASP.NET Core Identity
In my ASP.NET Core MVC application, an administrator may wish to delete a regular user from their organisation. This of course is trivial using the built-in Identity model, using the UserManager<T>.DeleteAsync() method.

However, the user may be logged in on multiple devices at the time. I don't need real-time messaging - I'm happy for the deleted user to be returned to the login page upon their next request. SignalR feels like an overkill for this situation.

Request.User.Identity.IsAuthenticated remains true during their session, even though their account has been deleted from the backing store.

My thought process is to override OnActionExecutingAsync() on the base controller and check for a valid record in the backing store upon each request and then take appropriate action (e.g. signout + redirect to login), but this feels like a significant overhead to perform on each request, especially since the backing store is CosmosDb and this will cost extra Request Units.

I also need to consider AJAX requests as significant pages within the MVC application have dynamic elements and the user might stay on a single page for a long time.

What's the most effective, lightweight way to check if their user account has been deleted upon next request?

答:
You are right, checking upon each request is inefficient. Since you mentioned that an administrator wants to be able to delete manually, a couple of seconds delay between deleting and forcing a logout won't be a problem (it's the same as deleting a couple of seconds later).

Upon defining that you are using .NET Core Identity, you can simply define SecurityStampValidatorOptions, such as

```<code>services.Configure<SecurityStampValidatorOptions>(options =>
{
    options.ValidationInterval = TimeSpan.FromMinutes(1);
});
</code>```

This results in the user token being validated every minute. If you set the ValidationInterval to .FromMinutes(0), the token is being validated upon each request (I think it's like 3 database call for verifying). My suggestion would be not to take 0 as a value, but rather a value that you think is acceptable for the timespan between a user being deleted manually and him being forced out of the application.

Body:
You are right, checking upon each request is inefficient. Since you mentioned that an administrator wants to be able to delete manually, a couple of seconds delay between deleting and forcing a logout won't be a problem (it's the same as deleting a couple of seconds later).

Upon defining that you are using .NET Core Identity, you can simply define SecurityStampValidatorOptions, such as

services.Configure<SecurityStampValidatorOptions>(options =>
{
    options.ValidationInterval = TimeSpan.FromMinutes(1);
});

This results in the user token being validated every minute. If you set the ValidationInterval to .FromMinutes(0), the token is being validated upon each request (I think it's like 3 database call for verifying). My suggestion would be not to take 0 as a value, but rather a value that you think is acceptable for the timespan between a user being deleted manually and him being forced out of the application.


问:
What rotation should I apply to my hamburger?
I'm trying to animate a simple two-line span which transforms into an 'X' shape when you click on it - but can't for the life of me work out what rotation I should do to align them properly. They just aren't rotating/translating to be a perfect 'X' shape.

// Variables

let line1 = document.getElementById("line-1");
let line2 = document.getElementById("line-2");
let hamburger = document.getElementById("hamburger-container");

// Function

function active() {
  line1.classList.toggle("active");
  line2.classList.toggle("active");
}

// Event Listener

hamburger.addEventListener("click", active);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.header-section {
  height: 100px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  background-color: #999;
}

#hamburger-container {
  height: 30px;
  width: 40px;
  margin-right: 10%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  flex-direction: column;
  cursor: pointer;
}

.hamburger-line {
  height: 5px;
  width: 30px;
  background-color: #fff;
  transition: all .5s ease-in-out;
  cursor: pointer;
}

#line-1.active {
  transform: translate(10px, 10px) rotate(-45deg);
}

#line-2.active {
  transform: translate(10px, -10px) rotate(45deg)
}</code>```

  ```

If anybody can explain how they'd work it out too, that'd be great. I can't find the right resource out there for it.

答:
Use space-between instead of space-around and reduce the height to 20px. Now the space bettwen the bars is exactly 10px and each bar is 5px height so you have to move by 7.5px (10px/2 + 5px/2) vertically:

// Variables

let line1 = document.getElementById("line-1");
let line2 = document.getElementById("line-2");
let hamburger = document.getElementById("hamburger-container");

// Function

function active() {
  line1.classList.toggle("active");
  line2.classList.toggle("active");
}

// Event Listener

hamburger.addEventListener("click", active);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.header-section {
  height: 100px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  background-color: #999;
}

#hamburger-container {
  height: 20px;
  width: 40px;
  margin-right: 10%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-direction: column;
  cursor: pointer;
}

.hamburger-line {
  height: 5px;
  width: 30px;
  background-color: #fff;
  transition: all .5s ease-in-out;
  cursor: pointer;
}

#line-1.active {
  transform: translateY(7.5px) rotate(-45deg);
}

#line-2.active {
  transform: translateY(-7.5px) rotate(45deg)
}</code>```

```

Body:
I'm trying to animate a simple two-line span which transforms into an 'X' shape when you click on it - but can't for the life of me work out what rotation I should do to align them properly. They just aren't rotating/translating to be a perfect 'X' shape.

// Variables

let line1 = document.getElementById("line-1");
let line2 = document.getElementById("line-2");
let hamburger = document.getElementById("hamburger-container");

// Function

function active() {
  line1.classList.toggle("active");
  line2.classList.toggle("active");
}

// Event Listener

hamburger.addEventListener("click", active);

body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.header-section {
  height: 100px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  background-color: #999;
}

#hamburger-container {
  height: 30px;
  width: 40px;
  margin-right: 10%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  flex-direction: column;
  cursor: pointer;
}

.hamburger-line {
  height: 5px;
  width: 30px;
  background-color: #fff;
  transition: all .5s ease-in-out;
  cursor: pointer;
}

#line-1.active {
  transform: translate(10px, 10px) rotate(-45deg);
}

#line-2.active {
  transform: translate(10px, -10px) rotate(45deg)
}

If anybody can explain how they'd work it out too, that'd be great. I can't find the right resource out there for it.

Body:
Use space-between instead of space-around and reduce the height to 20px. Now the space bettwen the bars is exactly 10px and each bar is 5px height so you have to move by 7.5px (10px/2 + 5px/2) vertically:

// Variables

let line1 = document.getElementById("line-1");
let line2 = document.getElementById("line-2");
let hamburger = document.getElementById("hamburger-container");

// Function

function active() {
  line1.classList.toggle("active");
  line2.classList.toggle("active");
}

// Event Listener

hamburger.addEventListener("click", active);

body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.header-section {
  height: 100px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  background-color: #999;
}

#hamburger-container {
  height: 20px;
  width: 40px;
  margin-right: 10%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-direction: column;
  cursor: pointer;
}

.hamburger-line {
  height: 5px;
  width: 30px;
  background-color: #fff;
  transition: all .5s ease-in-out;
  cursor: pointer;
}

#line-1.active {
  transform: translateY(7.5px) rotate(-45deg);
}

#line-2.active {
  transform: translateY(-7.5px) rotate(45deg)
}

<header class="header-section">
  <div id="hamburger-container">
    <span id="line-1" class="hamburger-line"></span>
    <span id="line-2" class="hamburger-line"></span>
  </div>
</header>


问:
How to serve ES6 modules on Safari?
I have a question regarding the usage of ES6 modules within Safari. It's driving me crazy because it prevents me from sharing my website with Safari users.

My web application and the coming up MWE work perfectly fine in the following environments:

Windows: Chrome, Edge and Firefox both via a Windows local server (WAMP) and via my web server;

Mobile: Chrome, Firefox (both in Android and iOS). Even Samsung Mobile and Opera for Android work fine.

MacOS:

on Safari, Chrome and Firefox via a Mac local server (AMPPS);

on Chrome and Firefox via my web server.

However, my web application does not work within MacOS Safari via my web server (at the moment I'm trying this code on Safari 13.0.4, but all modern versions of the mentioned browsers behave the same way with respect to this problem). Similarly, it does not work within the latest version of iOS Safari.

MWE

./test_class.js

export class TestClass {
  constructor() {
    console.log("Created a test class");
  }
}
```

<p><em>./index.html</em></p>

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>

<script type="module">
  console.log("Starting the main script.");

  // The following line seems to cause an error in Safari only
  import { TestClass } from './test_class.js';

  // The rest is not executed due to the error
  let test_class = new TestClass;
  console.log("Done.");
</script>
</code>```

Console Output

When I load index.html from my server, Safari's console gives me the error

TypeError: 'text/html' is not a valid JavaScript MIME type.

Additional info (not sure if it's relevant)

When I go to the resource section of Safari, there is indeed an entry for test_class.js that does not contain the code above but instead:

```

This only occurs when I connect to my server. Does the line location.href="http://www.my_super_website.com/test_class.js?i=1"; make sense? My understanding is that at this point Safari tries to load test_class.js but has some issue with it.

What I've tried so far

If I remove the line import { TestClass } from './test_class.js';, everything works fine.

The same problem occurs if I place the import call within a new script file that is then used in the html document.

I verified that my way of naming the file ./test_class.js is correct, but since this works in most browsers I guess it's fine.

I'm using a free-hosting solution, infinityfree.net, so maybe there's something going on there?

答:
In web development we develop using ES6 and ES7 but those are not supported yet in all browsers.

In order to ship the working code in most browsers (Safari - Chrome - IE9 )

and does not matter the browser. You supposed to use a build process like ( webpack - gulp - grant ) or using existing libraries like ( React, Angular and VUE )

Example: For starting using webpack
https://webpack.js.org/guides/getting-started/

witch will grant you get a complete working code by converting all your code into ES5 and bundle that code to ensure reducing chuck sizes

Title: How to serve ES6 modules on Safari?

Body:
I have a question regarding the usage of ES6 modules within Safari. It's driving me crazy because it prevents me from sharing my website with Safari users.

My web application and the coming up MWE work perfectly fine in the following environments:

Windows: Chrome, Edge and Firefox both via a Windows local server (WAMP) and via my web server;

Mobile: Chrome, Firefox (both in Android and iOS). Even Samsung Mobile and Opera for Android work fine.

MacOS:

on Safari, Chrome and Firefox via a Mac local server (AMPPS);

on Chrome and Firefox via my web server.

However, my web application does not work within MacOS Safari via my web server (at the moment I'm trying this code on Safari 13.0.4, but all modern versions of the mentioned browsers behave the same way with respect to this problem). Similarly, it does not work within the latest version of iOS Safari.

MWE

./test_class.js

export class TestClass {
  constructor() {
    console.log("Created a test class");
  }
}

./index.html

<!DOCTYPE html>

Console Output

When I load index.html from my server, Safari's console gives me the error

TypeError: 'text/html' is not a valid JavaScript MIME type.

Additional info (not sure if it's relevant)

When I go to the resource section of Safari, there is indeed an entry for test_class.js that does not contain the code above but instead:

This only occurs when I connect to my server. Does the line location.href="http://www.my_super_website.com/test_class.js?i=1"; make sense? My understanding is that at this point Safari tries to load test_class.js but has some issue with it.

What I've tried so far

If I remove the line import { TestClass } from './test_class.js';, everything works fine.

The same problem occurs if I place the import call within a new script file that is then used in the html document.

I verified that my way of naming the file ./test_class.js is correct, but since this works in most browsers I guess it's fine.

I'm using a free-hosting solution, infinityfree.net, so maybe there's something going on there?


问:
Choosing flash/openGL/other animation for an android app?
I need to add some animation to the UI of my application. Something similar to the Talking Tom application that is all the rage these days. I am a complete noob to animation, so had the following questions to zero in on a particular platform before I began with any development.

Out of Flash/Rendered Images/OpenGL which one would be the fastest to implement (assuming that I have a graphics designer to do the drawing)?

If I was to go with flash, would I still be able to interact with the application or will it be more of a one-way play-and-stop kind of animation?

I have looked over a lot of questions on SO about this issue and have not been able to make up my mind. Any help is most welcome.

答:
Talking Tom is a 3D animation. You will not be able to get that to work on a mobile device with flash. Adobe has an update pending - Air 2.7 - that promises great performance improvements and support for Open GL ES. That might to the trick when that comes along. ANd designers are comfortable with the adobe toolset.

However, if you don't feel like waiting, you will need to look elsewhere.
REndered images - know in technical circles as video - will make you app very large, slow to download, and not very interactive.

So you are left with openGL. That should work for you. There are a number of solutions that use open GL. A popular choice for games and animation is UNity3D which has great support on android and iPhone. ANd the toolset is very designer friendly.

ContentLicense: CC BY-SA 3.0


问:
python-flask db.session.commit() is not working
The problem is when user tries 'forgot password' option. It creates new reset_key for verification, but the new key is not getting updated into DB.

```<code>@app.route('/login/forgot/', methods=['GET', 'POST'])
def forgot():
   form = ResetLoginForm(request.form)
   #There's no session yet. User just pointing to /login/forgot url.

   if request.method == 'POST' and form.validate():
      user = User.query.filter_by(email=form.email.data).first()

   if not user:
     flash('The username or email incorrect')
     return render_template('forgot.html', form=form)

   reset_key = generate_key() ## this creates a new key, but how update  this key into db?
   #tried something like
   user.reset_key = reset_key
   db.session.add(user)
   db.session.commit()
   #this is not working. Is it due to session is not started or something?
</code>```

Thanks for any help or hint.

答: user = db.session.query(User).first() solved problem.

Body:
The problem is when user tries 'forgot password' option. It creates new reset_key for verification, but the new key is not getting updated into DB.

@app.route('/login/forgot/', methods=['GET', 'POST'])
def forgot():
   form = ResetLoginForm(request.form)
   #There's no session yet. User just pointing to /login/forgot url.

   if request.method == 'POST' and form.validate():
      user = User.query.filter_by(email=form.email.data).first()

   if not user:
     flash('The username or email incorrect')
     return render_template('forgot.html', form=form)

   reset_key = generate_key() ## this creates a new key, but how update  this key into db?
   #tried something like
   user.reset_key = reset_key
   db.session.add(user)
   db.session.commit()
   #this is not working. Is it due to session is not started or something?

Thanks for any help or hint.


问:
How to exclude dependencies from maven assembly plugin : jar-with-dependencies?
Maven's assembly plugin enables the creation of a big jar including all dependencies with descriptorRef jar-with-dependencies.

How can one exclude some of these dependencies? It seems like it does not have such a configuration? Is there another solution?

答:
This example indicates one way to do this:

```<code> <dependencySets>
    <dependencySet>
      ....
      <excludes>
        <exclude>commons-lang:commons-lang</exclude>
        <exclude>log4j:log4j</exclude>
      </excludes>
    </dependencySet>
    ....
  </dependencySets>
</code>```

Essentially we would use the excludes option available in dependencySet.

See also: https://maven.apache.org/plugins/maven-assembly-plugin/assembly-component.html

Body:
This example indicates one way to do this:

 <dependencySets>
    <dependencySet>
      ....
      <excludes>
        <exclude>commons-lang:commons-lang</exclude>
        <exclude>log4j:log4j</exclude>
      </excludes>
    </dependencySet>
    ....
  </dependencySets>

Essentially we would use the excludes option available in dependencySet.

See also: https://maven.apache.org/plugins/maven-assembly-plugin/assembly-component.html


问:
Lua: I get error when I try to run a script in Windows
I'm trying to run a Lua script from Windows but I only get errors. I've put my script inside the same folder of the Lua shell but if I write the same line of my Lua book % lua name.lua I get stdin:1: unexpected symbol near '%'
If i remove the % i get stdin:1: syntax error near 'prova'. I've found another thread here on stackoverflow. I've tried what the answer said but it doesn't work.

答:
There's two different problems here:

As was mentioned in the comments, % is meant to represent the prompt, so you shouldn't actually type it.

You're supposed to run lua name.lua from the command prompt, not from the Lua REPL.


问:
Extract IP Addresses from JSON file using VB.net
is there a way to extract only IPv4 from a file in JSON language using VB.net

For example I would like that when I open a JSON file from VB I can filter only IPv4 from this text for example: https://pastebin.com/raw/S7Vnnxqa

& i expect the results like this https://pastebin.com/raw/8L8Ckrwi i founded this website that he offer a tool to do that https://www.toolsvoid.com/extract-ip-addresses/ i put the link here to understand more what i mean but i don't want to use an external tool i want it to be converted from VB directly thanks for your help in advance.

答:
Your "text" is JSON. Load it using the JSON parser of your choice (google VB.NET parse JSON), loop over the matches array and read the IP address from the http.host property of each element.

Here is an example how to do it using the Newtonsoft.Json package (see it working here on DotNetFiddle):

' Assume that the variable myJsonString contains the original string

Dim myJObject = JObject.Parse(myJsonString)
For Each match In myJObject("matches")
    Console.WriteLine(match("http")("host"))
Next
```

<p>Output:</p>

```62.176.84.198
197.214.169.59
46.234.76.75
122.136.141.67
219.73.94.83
2402:800:621b:33f1:d1e3:5544:4fcf:526e
178.136.75.125
188.167.212.252
...
```

<p>If you want to extract only IPv4 and not IPv6, you can use a regular expression to check whether it matches:</p>

<pre class="lang-vb prettyprint-override"><code>Dim IPV4Regex = New Regex("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")

Dim ip = match("http")("host")
If IPV4Regex.Match(ip).Success Then
  Console.WriteLine(ip)
End If
</code>```

```<code>62.176.84.198
197.214.169.59
46.234.76.75
122.136.141.67
219.73.94.83
178.136.75.125
188.167.212.252
...
</code>```

Of course it's always recommended to parse the input data in a structured way, to avoid surprises such as false positives. But if you just want to match anything that looks like an IP address, regardless of the input format (even if you just put hello1.2.3.4world in the textbox), then you could use just the regular expression and skip the structured approach (see it working here on DotNetFiddle):

Dim IPV4RegexWithWordBoundary = New Regex("\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b")

Dim match = IPV4RegexWithWordBoundary.Match(myJsonString)
Do While match.Success
    Console.WriteLine(match.Value)
    match = match.NextMatch()
Loop
```

<p>Here I modified the regular expression to use <code>\b...\b</code> instead of <code>^...$</code> so that it matches word boundaries instead of start/end of string. Note however that now we get IP addresses <em>twice</em> with the input that you provided, because the addresses exist more than once:</p>

```62.176.84.198
62.176.84.198
197.214.169.59
197.214.169.59
46.234.76.75
46.234.76.75
...
```

Body:
Your "text" is JSON. Load it using the JSON parser of your choice (google VB.NET parse JSON), loop over the matches array and read the IP address from the http.host property of each element.

Here is an example how to do it using the Newtonsoft.Json package (see it working here on DotNetFiddle):

' Assume that the variable myJsonString contains the original string

Dim myJObject = JObject.Parse(myJsonString)
For Each match In myJObject("matches")
    Console.WriteLine(match("http")("host"))
Next

Output:

62.176.84.198
197.214.169.59
46.234.76.75
122.136.141.67
219.73.94.83
2402:800:621b:33f1:d1e3:5544:4fcf:526e
178.136.75.125
188.167.212.252
...

If you want to extract only IPv4 and not IPv6, you can use a regular expression to check whether it matches:

Dim IPV4Regex = New Regex("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")

Dim ip = match("http")("host")
If IPV4Regex.Match(ip).Success Then
  Console.WriteLine(ip)
End If

62.176.84.198
197.214.169.59
46.234.76.75
122.136.141.67
219.73.94.83
178.136.75.125
188.167.212.252
...

Of course it's always recommended to parse the input data in a structured way, to avoid surprises such as false positives. But if you just want to match anything that looks like an IP address, regardless of the input format (even if you just put hello1.2.3.4world in the textbox), then you could use just the regular expression and skip the structured approach (see it working here on DotNetFiddle):

Dim IPV4RegexWithWordBoundary = New Regex("\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b")

Dim match = IPV4RegexWithWordBoundary.Match(myJsonString)
Do While match.Success
    Console.WriteLine(match.Value)
    match = match.NextMatch()
Loop

Here I modified the regular expression to use \b...\b instead of ^...$ so that it matches word boundaries instead of start/end of string. Note however that now we get IP addresses twice with the input that you provided, because the addresses exist more than once:

62.176.84.198
62.176.84.198
197.214.169.59
197.214.169.59
46.234.76.75
46.234.76.75
...


问:
Need help understanding the gradient function in pytorch
The following code

```<code>
w = np.array([[2., 2.],[2., 2.]])
x = np.array([[3., 3.],[3., 3.]])
b = np.array([[4., 4.],[4., 4.]])
w = torch.tensor(w, requires_grad=True)
x = torch.tensor(x, requires_grad=True)
b = torch.tensor(b, requires_grad=True)

y = w*x + b
print(y)
# tensor([[10., 10.],
#         [10., 10.]], dtype=torch.float64, grad_fn=<AddBackward0>)

y.backward(torch.FloatTensor([[1, 1],[ 1, 1]]))

print(w.grad)
# tensor([[3., 3.],
#         [3., 3.]], dtype=torch.float64)

print(x.grad)
# tensor([[2., 2.],
#         [2., 2.]], dtype=torch.float64)

print(b.grad)
# tensor([[1., 1.],
#         [1., 1.]], dtype=torch.float64)

</code>```

As the tensor argument inside gradient function is an all ones tensor in the shape of the input tensor, my understanding says that

w.grad means derivative of y w.r.t w, and produces b,

x.grad means derivative of y w.r.t x, and produces b and

b.grad means derivative of y w.r.t b, and produces all ones.

Out of these, only point 3 answer is matching my expected result. Can someone help me in understanding the first two answers. I think I understand the accumulation part, but don't think that is happening here.

答:
To find the correct derivatives in this example, we need to take the sum and product rule into consideration.

Sum rule:

Product rule:

That means the derivatives of your equation are calculated as follows.

With respect to x:

With respect to w:

With respect to b:

The gradients reflect exactly that:

torch.equal(w.grad, x) # => True

torch.equal(x.grad, w) # => True

torch.equal(b.grad, torch.tensor([[1, 1], [1, 1]], dtype=torch.float64)) # => True
```

Body:
The following code

w = np.array([[2., 2.],[2., 2.]])
x = np.array([[3., 3.],[3., 3.]])
b = np.array([[4., 4.],[4., 4.]])
w = torch.tensor(w, requires_grad=True)
x = torch.tensor(x, requires_grad=True)
b = torch.tensor(b, requires_grad=True)

y = w*x + b
print(y)
# tensor([[10., 10.],
#         [10., 10.]], dtype=torch.float64, grad_fn=<AddBackward0>)

y.backward(torch.FloatTensor([[1, 1],[ 1, 1]]))

print(w.grad)
# tensor([[3., 3.],
#         [3., 3.]], dtype=torch.float64)

print(x.grad)
# tensor([[2., 2.],
#         [2., 2.]], dtype=torch.float64)

print(b.grad)
# tensor([[1., 1.],
#         [1., 1.]], dtype=torch.float64)

As the tensor argument inside gradient function is an all ones tensor in the shape of the input tensor, my understanding says that

w.grad means derivative of y w.r.t w, and produces b,

x.grad means derivative of y w.r.t x, and produces b and

b.grad means derivative of y w.r.t b, and produces all ones.

Out of these, only point 3 answer is matching my expected result. Can someone help me in understanding the first two answers. I think I understand the accumulation part, but don't think that is happening here.


问:
Why my YouTube video downloader only downloads some videos and for other videos it shows keyerror like URL and cipher?
I am trying to make a YouTube video downloader using Python pytube3 but it doesn't download all the videos. Some videos download very easily but some videos won't download and instead of download it shows error:</p>

```<code>Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\extract.py", line 297, in apply_descrambler
    for format_item in formats
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\extract.py", line 297, in <listcomp>
    for format_item in formats
KeyError: 'url'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\tarun\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:/Users/tarun/PycharmProjects/YTDownloader/YTD.py", line 15, in video_download
    my_video = YouTube(input_user)
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\__main__.py", line 92, in __init__
    self.descramble()
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\__main__.py", line 132, in descramble
    apply_descrambler(self.player_config_args, fmt)
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\extract.py", line 301, in apply_descrambler
    parse_qs(formats[i]["cipher"]) for i, data in enumerate(formats)
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\extract.py", line 301, in <listcomp>
    parse_qs(formats[i]["cipher"]) for i, data in enumerate(formats)
KeyError: 'cipher'
</code>```

答:
This is a problem with pytube3, I believe as of now they have not submitted a fix yet.
Here is the link to the issue on github</p>

Body:
I am trying to make a YouTube video downloader using Python pytube3 but it doesn't download all the videos. Some videos download very easily but some videos won't download and instead of download it shows error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\extract.py", line 297, in apply_descrambler
    for format_item in formats
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\extract.py", line 297, in <listcomp>
    for format_item in formats
KeyError: 'url'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\tarun\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:/Users/tarun/PycharmProjects/YTDownloader/YTD.py", line 15, in video_download
    my_video = YouTube(input_user)
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\__main__.py", line 92, in __init__
    self.descramble()
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\__main__.py", line 132, in descramble
    apply_descrambler(self.player_config_args, fmt)
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\extract.py", line 301, in apply_descrambler
    parse_qs(formats[i]["cipher"]) for i, data in enumerate(formats)
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\extract.py", line 301, in <listcomp>
    parse_qs(formats[i]["cipher"]) for i, data in enumerate(formats)
KeyError: 'cipher'


问:
OpenGL program doesn't show a triangle
I am following a tutorial on OpenGL in C++ and for some reason the exact same code doesn't work for me.
It is supposed to display a triangle, but it doesn't show anything.Just a blank screen.
Here is the code:

```<code>#include<iostream>

#define GLEW_STATIC
#include"GL/glew.h"

#include"GLFW/glfw3.h"

static unsigned int compileShader(unsigned int type, const std::string& shader)
{
    unsigned int id = glCreateShader(type);
    const char* src = shader.c_str();
    glShaderSource(id, 1, &src, NULL);
    glCompileShader(id);

    int result;
    glGetShaderiv(id, GL_COMPILE_STATUS, &result);
    if (!result) {
        char log[512];
        glGetShaderInfoLog(id, 512, NULL, log);
        std::cout << "Compiling shader error:\n" << log << std::endl;
    }

    return id;
}

static unsigned int createShader(const std::string& vertexShader, const std::string& fragmentShader)
{
    unsigned int program = glCreateProgram();
    unsigned int vs = compileShader(GL_VERTEX_SHADER, vertexShader);
    unsigned int fs = compileShader(GL_FRAGMENT_SHADER, fragmentShader);

    glAttachShader(program, vs);
    glAttachShader(program, fs);
    glLinkProgram(program);

    int result;
    glGetProgramiv(program, GL_LINK_STATUS, &result);
    if (!result) {
        char log[512];
        glGetProgramInfoLog(program, 512, NULL, log);
        std::cout << "linking shader error:\n" << log << std::endl;
    }

    glValidateProgram(program);

    glDeleteShader(vs);
    glDeleteShader(fs);

    return program;
}

void keyCallBack(GLFWwindow* window, int key, int scancode, int action, int mode)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);
}

int main()
{
    int width = 0, height = 0;

    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(500, 500, "Test", nullptr, nullptr);

    glfwMakeContextCurrent(window);

    glewExperimental = GL_TRUE;
    glewInit();
    glfwGetFramebufferSize(window, &width, &height);
    glViewport(0, 0, width, height);

    glfwSetKeyCallback(window, keyCallBack);

    float triangle[] = {
        -0.5f, -0.5f,
         0.0f,  0.5f,
         0.5f, -0.5f
    };

    GLuint buffer = 0;
    glGenBuffers(1, &buffer);
    glBindBuffer(GL_ARRAY_BUFFER, buffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(triangle), triangle, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);
    glEnableVertexAttribArray(0);

    std::string vertexShader = "#version 330 core\n"
    "layout (location = 0) in vec4 position;\n"
    "void main()\n"
    "{\n"
    "gl_Position = position;\n"
    "}\n";

    std::string fragmentShader = "#version 330 core\n"
    "out vec4 color;\n"
    "void main()\n"
    "{\n"
    "color = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
    "}\n";

    unsigned int program = createShader(vertexShader, fragmentShader);
    glUseProgram(program);

    while(!glfwWindowShouldClose(window)) {

        glfwPollEvents();

        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        glDrawArrays(GL_TRIANGLES, 0, 3);

        glfwSwapBuffers(window);
    }

    glfwTerminate();
    return 0;
}
</code>```

I really don't understand why it is not working.The triangle's positions look correct.glVertexAttribPointer also looks correct.I can't find any errors in the compiling and linking of the shaders and their sources..
I also get zero errors when compiling and linking them..

答:
The issue is caused by GLFW_OPENGL_CORE_PROFILE. If you use a core profile OpenGL Context, then you have to use a named Vertex Array Object, because the default VAO (0) is not valid.

Either use a compatibility profile:

glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);
```

<p>or create a VAO before specifying the array of vertex attribute data: </p>

<pre class="lang-cpp prettyprint-override"><code>GLuint VAO;
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);

glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);
glEnableVertexAttribArray(0);
</code>```

Title: OpenGL program doesn't show a triangle

Body:
I am following a tutorial on OpenGL in C++ and for some reason the exact same code doesn't work for me.
It is supposed to display a triangle, but it doesn't show anything.Just a blank screen.
Here is the code:

#include<iostream>

#define GLEW_STATIC
#include"GL/glew.h"

#include"GLFW/glfw3.h"

static unsigned int compileShader(unsigned int type, const std::string& shader)
{
    unsigned int id = glCreateShader(type);
    const char* src = shader.c_str();
    glShaderSource(id, 1, &src, NULL);
    glCompileShader(id);

    int result;
    glGetShaderiv(id, GL_COMPILE_STATUS, &result);
    if (!result) {
        char log[512];
        glGetShaderInfoLog(id, 512, NULL, log);
        std::cout << "Compiling shader error:\n" << log << std::endl;
    }

    return id;
}

static unsigned int createShader(const std::string& vertexShader, const std::string& fragmentShader)
{
    unsigned int program = glCreateProgram();
    unsigned int vs = compileShader(GL_VERTEX_SHADER, vertexShader);
    unsigned int fs = compileShader(GL_FRAGMENT_SHADER, fragmentShader);

    glAttachShader(program, vs);
    glAttachShader(program, fs);
    glLinkProgram(program);

    int result;
    glGetProgramiv(program, GL_LINK_STATUS, &result);
    if (!result) {
        char log[512];
        glGetProgramInfoLog(program, 512, NULL, log);
        std::cout << "linking shader error:\n" << log << std::endl;
    }

    glValidateProgram(program);

    glDeleteShader(vs);
    glDeleteShader(fs);

    return program;
}

void keyCallBack(GLFWwindow* window, int key, int scancode, int action, int mode)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);
}

int main()
{
    int width = 0, height = 0;

    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(500, 500, "Test", nullptr, nullptr);

    glfwMakeContextCurrent(window);

    glewExperimental = GL_TRUE;
    glewInit();
    glfwGetFramebufferSize(window, &width, &height);
    glViewport(0, 0, width, height);

    glfwSetKeyCallback(window, keyCallBack);

    float triangle[] = {
        -0.5f, -0.5f,
         0.0f,  0.5f,
         0.5f, -0.5f
    };

    GLuint buffer = 0;
    glGenBuffers(1, &buffer);
    glBindBuffer(GL_ARRAY_BUFFER, buffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(triangle), triangle, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);
    glEnableVertexAttribArray(0);

    std::string vertexShader = "#version 330 core\n"
    "layout (location = 0) in vec4 position;\n"
    "void main()\n"
    "{\n"
    "gl_Position = position;\n"
    "}\n";

    std::string fragmentShader = "#version 330 core\n"
    "out vec4 color;\n"
    "void main()\n"
    "{\n"
    "color = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
    "}\n";

    unsigned int program = createShader(vertexShader, fragmentShader);
    glUseProgram(program);

    while(!glfwWindowShouldClose(window)) {

        glfwPollEvents();

        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        glDrawArrays(GL_TRIANGLES, 0, 3);

        glfwSwapBuffers(window);
    }

    glfwTerminate();
    return 0;
}

I really don't understand why it is not working.The triangle's positions look correct.glVertexAttribPointer also looks correct.I can't find any errors in the compiling and linking of the shaders and their sources..
I also get zero errors when compiling and linking them..

Body:
The issue is caused by GLFW_OPENGL_CORE_PROFILE. If you use a core profile OpenGL Context, then you have to use a named Vertex Array Object, because the default VAO (0) is not valid.

Either use a compatibility profile:

glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);

or create a VAO before specifying the array of vertex attribute data:

GLuint VAO;
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);

glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);
glEnableVertexAttribArray(0);


问:
How to get the text value from an element based on its sibling attribute value?
Example xml:

```<code><root>
    <ns1:agent ns2:about="a3">
        <ns2:name xml:lang="en">Helen</ns2:name>
        <ns2:age>26</ns2:age>
    </ns1:agent>
    <ns1:agent ns2:about="a1">
        <ns2:name xml:lang="en">John</ns2:name>
        <ns2:age>26</ns2:age>
    </ns1:agent>
    <ns1:agent ns2:about="a2">
        <ns2:name xml:lang="en">Mike</ns2:name>
        <ns2:age>30</ns2:age>
    </ns1:agent>
    ...
    <!-- More ns1:agent nodes -->
    ...
    <ns3:person ns2:id="a1"/>
    <ns3:person ns2:id="a2"/>
    <ns3:person ns2:id="a3"/>
    ...
    <!-- More ns3:person nodes -->
    ...
</root>
</code>```

So how to get the text value of the agent/name element based on its about attribute starting from person element, using XPath?

Edit:
XPath expression will be used in a loop, for each ns3:person node, so I don't know the specific id attribute value beforehand.

答:
Assuming you've properly declared namespace prefixes ns1, ns2, and ns3, this XPath,

```<code>//ns3:person[@ns2:id = "a1"]/preceding-sibling::ns1:agent[1]/ns2:name
</code>```

will select the name of the agent immediately preceding the identified person.

If you need help declaring the XML namespace prefixes, see How does XPath deal with XML namespaces?

Update based on OP's comment:

In my original xml document, the agent node is not immediately preceding the person node. I will be running the expression in a loop, for each person node. Sorry for the confusion, I have edited the example and the question so it is more clear what I need.

And in the edited question:

Edit: XPath expression will be used in a loop, for each ns3:person node, so I don't know the specific id attribute value beforehand.

So in your loop simply bind a variable, say $id, to the current ns3:person/@n2:id and then test it in the XPath:

```<code>//ns1:agent[@ns2:about = $id]/ns2:name
</code>```

See also How to pass variable parameter into XPath expression?

Body:
Example xml:

<root>
    <ns1:agent ns2:about="a3">
        <ns2:name xml:lang="en">Helen</ns2:name>
        <ns2:age>26</ns2:age>
    </ns1:agent>
    <ns1:agent ns2:about="a1">
        <ns2:name xml:lang="en">John</ns2:name>
        <ns2:age>26</ns2:age>
    </ns1:agent>
    <ns1:agent ns2:about="a2">
        <ns2:name xml:lang="en">Mike</ns2:name>
        <ns2:age>30</ns2:age>
    </ns1:agent>
    ...

    ...
    <ns3:person ns2:id="a1"/>
    <ns3:person ns2:id="a2"/>
    <ns3:person ns2:id="a3"/>
    ...

    ...
</root>

So how to get the text value of the agent/name element based on its about attribute starting from person element, using XPath?

Edit:
XPath expression will be used in a loop, for each ns3:person node, so I don't know the specific id attribute value beforehand.

Body:
Assuming you've properly declared namespace prefixes ns1, ns2, and ns3, this XPath,

//ns3:person[@ns2:id = "a1"]/preceding-sibling::ns1:agent[1]/ns2:name

will select the name of the agent immediately preceding the identified person.

If you need help declaring the XML namespace prefixes, see How does XPath deal with XML namespaces?

Update based on OP's comment:

In my original xml document, the agent node is not immediately preceding the person node. I will be running the expression in a loop, for each person node. Sorry for the confusion, I have edited the example and the question so it is more clear what I need.

And in the edited question:

Edit: XPath expression will be used in a loop, for each ns3:person node, so I don't know the specific id attribute value beforehand.

So in your loop simply bind a variable, say $id, to the current ns3:person/@n2:id and then test it in the XPath:

//ns1:agent[@ns2:about = $id]/ns2:name

See also How to pass variable parameter into XPath expression?


问:
How to handle null while comparing maps using streams - Java?
I have 2 data structures with values like:

```<code>List<Map<String,String>> customerDirectory
</code>```

```<code>[{NAME=ALEX BENSON, PHONE=012-12342, ADDRESS=123 MAIN ST, CITY=QUEENS, STATE=NY},
 {NAME=ZOYE ABEL, PHONE=012-12445, ADDRESS=123 WATERSIDE, CITY=WINDSOR, STATE=CT}]
</code>```

and

```<code>Map<String,String> customerInfo
</code>```

```<code>{NAME=ALEX BENSON, PHONE=012-12342, ADDRESS=123 MAIN ST}
</code>```

I am trying to iterate through the customerDirectory to find if customerInfo has exact match in values for the keys - "NAME","PHONE","ADDRESS" so that I could find if the record is a duplicate.

So I have come up with:

```<code>List<String> compareKeys = Arrays.asList("NAME","PHONE","ADDRESS");

Function<Map<String,String>, String> getVal = mp -> compareKeys.stream().map(mp::get).map(String::trim).collect(Collectors.joining());

BiPredicate<Map<String,String>, Map<String,String>> checkDup = (mp1,mp2) -> getVal.apply(mp1).equals(getVal.apply(mp2));

boolean anyMatch = customerDirectory.stream().anyMatch(customer-> checkDup.test(customerInfo, customer));
</code>```

But the customerInfo map can have value for ADDRESS as null for which I have tried:

```<code>BiFunction<Map<String, String>, String, String> handleNull = (mp, key) -> mp.get(key) == null ? " " : mp.get(key);
</code>```

and I have used it in :

```<code>Function<Map<String,String>, String> getVal = mp -> compareKeys.stream().map(key->handleNull.apply(mp,key)).map(mp::get).map(String::trim).collect(Collectors.joining());
</code>```

But I still end up getting NullPointerException which means I am missing the exact flow probably.
Is there a better way to handle null values here?

答:
If i correctly understood your question then you just want to find out is there any exact match or not, and you want to keep your answer in anyMatch. Please try to update your code with below one.

```<code>Function<Map<String, String>, String> getVal = mp ->
    compareKeys.stream().map(mp::get).filter(Objects::nonNull).map(String::trim)
            .collect(Collectors.joining());
</code>```

Body:
I have 2 data structures with values like:

List<Map<String,String>> customerDirectory

[{NAME=ALEX BENSON, PHONE=012-12342, ADDRESS=123 MAIN ST, CITY=QUEENS, STATE=NY},
 {NAME=ZOYE ABEL, PHONE=012-12445, ADDRESS=123 WATERSIDE, CITY=WINDSOR, STATE=CT}]

and

Map<String,String> customerInfo

{NAME=ALEX BENSON, PHONE=012-12342, ADDRESS=123 MAIN ST}

I am trying to iterate through the customerDirectory to find if customerInfo has exact match in values for the keys - "NAME","PHONE","ADDRESS" so that I could find if the record is a duplicate.

So I have come up with:

List<String> compareKeys = Arrays.asList("NAME","PHONE","ADDRESS");

Function<Map<String,String>, String> getVal = mp -> compareKeys.stream().map(mp::get).map(String::trim).collect(Collectors.joining());

BiPredicate<Map<String,String>, Map<String,String>> checkDup = (mp1,mp2) -> getVal.apply(mp1).equals(getVal.apply(mp2));

boolean anyMatch = customerDirectory.stream().anyMatch(customer-> checkDup.test(customerInfo, customer));

But the customerInfo map can have value for ADDRESS as null for which I have tried:

BiFunction<Map<String, String>, String, String> handleNull = (mp, key) -> mp.get(key) == null ? " " : mp.get(key);

and I have used it in :

Function<Map<String,String>, String> getVal = mp -> compareKeys.stream().map(key->handleNull.apply(mp,key)).map(mp::get).map(String::trim).collect(Collectors.joining());

But I still end up getting NullPointerException which means I am missing the exact flow probably.
Is there a better way to handle null values here?

Body:
If i correctly understood your question then you just want to find out is there any exact match or not, and you want to keep your answer in anyMatch. Please try to update your code with below one.

Function<Map<String, String>, String> getVal = mp ->
    compareKeys.stream().map(mp::get).filter(Objects::nonNull).map(String::trim)
            .collect(Collectors.joining());


问:
How to convert document snapshot into a Stream data in flutter?
```<code>DocumentSnapshot doc = await userRef.document(widget.currentuserId).get();
user = User.fromDocument(doc);
bioController.text = user.bio;
usernameController.text = user.username;
displayNameController.text = user.displayName;
</code>```

How to convert this in Stream data?

I tried this but there is some error I can't figure it out:

```<code>Stream<DocumentSnapshot> doc = await userRef.document(widget.currentuserId).snapshots();
user = User.fromDocument(doc);
bioController.text = user.bio;
usernameController.text = user.username;
displayNameController.text = user.displayName;
</code>```

答:
If you use get(), you get Future<DocumentSnapshot>, you need to use snapshots.

```<code>Stream<DocumentSnapshot> stream = userRef.document(widget.currentuserId).snapshots();
stream.listen((snapshot) {
  // snapshot is DocumentSnapshot
});
</code>```

Body:
DocumentSnapshot doc = await userRef.document(widget.currentuserId).get();
user = User.fromDocument(doc);
bioController.text = user.bio;
usernameController.text = user.username;
displayNameController.text = user.displayName;

How to convert this in Stream data?

I tried this but there is some error I can't figure it out:

Stream<DocumentSnapshot> doc = await userRef.document(widget.currentuserId).snapshots();
user = User.fromDocument(doc);
bioController.text = user.bio;
usernameController.text = user.username;
displayNameController.text = user.displayName;

Body:
If you use get(), you get Future<DocumentSnapshot>, you need to use snapshots.

Stream<DocumentSnapshot> stream = userRef.document(widget.currentuserId).snapshots();
stream.listen((snapshot) {
  // snapshot is DocumentSnapshot
});


问:
Creating a button in Java, causes getLayoutParams to return null
I need to create a button in Java. Below is my code:

```<code> Button b = new Button(MyClass.this);
 b.requestLayout();
 LayoutParams lp = b.getLayoutParams();
 lp.height = LayoutParams.WRAP_CONTENT;
 lp.width = LayoutParams.WRAP_CONTENT;
 b.setLayoutParams(lp);
 b.setText("bla");
 b.setTextSize(16);
 b.setOnClickListener(myListener);
</code>```

I then add this button to the bottom of a ListView:

```<code> getListView().addFooterView(b);
</code>```

However this crashes, because getLayoutParams returns null.

Even if I create new  LayoutParams instead of getLayoutParams, i.e.:

```<code> Button b = new Button(MyClass.this);
 LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
 b.setLayoutParams(lp);
 b.setText("bla");
 b.setTextSize(16);
 b.setOnClickListener(myListener);
</code>```

then the application crashes. Without setLayoutParams, it runs fine, but my button is not sized properly.

How can I size my button?

答:
Because I'm adding this button via ListView::addFooterView, it turns out I had to use the ListView type.

```<code> b.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.WRAP_CONTENT, ListView.LayoutParams.WRAP_CONTENT));
</code>```

Using this instead of just LayoutParams resolves my crash. Hope this helps others.

Body:
I need to create a button in Java. Below is my code:

 Button b = new Button(MyClass.this);
 b.requestLayout();
 LayoutParams lp = b.getLayoutParams();
 lp.height = LayoutParams.WRAP_CONTENT;
 lp.width = LayoutParams.WRAP_CONTENT;
 b.setLayoutParams(lp);
 b.setText("bla");
 b.setTextSize(16);
 b.setOnClickListener(myListener);

I then add this button to the bottom of a ListView:

 getListView().addFooterView(b);

However this crashes, because getLayoutParams returns null.

Even if I create new  LayoutParams instead of getLayoutParams, i.e.:

 Button b = new Button(MyClass.this);
 LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
 b.setLayoutParams(lp);
 b.setText("bla");
 b.setTextSize(16);
 b.setOnClickListener(myListener);

then the application crashes. Without setLayoutParams, it runs fine, but my button is not sized properly.

How can I size my button?

Body:
Because I'm adding this button via ListView::addFooterView, it turns out I had to use the ListView type.

 b.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.WRAP_CONTENT, ListView.LayoutParams.WRAP_CONTENT));

Using this instead of just LayoutParams resolves my crash. Hope this helps others.


问:
Read starts before the insert completes
```<code>@Transactional
    public void save(String myIds)
    {
            synchronized (this)
            {
                List<mydata> data = getDataToSaveOrUpdate(myIds);//Returns the new dataList and updates old data
                repository.saveAll(data);
                logger.info("request processed");
            }
        logger.debug("exiting the method");
    }
</code>```

In this method if i sent the two same request with the difference between 0.5 sec what happens getDataToSaveOrUpdate method start reading data from repository before the previous request saveAll finishes the job.

Note One thing i noticed that it will work properly once i removed @Transactional

答:
Second request processing starts as soon as first thread exits synchronized block. Transaction might still not be committed by then. Transaction will only be committed after method execution is completed.

One possible solution is to add synchronized keyword to the method itself.

```<code>@Transactional
public synchronized void save(String myIds) {
    List<mydata> data = getDataToSaveOrUpdate(myIds);//Returns the new dataList and updates old data
    repository.saveAll(data);
    logger.info("request processed");
    logger.debug("exiting the method");
}
</code>```

One need to be very careful when using synchronized keyword. I don't know your exact need, may be it is a valid usage for your scenario.

Title: Read starts before the insert completes

Body:
@Transactional
    public void save(String myIds)
    {
            synchronized (this)
            {
                List<mydata> data = getDataToSaveOrUpdate(myIds);//Returns the new dataList and updates old data
                repository.saveAll(data);
                logger.info("request processed");
            }
        logger.debug("exiting the method");
    }

In this method if i sent the two same request with the difference between 0.5 sec what happens getDataToSaveOrUpdate method start reading data from repository before the previous request saveAll finishes the job.

Note One thing i noticed that it will work properly once i removed @Transactional

Body:
Second request processing starts as soon as first thread exits synchronized block. Transaction might still not be committed by then. Transaction will only be committed after method execution is completed.

One possible solution is to add synchronized keyword to the method itself.

@Transactional
public synchronized void save(String myIds) {
    List<mydata> data = getDataToSaveOrUpdate(myIds);//Returns the new dataList and updates old data
    repository.saveAll(data);
    logger.info("request processed");
    logger.debug("exiting the method");
}

One need to be very careful when using synchronized keyword. I don't know your exact need, may be it is a valid usage for your scenario.


问:
Returning the top 3 values in a range
I am using these 3 formulas to return the #1, #2 and #3 top referral source, in other words the value that appears the most times, 2nd most times and 3rd most times. It has been working perfectly until I today when the #2 and #3 happened to appear the same number of times. The result is that the #2 and #3 result are returning the same name.

Any ideas on how I can fix this or perhaps a different way of returning the top 3 occurring values in a range?

1 Most occurring Referral Source

=INDEX(T:T, 10000*MOD(MAX(COUNTIF(T11:T992,T11:T992)+(ROW(T11:T992)/10000)),1), 1)

2nd most occurring Referral Source

=INDEX(T11:T992,MODE(IF((T11:T992<>"")*(T11:T992<>INDEX(T11:T992,MODE(IF(T11:T992<>"",MATCH(T11:T992,T11:T992,0))))),MATCH(T11:T992,T11:T992,0))))

3 most occurring Referral Source

=INDEX(T11:T992,MODE(IF(((T11:T992<>"")(T11:T992<>INDEX(T11:T992,MODE(IF(T11:T992<>"",MATCH(T11:T992,T11:T992,0)))))(T11:T992<>INDEX(T11:T992,MODE(IF((T11:T992<>"")*(T11:T992<>INDEX(T11:T992,MODE(IF(T11:T992<>"",MATCH(T11:T992,T11:T992,0))))),MATCH(T11:T992,T11:T992,0)))))),MATCH(T11:T992,T11:T992,0))))

答:
I was able to get a working formula from another excel forum that worked perfectly:

jasonb75 said:
Try this for all 3 note that there are 2 instances of D$1:D1 in the formula which need to be changed, these should refer to the cell directly above the first formula before dragging down, e.g. if the formula is going into D2, then it would be D$1:D1, if it is going into Z10 then it would be Z$9:Z9

=INDEX(T:T,AGGREGATE(15,6,ROW($T$11:$T$992)/(COUNTIF($T$11:$T$992,$T$11:$T$992)=AGGREGATE(14,6,COUNTIF($T$11:$T$992,$T$11:$T$992),1+SUMPRODUCT(COUNTIF($T$11:$T$992,D$1:D1))))/ISNA(MATCH($T$11:$T$992,D$1:D1,0)),1))

Title: Returning the top 3 values in a range


问:
Add custom columns to select
I am trying to add custom row and column to all results. I am getting below error,

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.png as badge, 3.5 as rating from instructors as i inner join use' at line 1 (SQL: selecti.id,u.name,i.about,i.price_per_hour,u.profile_picture,https://www.pngitem.com/pimgs/m/575-5754595_why-bali-best-driver-driver-icons-hd-png.pngasbadge,3.5asratingfrominstructorsasiinner joinusersasuonu.id=i.user_idwhere 0 = 1 andgenderin (male) order byi.id` desc limit 10 offset 0)

The associated code:

```<code>public function findInstructors($instrutors, $gender, $offet, $fetch) {

    return DB::table('instructors as i')
        ->select(
            'i.id',
            'u.name',
            'i.about',
            'i.price_per_hour',
            'u.profile_picture',
            'https://www.pngitem.com/pimgs/m/575-5754595_why-bali-best-driver-driver-icons-hd-png.png as badge',
            '3.5 as rating'
        )
        ->join('users as u', 'u.id', 'i.user_id')
        ->whereIn('i.id', $instrutors)
        ->whereIn('gender', $gender)
        ->offset($offet)
        ->limit($fetch)
        ->orderBy('i.id', 'desc')->get();
}
</code>```

答:
mysql understand

```<code>  'https://www.pngitem.com/pimgs/m/575-5754595_why-bali-best-driver-driver-icons-hd-png.png as badge',
</code>```

as tableName.columnNmae as alias
because of dot using in extra column name:

to avoid this behavior
you should use MySQL Backticks `` :

```<code> `https://www.pngitem.com/pimgs/m/575-5754595_why-bali-best-driver-driver-icons-hd-png.png as badge`,
            `3.5 as rating`
</code>```

more details in:
https://riptutorial.com/mysql/example/18445/backticks-usage

Title: Add custom columns to select

Body:
I am trying to add custom row and column to all results. I am getting below error,

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.png as badge, 3.5 as rating from instructors as i inner join use' at line 1 (SQL: selecti.id,u.name,i.about,i.price_per_hour,u.profile_picture,https://www.pngitem.com/pimgs/m/575-5754595_why-bali-best-driver-driver-icons-hd-png.pngasbadge,3.5asratingfrominstructorsasiinner joinusersasuonu.id=i.user_idwhere 0 = 1 andgenderin (male) order byi.id` desc limit 10 offset 0)

The associated code:

public function findInstructors($instrutors, $gender, $offet, $fetch) {

    return DB::table('instructors as i')
        ->select(
            'i.id',
            'u.name',
            'i.about',
            'i.price_per_hour',
            'u.profile_picture',
            'https://www.pngitem.com/pimgs/m/575-5754595_why-bali-best-driver-driver-icons-hd-png.png as badge',
            '3.5 as rating'
        )
        ->join('users as u', 'u.id', 'i.user_id')
        ->whereIn('i.id', $instrutors)
        ->whereIn('gender', $gender)
        ->offset($offet)
        ->limit($fetch)
        ->orderBy('i.id', 'desc')->get();
}

Body:
mysql understand

  'https://www.pngitem.com/pimgs/m/575-5754595_why-bali-best-driver-driver-icons-hd-png.png as badge',

as tableName.columnNmae as alias
because of dot using in extra column name:

to avoid this behavior
you should use MySQL Backticks `` :

 `https://www.pngitem.com/pimgs/m/575-5754595_why-bali-best-driver-driver-icons-hd-png.png as badge`,
            `3.5 as rating`

more details in:
https://riptutorial.com/mysql/example/18445/backticks-usage


问:
Is it possible to substitute a server backend using Dropbox?
I am developing an iOS application (to be deployed on the App Store) that requires content updates on a weekly basis.

I understand that the best way to achieve this would be to use a server, where the app would query for new data and download responses in JSON. However I am not knowledgeable when it comes to HTML, PHP or MySQL and therefore am endeavoring to find an alternative.

Here's an idea: using Dropbox to substitute for a server backend. My app connects to one central Dropbox account, checks for new files, and downloads them if present.

Is this idea feasible? If not, are there any alternatives?

答: I am pretty late to the party, but this is possible and not necessarily a stupid idea (though this depends on what you need). You might want to have a look at remote storage for example, which allows you to use Dropbox among other providers as backend.</p>


问:
JavaScript Copy of Arrays
I'm trying to eliminate the minimum and maximum values from the below array and create 2 new arrays without the maximum and minimum values

array = [4, 6, 7, 8, 9]
const indOmin = 0,
  indOm = 5

minArr = arr
maxArr = arr

minArr.forEach(cur => {
  if (arr.indexOf(cur) === indOmin) {
    minArr.splice(indOmin, 1)
  }
})

maxArr.forEach(cur => {
  if (arr.indexOf(cur) === indOm) {
    maxArr.splice(indOm, 1)
  }
})
```

<p>When I use...</p>

<pre class="lang-js prettyprint-override"><code>console.log(minArr)
console.log(maxArr)
</code>```

...then in both cases it returns [6, 7, 8, 9].

But instead of...

minArr = arr
maxArr = arr
```

<p>...if I use...</p>

<pre class="lang-js prettyprint-override"><code>minArr = arr.map(cur => cur = cur)
maxArr = arr.map(cur => cur = cur)
</code>```

... then the arrays return expected values.

```<code>[6, 7, 8, 9]
[4, 6, 7, 8]
</code>```

Please help me understand why it doesn't work when I explicitly use the = operator (minArr = arr).

答:
Change

```<code>minArr=arr; maxArr=arr;
</code>```

To

```<code>minArr=[...arr]; maxArr=[...arr];
</code>```

It doesn't work because array doesn't copy with = you had reference of same array in both minarr and maxarr.

Title: JavaScript Copy of Arrays

Body:
I'm trying to eliminate the minimum and maximum values from the below array and create 2 new arrays without the maximum and minimum values

array = [4, 6, 7, 8, 9]
const indOmin = 0,
  indOm = 5

minArr = arr
maxArr = arr

minArr.forEach(cur => {
  if (arr.indexOf(cur) === indOmin) {
    minArr.splice(indOmin, 1)
  }
})

maxArr.forEach(cur => {
  if (arr.indexOf(cur) === indOm) {
    maxArr.splice(indOm, 1)
  }
})

When I use...

console.log(minArr)
console.log(maxArr)

...then in both cases it returns [6, 7, 8, 9].

But instead of...

minArr = arr
maxArr = arr

...if I use...

minArr = arr.map(cur => cur = cur)
maxArr = arr.map(cur => cur = cur)

... then the arrays return expected values.

[6, 7, 8, 9]
[4, 6, 7, 8]

Please help me understand why it doesn't work when I explicitly use the = operator (minArr = arr).

Body:
Change

minArr=arr; maxArr=arr;

To

minArr=[...arr]; maxArr=[...arr];

It doesn't work because array doesn't copy with = you had reference of same array in both minarr and maxarr.


问:
Flutter: How to open Drawer programmatically
I want to open Drawer programmatically not by sliding  it, how to disable that sliding functionality (touch functionality of Drawer)

答:
Here is another example of opening the drawer programmatically from a hamburger icon and without the Appbar:-</p>

```<code>import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  var scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        key: scaffoldKey,
        drawer: new Drawer(
          child: new ListView(
            padding: EdgeInsets.zero,
            children: <Widget>[
              DrawerHeader(
                child: Text('Drawer Header'),
                decoration: BoxDecoration(
                  color: Colors.blue,
                ),
              ),
              ListTile(
                title: Text('Item 1'),
                onTap: () {
                  //Do some stuff here
                  //Closing programmatically - very less practical use
                  scaffoldKey.currentState.openEndDrawer();
                },
              )
            ],
          ),
        ),
        body: Stack(
          children: <Widget>[
            new Center(
                child: new Column(
              children: <Widget>[],
            )),
            Positioned(
              left: 10,
              top: 20,
              child: IconButton(
                icon: Icon(Icons.menu),
                onPressed: () => scaffoldKey.currentState.openDrawer(),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

Body:
Here is another example of opening the drawer programmatically from a hamburger icon and without the Appbar:-

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  var scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        key: scaffoldKey,
        drawer: new Drawer(
          child: new ListView(
            padding: EdgeInsets.zero,
            children: <Widget>[
              DrawerHeader(
                child: Text('Drawer Header'),
                decoration: BoxDecoration(
                  color: Colors.blue,
                ),
              ),
              ListTile(
                title: Text('Item 1'),
                onTap: () {
                  //Do some stuff here
                  //Closing programmatically - very less practical use
                  scaffoldKey.currentState.openEndDrawer();
                },
              )
            ],
          ),
        ),
        body: Stack(
          children: <Widget>[
            new Center(
                child: new Column(
              children: <Widget>[],
            )),
            Positioned(
              left: 10,
              top: 20,
              child: IconButton(
                icon: Icon(Icons.menu),
                onPressed: () => scaffoldKey.currentState.openDrawer(),
              ),
            ),
          ],
        ),
      ),
    );
  }
}


问:
Transact-SQL: How do I tokenize a string?
I want to be able to tokenize an input string from a text box to do my query.
Example: user enters "abc xyz 123" in the text box.
I want to do this:

```<code>SELECT * FROM database WHERE Name contains "abc" AND "xyz" AND "123"
-- as opposed to containing "abc xyz 123"
-- please ignore my sql syntax, I am an absolute beginner
</code>```

Thanks.

答:
Using a string split function (for example, like this one), you could have something like this:</p>

```<code>SELECT t.*
FROM atable t
  INNER JOIN dbo.Split(@UserInput, ' ') s ON t.Name LIKE '%' + s.Data + '%'
</code>```

Body:
I want to be able to tokenize an input string from a text box to do my query.
Example: user enters "abc xyz 123" in the text box.
I want to do this:

SELECT * FROM database WHERE Name contains "abc" AND "xyz" AND "123"
-- as opposed to containing "abc xyz 123"
-- please ignore my sql syntax, I am an absolute beginner

Thanks.

Body:
Using a string split function (for example, like this one), you could have something like this:

SELECT t.*
FROM atable t
  INNER JOIN dbo.Split(@UserInput, ' ') s ON t.Name LIKE '%' + s.Data + '%'


问:
check if number is in given range?
Given a number and a dictionary with min and max properties, return True if the number lies within the given range (inclusive).

Examples

```<code>is_in_range(4, { "min": 0, "max": 5 }) ➞ True
is_in_range(1, { "min": 4, "max": 5 }) ➞ False
</code>```

The below code is working for the int values of a number to be searched and dictionary values, but not for float values.

Examples

```<code>is_in_range(1.8, { "min": 1.25, "max": 1.75 }) ➞ False
</code>```

So far what I tried:

def is_in_range(n, r):
    for i in range(r['min'],r['max']+1):
        if i<=n:
            return True
        else:
            return False

    print(is_in_range(4, { "min": 6, "max": 10 }))
```

答:
You can try something like this</p>

```<code>r = {'min':4, 'max':5}
n = 1

def isin(r,n):
    return (n>=r['min']) & (n<=r['max'])
</code>```

Title: check if number is in given range?

Body:
Given a number and a dictionary with min and max properties, return True if the number lies within the given range (inclusive).

Examples

is_in_range(4, { "min": 0, "max": 5 }) ➞ True
is_in_range(1, { "min": 4, "max": 5 }) ➞ False

The below code is working for the int values of a number to be searched and dictionary values, but not for float values.

Examples

is_in_range(1.8, { "min": 1.25, "max": 1.75 }) ➞ False

So far what I tried:

def is_in_range(n, r):
    for i in range(r['min'],r['max']+1):
        if i<=n:
            return True
        else:
            return False

    print(is_in_range(4, { "min": 6, "max": 10 }))

Body:
You can try something like this

r = {'min':4, 'max':5}
n = 1

def isin(r,n):
    return (n>=r['min']) & (n<=r['max'])


问:
Can't convert QLineEdit input into float
I made an exchange rate program which i could use from the terminal and I'm trying to make an interface for I but I can't turn the QLineEdit input into float.
It gives me this error

Traceback (most recent call last):
  ..., line 73, in
    self.buton.clicked.connect(lambda: self.pressed(currency1, currency2,input))
  ..., line 79, in pressed
    quantity = float(input)
ValueError: could not convert string to float:

```<code>
      self.lineEdit = QtWidgets.QLineEdit(self.verticalLayoutWidget_2)

      self.lineEdit.setObjectName("lineEdit")

----

     input=self.lineEdit.text()

----

    self.buton.clicked.connect(lambda: self.pressed(currency1, currency2,input))

    def pressed(self,currency1,currency2,input):

        quantity = float(input)

        if currency1 == "EUR":
           self.label.setText("{} EUR = {} {}".format(quantity, currency2, float(self.json_data["rates"][currency2]) * quantity))

        else:
             self.label.setText("{} {} = {} {}".format(quantity, currency1, currency2, float(
                (self.json_data["rates"][currency2] / self.json_data["rates"][currency1])) * quantity))
</code>```

Here is the full code if needed.

```<code>
from PyQt5 import QtCore, QtGui, QtWidgets
import requests

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Exchange")
        Form.resize(850, 558)
        self.buton=QtWidgets.QPushButton("Calculate")
        self.verticalLayoutWidget_2 = QtWidgets.QWidget(Form)
        self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(50, 60, 751, 351))
        self.verticalLayoutWidget_2.setObjectName("verticalLayoutWidget_2")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget_2)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.lineEdit = QtWidgets.QLineEdit(self.verticalLayoutWidget_2)
        self.lineEdit.setObjectName("lineEdit")
        self.verticalLayout.addWidget(self.lineEdit)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.comboBox_2 = QtWidgets.QComboBox(self.verticalLayoutWidget_2)
        self.comboBox_2.setObjectName("comboBox_2")
        self.horizontalLayout.addWidget(self.comboBox_2)
        self.comboBox = QtWidgets.QComboBox(self.verticalLayoutWidget_2)
        self.comboBox.setObjectName("comboBox")
        self.horizontalLayout.addWidget(self.comboBox)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.verticalLayout_2.addLayout(self.verticalLayout)
        self.verticalLayout_2.addWidget(self.buton)
        self.label = QtWidgets.QLabel(self.verticalLayoutWidget_2)
        self.verticalLayout_2.addStretch()
        self.label.setText("")
        self.label.setObjectName("label")
        self.verticalLayout_2.addWidget(self.label)

        self.label.setText("Select currencies and enter the quantity")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

        url = "http://data.fixer.io/api/latest?access_key=f79c72f7979f662b465bd28e40efa5cf&format=1"
        response = requests.get(url)
        self.json_data = response.json()
        kurlar=self.json_data["rates"].keys()
        for i in kurlar:
            self.comboBox.addItem(i)
            self.comboBox_2.addItem(i)

        index=self.comboBox.findText("TRY",QtCore.Qt.MatchFixedString)
        self.comboBox.setCurrentIndex(index)
        self.comboBox_2.setCurrentIndex(index)

        currency1=self.comboBox.currentText()
        currency2=self.comboBox_2.currentText()

        input=self.lineEdit.text()

        self.buton.clicked.connect(lambda: self.pressed(currency1, currency2,input))

    def pressed(self,currency1,currency2,input):

        quantity = float(input)

        if currency1 == "EUR":
           self.label.setText("{} EUR = {} {}".format(quantity, currency2, float(self.json_data["rates"][currency2]) * quantity))

        else:
             self.label.setText("{} {} = {} {}".format(quantity, currency1, currency2, float(
                (self.json_data["rates"][currency2] / self.json_data["rates"][currency1])) * quantity))

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())
</code>```

答:
That occurs because you're getting the text from the lineEdit in the beginning  itself that's why it is an empty string you should get the text from lineEdit after pressing the button</p>

```<code>from PyQt5 import QtCore, QtGui, QtWidgets
import requests

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Exchange")
        Form.resize(850, 558)
        self.buton = QtWidgets.QPushButton("Calculate")
        self.verticalLayoutWidget_2 = QtWidgets.QWidget(Form)
        self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(50, 60, 751, 351))
        self.verticalLayoutWidget_2.setObjectName("verticalLayoutWidget_2")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget_2)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.lineEdit = QtWidgets.QLineEdit(self.verticalLayoutWidget_2)
        self.lineEdit.setObjectName("lineEdit")
        self.verticalLayout.addWidget(self.lineEdit)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.comboBox_2 = QtWidgets.QComboBox(self.verticalLayoutWidget_2)
        self.comboBox_2.setObjectName("comboBox_2")
        self.horizontalLayout.addWidget(self.comboBox_2)
        self.comboBox = QtWidgets.QComboBox(self.verticalLayoutWidget_2)
        self.comboBox.setObjectName("comboBox")
        self.horizontalLayout.addWidget(self.comboBox)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.verticalLayout_2.addLayout(self.verticalLayout)
        self.verticalLayout_2.addWidget(self.buton)
        self.label = QtWidgets.QLabel(self.verticalLayoutWidget_2)
        self.verticalLayout_2.addStretch()
        self.label.setText("")
        self.label.setObjectName("label")
        self.verticalLayout_2.addWidget(self.label)

        self.label.setText("Select currencies and enter the quantity")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

        url = "http://data.fixer.io/api/latest?access_key=f79c72f7979f662b465bd28e40efa5cf&format=1"
        response = requests.get(url)
        self.json_data = response.json()
        kurlar = self.json_data["rates"].keys()
        for i in kurlar:
            self.comboBox.addItem(i)
            self.comboBox_2.addItem(i)

        index = self.comboBox.findText("TRY", QtCore.Qt.MatchFixedString)
        self.comboBox.setCurrentIndex(index)
        self.comboBox_2.setCurrentIndex(index)

        currency1 = self.comboBox.currentText()
        currency2 = self.comboBox_2.currentText()

        self.buton.clicked.connect(lambda: self.pressed(currency1, currency2))

    def pressed(self, currency1, currency2):
        # getting the text from the lineEdit after pressing the button
        quantity = float(self.lineEdit.text())

        if currency1 == "EUR":
            self.label.setText(
                "{} EUR = {} {}".format(quantity, currency2, float(self.json_data["rates"][currency2]) * quantity))

        else:
            self.label.setText("{} {} = {} {}".format(quantity, currency1, currency2, float(
                (self.json_data["rates"][currency2] / self.json_data["rates"][currency1])) * quantity))

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())
</code>```

Body:
I made an exchange rate program which i could use from the terminal and I'm trying to make an interface for I but I can't turn the QLineEdit input into float.
It gives me this error

Traceback (most recent call last):
  ..., line 73, in
    self.buton.clicked.connect(lambda: self.pressed(currency1, currency2,input))
  ..., line 79, in pressed
    quantity = float(input)
ValueError: could not convert string to float:

      self.lineEdit = QtWidgets.QLineEdit(self.verticalLayoutWidget_2)

      self.lineEdit.setObjectName("lineEdit")

----

     input=self.lineEdit.text()

----

    self.buton.clicked.connect(lambda: self.pressed(currency1, currency2,input))

    def pressed(self,currency1,currency2,input):

        quantity = float(input)

        if currency1 == "EUR":
           self.label.setText("{} EUR = {} {}".format(quantity, currency2, float(self.json_data["rates"][currency2]) * quantity))

        else:
             self.label.setText("{} {} = {} {}".format(quantity, currency1, currency2, float(
                (self.json_data["rates"][currency2] / self.json_data["rates"][currency1])) * quantity))

Here is the full code if needed.

from PyQt5 import QtCore, QtGui, QtWidgets
import requests

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Exchange")
        Form.resize(850, 558)
        self.buton=QtWidgets.QPushButton("Calculate")
        self.verticalLayoutWidget_2 = QtWidgets.QWidget(Form)
        self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(50, 60, 751, 351))
        self.verticalLayoutWidget_2.setObjectName("verticalLayoutWidget_2")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget_2)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.lineEdit = QtWidgets.QLineEdit(self.verticalLayoutWidget_2)
        self.lineEdit.setObjectName("lineEdit")
        self.verticalLayout.addWidget(self.lineEdit)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.comboBox_2 = QtWidgets.QComboBox(self.verticalLayoutWidget_2)
        self.comboBox_2.setObjectName("comboBox_2")
        self.horizontalLayout.addWidget(self.comboBox_2)
        self.comboBox = QtWidgets.QComboBox(self.verticalLayoutWidget_2)
        self.comboBox.setObjectName("comboBox")
        self.horizontalLayout.addWidget(self.comboBox)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.verticalLayout_2.addLayout(self.verticalLayout)
        self.verticalLayout_2.addWidget(self.buton)
        self.label = QtWidgets.QLabel(self.verticalLayoutWidget_2)
        self.verticalLayout_2.addStretch()
        self.label.setText("")
        self.label.setObjectName("label")
        self.verticalLayout_2.addWidget(self.label)

        self.label.setText("Select currencies and enter the quantity")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

        url = "http://data.fixer.io/api/latest?access_key=f79c72f7979f662b465bd28e40efa5cf&format=1"
        response = requests.get(url)
        self.json_data = response.json()
        kurlar=self.json_data["rates"].keys()
        for i in kurlar:
            self.comboBox.addItem(i)
            self.comboBox_2.addItem(i)

        index=self.comboBox.findText("TRY",QtCore.Qt.MatchFixedString)
        self.comboBox.setCurrentIndex(index)
        self.comboBox_2.setCurrentIndex(index)

        currency1=self.comboBox.currentText()
        currency2=self.comboBox_2.currentText()

        input=self.lineEdit.text()

        self.buton.clicked.connect(lambda: self.pressed(currency1, currency2,input))

    def pressed(self,currency1,currency2,input):

        quantity = float(input)

        if currency1 == "EUR":
           self.label.setText("{} EUR = {} {}".format(quantity, currency2, float(self.json_data["rates"][currency2]) * quantity))

        else:
             self.label.setText("{} {} = {} {}".format(quantity, currency1, currency2, float(
                (self.json_data["rates"][currency2] / self.json_data["rates"][currency1])) * quantity))

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

Body:
That occurs because you're getting the text from the lineEdit in the beginning  itself that's why it is an empty string you should get the text from lineEdit after pressing the button

from PyQt5 import QtCore, QtGui, QtWidgets
import requests

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Exchange")
        Form.resize(850, 558)
        self.buton = QtWidgets.QPushButton("Calculate")
        self.verticalLayoutWidget_2 = QtWidgets.QWidget(Form)
        self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(50, 60, 751, 351))
        self.verticalLayoutWidget_2.setObjectName("verticalLayoutWidget_2")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget_2)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.lineEdit = QtWidgets.QLineEdit(self.verticalLayoutWidget_2)
        self.lineEdit.setObjectName("lineEdit")
        self.verticalLayout.addWidget(self.lineEdit)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.comboBox_2 = QtWidgets.QComboBox(self.verticalLayoutWidget_2)
        self.comboBox_2.setObjectName("comboBox_2")
        self.horizontalLayout.addWidget(self.comboBox_2)
        self.comboBox = QtWidgets.QComboBox(self.verticalLayoutWidget_2)
        self.comboBox.setObjectName("comboBox")
        self.horizontalLayout.addWidget(self.comboBox)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.verticalLayout_2.addLayout(self.verticalLayout)
        self.verticalLayout_2.addWidget(self.buton)
        self.label = QtWidgets.QLabel(self.verticalLayoutWidget_2)
        self.verticalLayout_2.addStretch()
        self.label.setText("")
        self.label.setObjectName("label")
        self.verticalLayout_2.addWidget(self.label)

        self.label.setText("Select currencies and enter the quantity")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

        url = "http://data.fixer.io/api/latest?access_key=f79c72f7979f662b465bd28e40efa5cf&format=1"
        response = requests.get(url)
        self.json_data = response.json()
        kurlar = self.json_data["rates"].keys()
        for i in kurlar:
            self.comboBox.addItem(i)
            self.comboBox_2.addItem(i)

        index = self.comboBox.findText("TRY", QtCore.Qt.MatchFixedString)
        self.comboBox.setCurrentIndex(index)
        self.comboBox_2.setCurrentIndex(index)

        currency1 = self.comboBox.currentText()
        currency2 = self.comboBox_2.currentText()

        self.buton.clicked.connect(lambda: self.pressed(currency1, currency2))

    def pressed(self, currency1, currency2):
        # getting the text from the lineEdit after pressing the button
        quantity = float(self.lineEdit.text())

        if currency1 == "EUR":
            self.label.setText(
                "{} EUR = {} {}".format(quantity, currency2, float(self.json_data["rates"][currency2]) * quantity))

        else:
            self.label.setText("{} {} = {} {}".format(quantity, currency1, currency2, float(
                (self.json_data["rates"][currency2] / self.json_data["rates"][currency1])) * quantity))

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())


问:
Is there a way I can read packets from a pcap file into an array?
I am trying to build a new layer using scapy. I want to read a pcap file and store each packet in an array so that I can access all the information inside the packet using the index of the array.</p>

答:
As you can read everywhere Scape is SUPER slow for pcap files >10MB. I made a couple of tools always using dpkt. Just to give you an idea. Having a 670MB file using dpkt splitting the specific bytes I need compared to full fletched scapy (reading raw packages (the fastest solution with scapy)) is:

dpkt needs 150s (6GB ram), scapy >750s (>10GB)


问:
iFrame not loading URL
I am using the following simple iFrame code to load Yahoo but it's not loading anyway. in Chrome Inspector I see the URL status as 301 first and then cancel. Any idea why is it happening?</p>

```<code><iframe name="iframe1" src="http://yahoo.com"></iframe>
</code>```

答: My latest Firefox silently refused to load an unencrypted iframe when the parent was unencrypted.  It showed no console messages about an attempt to load the child or any reason to not try doing so.</p>

Title: iFrame not loading URL