问:
Chain iterators to references of different lifetimies
I want to build a recursive function for traversing a tree in Rust. The function should always get the next element and an iterator over references to the ancestor elements.

For the iterator over ancestor elements, one could in principle use the chain and once methods. Consider the following simple example, where the tree is jsut a Vec (for the purpose of this demonstration):

```<code>fn proceed<'a, I>(mut remaining: Vec<String>, ancestors: I)
where
    I: Iterator<Item = &'a String> + Clone,
{
    if let Some(next) = remaining.pop() {
        let next_ancestors = ancestors.chain(std::iter::once(&next));
        proceed(remaining, next_ancestors);
    }
}
</code>```

Playground

This fails to compile because &next has a shorter lifetime than 'a:

error[E0597]: `next` does not live long enough
 --> src/lib.rs:6:62
  |
1 | fn proceed<'a, I>(mut remaining: Vec<String>, ancestors: I)
  |            -- lifetime `'a` defined here
...
6 |         let next_ancestors = ancestors.chain(std::iter::once(&next));
  |                              --------------------------------^^^^^--
  |                              |                               |
  |                              |                               borrowed value does not live long enough
  |                              argument requires that `next` is borrowed for `'a`
7 |         proceed(remaining, next_ancestors);
8 |     }
  |     - `next` dropped here while still borrowed
```

<p>I tried to overcome this by adding an explicit second lifetime <code>'b: 'a</code> and forcing an explicit reference by something like <code>let next_ref: &'b String = &next</code>, but that yields a (different) error message as well.</p>

<p>One solution I came up with was to call <code>map</code> as follows:</p>

```let next_ancestors = ancestors.map(|r| r).chain(std::iter::once(&next));
```

As pointed out by @trentcl, this doesn't actually solve the problem, as the compiler then gets stuck in an infinite loop when compiling proceed for all the nested Chains when one actually tries to call the function.

答:
The pieces of solution are already around, just to summarize:

As you already know, using map(|r| r) "decouples" the lifetime requirement of ancestors
from the lifetime of &next.

As already stated in the comments, fixing
the infinite recursion is a matter to change ancestors into a trait object.

```<code>fn proceed<'a>(mut remaining: Vec<String>, ancestors: &mut dyn Iterator<Item = &'a String>) {
    if let Some(next) = remaining.pop() {
        let mut next_ancestors = ancestors.map(|r| r).chain(std::iter::once(&next));
        proceed(remaining, &mut next_ancestors);
    }
}

fn main() {
    let v = vec!["a".to_string(), "b".to_string()];
    proceed(v, &mut std::iter::empty());
}
</code>```

Body:
I want to build a recursive function for traversing a tree in Rust. The function should always get the next element and an iterator over references to the ancestor elements.

For the iterator over ancestor elements, one could in principle use the chain and once methods. Consider the following simple example, where the tree is jsut a Vec (for the purpose of this demonstration):

fn proceed<'a, I>(mut remaining: Vec<String>, ancestors: I)
where
    I: Iterator<Item = &'a String> + Clone,
{
    if let Some(next) = remaining.pop() {
        let next_ancestors = ancestors.chain(std::iter::once(&next));
        proceed(remaining, next_ancestors);
    }
}

Playground

This fails to compile because &next has a shorter lifetime than 'a:

error[E0597]: `next` does not live long enough
 --> src/lib.rs:6:62
  |
1 | fn proceed<'a, I>(mut remaining: Vec<String>, ancestors: I)
  |            -- lifetime `'a` defined here
...
6 |         let next_ancestors = ancestors.chain(std::iter::once(&next));
  |                              --------------------------------^^^^^--
  |                              |                               |
  |                              |                               borrowed value does not live long enough
  |                              argument requires that `next` is borrowed for `'a`
7 |         proceed(remaining, next_ancestors);
8 |     }
  |     - `next` dropped here while still borrowed

I tried to overcome this by adding an explicit second lifetime 'b: 'a and forcing an explicit reference by something like let next_ref: &'b String = &next, but that yields a (different) error message as well.

One solution I came up with was to call map as follows:

let next_ancestors = ancestors.map(|r| r).chain(std::iter::once(&next));

As pointed out by @trentcl, this doesn't actually solve the problem, as the compiler then gets stuck in an infinite loop when compiling proceed for all the nested Chains when one actually tries to call the function.

Body:
The pieces of solution are already around, just to summarize:

As you already know, using map(|r| r) "decouples" the lifetime requirement of ancestors
from the lifetime of &next.

As already stated in the comments, fixing
the infinite recursion is a matter to change ancestors into a trait object.

fn proceed<'a>(mut remaining: Vec<String>, ancestors: &mut dyn Iterator<Item = &'a String>) {
    if let Some(next) = remaining.pop() {
        let mut next_ancestors = ancestors.map(|r| r).chain(std::iter::once(&next));
        proceed(remaining, &mut next_ancestors);
    }
}

fn main() {
    let v = vec!["a".to_string(), "b".to_string()];
    proceed(v, &mut std::iter::empty());
}


来源: stackexchange

问:
Custom creation of QFuture
I've faced quite an odd problem with QtConcurrent, mostly because of strange programming desires, maybe it's just an XY-problem, but...

So, there is my code, trying to communicate with the database, a backend code actually (on Qt, yes). It has to work quick and handle some requests, so I need a thread pool. As a well-known fact I suppose the connection establishing itself is a very time-consuming operation, so there is a need in persistent database connections resulting in persistent threads (QSqlDatabase cannot be moved around between the threads). Also it is quite natural to want asynchronous request handling, thus resulting in some need of a simple way to pass them to the persistent threads.

Nothing too complex, lets assume there already exists some boilerplate in a form like...

// That's what I want for now
QFuture<int> res = workers[i]->async(param1, param2);

// OR

// That's what I DO NOT want to get
workers[i]->async(param1, param2, [](QFuture<int> res) { // QFuture to pass exceptions
     // callback here
});

```

That can be done for sure. Why not std::future? Well, it is much easier to use QFutureWatcher and it's signals for notifications about result's readiness. Pure C++ notification solutions are muuuch more complex and callbacks are also someting that has to be dragged through the class hierarchy. Each worker interfaces a thread with DB connections, obviously.

Okay, all of that can be written, but... custom thread pool would mean no QtConcurrent convenience, there seem to be only risky ways to create that QFuture so that it could be returned by the custom worker. QThreadPool is of no use, because it would be a whole big story to create persistent runnables in it. More to say, the boilerplate I've briefly described is gonna be some kind of project's core, used in many places, not something to be easily replaced by a 100 hand-made thread managings.

In short: if I could construst a QFuture for my results, the problem would be solved.
Could anyone point me to a solution or a workaround? Would be grateful for any bright ideas.

UPD:

@VladimirBershov offered a good modern solution which implements observer pattern. After some googling I've found a QPromise library. Of course, constructing a custom QFuture is still hacky and can be only done via undocumented QFutureInterface class, but still some  "promise-like" solution makes asynchronous calls neater by far as I can judge.

答:
My idea is to use thread pools with maximum 1 thread available for each.

```<code>QThreadPool* persistentThread = new QThreadPool; // no need to write custom thread pool
persistentThread->setMaxThreadCount(1);
persistentThread->setExpiryTimeout(-1);
</code>```

and then

```<code>QFuture<int> future_1 = QtConcurrent::run(persistentThread, func_1);
QFuture<int> future_2 = QtConcurrent::run(persistentThread, func_2);
</code>```

func_2 will be executed after func_1 in the same one "persistent" thread.

ContentLicense: CC BY-SA 4.0

Title: Custom creation of QFuture

Body:
I've faced quite an odd problem with QtConcurrent, mostly because of strange programming desires, maybe it's just an XY-problem, but...

So, there is my code, trying to communicate with the database, a backend code actually (on Qt, yes). It has to work quick and handle some requests, so I need a thread pool. As a well-known fact I suppose the connection establishing itself is a very time-consuming operation, so there is a need in persistent database connections resulting in persistent threads (QSqlDatabase cannot be moved around between the threads). Also it is quite natural to want asynchronous request handling, thus resulting in some need of a simple way to pass them to the persistent threads.

Nothing too complex, lets assume there already exists some boilerplate in a form like...

// That's what I want for now
QFuture<int> res = workers[i]->async(param1, param2);

// OR

// That's what I DO NOT want to get
workers[i]->async(param1, param2, [](QFuture<int> res) { // QFuture to pass exceptions
     // callback here
});

That can be done for sure. Why not std::future? Well, it is much easier to use QFutureWatcher and it's signals for notifications about result's readiness. Pure C++ notification solutions are muuuch more complex and callbacks are also someting that has to be dragged through the class hierarchy. Each worker interfaces a thread with DB connections, obviously.

Okay, all of that can be written, but... custom thread pool would mean no QtConcurrent convenience, there seem to be only risky ways to create that QFuture so that it could be returned by the custom worker. QThreadPool is of no use, because it would be a whole big story to create persistent runnables in it. More to say, the boilerplate I've briefly described is gonna be some kind of project's core, used in many places, not something to be easily replaced by a 100 hand-made thread managings.

In short: if I could construst a QFuture for my results, the problem would be solved.
Could anyone point me to a solution or a workaround? Would be grateful for any bright ideas.

UPD:

@VladimirBershov offered a good modern solution which implements observer pattern. After some googling I've found a QPromise library. Of course, constructing a custom QFuture is still hacky and can be only done via undocumented QFutureInterface class, but still some  "promise-like" solution makes asynchronous calls neater by far as I can judge.

Body:
My idea is to use thread pools with maximum 1 thread available for each.

QThreadPool* persistentThread = new QThreadPool; // no need to write custom thread pool
persistentThread->setMaxThreadCount(1);
persistentThread->setExpiryTimeout(-1);

and then

QFuture<int> future_1 = QtConcurrent::run(persistentThread, func_1);
QFuture<int> future_2 = QtConcurrent::run(persistentThread, func_2);

func_2 will be executed after func_1 in the same one "persistent" thread.


问:
How to get the background to follow the camera?
i am looking to make the background follow the player instead of having to keep pasting the background across the screen. Do i need to attach the background to do the same?

The code below is the code i have to move the background across the screen

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

    public class CameraMovement : MonoBehaviour

{
    private Vector3 xDirectionMove;

        public Transform LevelFinishCam;
        public float speed = 5f;

    void Start()
    {
        xDirectionMove = (LevelFinishCam.position -transform.position).normalized;
    }

    void Update()
{
    transform.position += xDirectionMove * speed * Time.deltaTime;
}
</code>```

}

答:
there are some examples in this thread:

https://answers.unity.com/questions/1310167/how-to-make-the-background-follow-the-camera.html

Body:
i am looking to make the background follow the player instead of having to keep pasting the background across the screen. Do i need to attach the background to do the same?

The code below is the code i have to move the background across the screen

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

    public class CameraMovement : MonoBehaviour

{
    private Vector3 xDirectionMove;

        public Transform LevelFinishCam;
        public float speed = 5f;

    void Start()
    {
        xDirectionMove = (LevelFinishCam.position -transform.position).normalized;
    }

    void Update()
{
    transform.position += xDirectionMove * speed * Time.deltaTime;
}

}


问:
Group comma seperated values in a row and create a new pandas column
I have a situation where I need to create a new pandas column based on the comma separated values that are present in the corresponding using some matching of the phrases.
For examples: My data frame looks like this :

```<code>ID             INFORMATION
1              HR, MGMT, Leadership, etc
2              Analytics, leader, role, etc
3              Telecom, leader, management, manager, etc
4              IT, leader, role, etc
5              Management, HR, Role, Leadership
</code>```

I want a new pandas column that will give me the following basis the selection of the keywords from the information column. For example: if I search for HR in row 1, then the HR Skills should be returned. In row 5 if I search for HR and Management- HR Management Skills should be returned. The output should look like this :

```<code>ID      SkillSet
1       HR Skills
2       Analytics Skills
3       Telecom Skills
4       IT Skills
5       HR and Management Skills
</code>```

The problem is more around doing an active keyword search or multiple keyword search. How should I achieve this?

答:
```<code> df.loc[df['INFORMATION'].str.contains('HR'), 'SkillSet'] = 'HR Skills'
</code>```

Body:
I have a situation where I need to create a new pandas column based on the comma separated values that are present in the corresponding using some matching of the phrases.
For examples: My data frame looks like this :

ID             INFORMATION
1              HR, MGMT, Leadership, etc
2              Analytics, leader, role, etc
3              Telecom, leader, management, manager, etc
4              IT, leader, role, etc
5              Management, HR, Role, Leadership

I want a new pandas column that will give me the following basis the selection of the keywords from the information column. For example: if I search for HR in row 1, then the HR Skills should be returned. In row 5 if I search for HR and Management- HR Management Skills should be returned. The output should look like this :

ID      SkillSet
1       HR Skills
2       Analytics Skills
3       Telecom Skills
4       IT Skills
5       HR and Management Skills

The problem is more around doing an active keyword search or multiple keyword search. How should I achieve this?


问:
Why aren't delegate instances always cached?
Why does the C# compiler not create code which caches the delegate instance of Action(SomeMethod) in this case:

```<code>void MyMethod() {
   Decorator(SomeMethod);
}

void Decorator(Action a) { a(); }
void SomeMethod() { }
</code>```

It does it only when SomeMethod is static:

```<code>static void SomeMethod() { }
</code>```

EDIT:

To be clearer, let's take the following code:

```<code>class A {
    public void M1() {
       var b = new B();
       b.Decorate(M2);
    }

    public void M2() {
    }
}

class B {
    public void Decorate(Action a) {
        Console.WriteLine("Calling");
        a();
    }
}

</code>```

If you want to avoid the delegate allocation every time M1 is called, you can do it easily but it's quite ugly:

```<code>using System;

class A {
    Action _m2;

    public A() {
        _m2 = new Action(M2);
    }

    public void M1() {
       var b = new B();
       b.Decorate(_m2);
    }

     public void M2() {
     }
}

class B {
    public void Decorate(Action a) {
        Console.WriteLine("Calling");
        a();
    }
}
</code>```

So my question was, what's the reason the compiler cannot generate a similar code? I can't see any side effects.

I'm not saying there's no reason, the people working on the compiler are much smarter than I will probably ever be. I'm only looking to understand which scenarios this won't work.

答:
It can't cache it for instance methods because the target instance is part of the delegate, and it really wants to use a static field for the cache. A static method call that doesn't capture any variables etc can be cached very cheaply, but it gets a lot more complex when state is involved, and this counts as state.

Yes, I suppose is could use an instance field to cache () => this.SomeMethod(), but frankly, this being the target is a relatively rare case and doesn't solve the general problem.

However, it also only does this for lambda syntax, i.e. even if SomeMethod is static

Decorator(SomeMethod); // not cached
Decorator(() => SomeMethod()); // cached
```

<p>You can see the difference here</p>

<p>This is because the difference is detectable (different object refs vs same object ref) and could <em>in theory</em> lead to different program behavior in existing code that used the original (non-lambda) syntax; so the cache provision has not to-date been applied retrospectively to the old syntax. Compatibility reasons. This has been discussed for years, though; IMO it is one of those things like the change to <code>foreach</code> L-value captures, that could probably be changed without breaking the world as much as we imagine.</p>

<hr>

<p>To see the theoretical difference in an example based on the edited question:</p>

<pre class="lang-cs prettyprint-override"><code>using System;

class A
{
    static void Main()
    {
        var obj = new A();
        Console.WriteLine("With cache...");
        for (int i = 0; i < 5; i++) obj.WithCache();
        Console.WriteLine("And without cache...");
        for (int i = 0; i < 5; i++) obj.WithoutCache();
    }
    Action _m2;
    B b = new B();
    public void WithCache() => b.Decorate(_m2 ??= M2);
    public void WithoutCache() => b.Decorate(M2);
    public void M2() => Console.WriteLine("I'm M2");
}

 class B
{
    private object _last;
    public void Decorate(Action a)
    {
        if (_last != (object)a)
        {
            a();
            _last = a;
        }
        else
        {
            Console.WriteLine("No do-overs!");
        }
    }
}
</code>```

This currently outputs:

```<code>With cache...
I'm M2
No do-overs!
No do-overs!
No do-overs!
No do-overs!
And without cache...
I'm M2
I'm M2
I'm M2
I'm M2
I'm M2
</code>```

Body:
Why does the C# compiler not create code which caches the delegate instance of Action(SomeMethod) in this case:

void MyMethod() {
   Decorator(SomeMethod);
}

void Decorator(Action a) { a(); }
void SomeMethod() { }

It does it only when SomeMethod is static:

static void SomeMethod() { }

EDIT:

To be clearer, let's take the following code:

class A {
    public void M1() {
       var b = new B();
       b.Decorate(M2);
    }

    public void M2() {
    }
}

class B {
    public void Decorate(Action a) {
        Console.WriteLine("Calling");
        a();
    }
}

If you want to avoid the delegate allocation every time M1 is called, you can do it easily but it's quite ugly:

using System;

class A {
    Action _m2;

    public A() {
        _m2 = new Action(M2);
    }

    public void M1() {
       var b = new B();
       b.Decorate(_m2);
    }

     public void M2() {
     }
}

class B {
    public void Decorate(Action a) {
        Console.WriteLine("Calling");
        a();
    }
}

So my question was, what's the reason the compiler cannot generate a similar code? I can't see any side effects.

I'm not saying there's no reason, the people working on the compiler are much smarter than I will probably ever be. I'm only looking to understand which scenarios this won't work.

Body:
It can't cache it for instance methods because the target instance is part of the delegate, and it really wants to use a static field for the cache. A static method call that doesn't capture any variables etc can be cached very cheaply, but it gets a lot more complex when state is involved, and this counts as state.

Yes, I suppose is could use an instance field to cache () => this.SomeMethod(), but frankly, this being the target is a relatively rare case and doesn't solve the general problem.

However, it also only does this for lambda syntax, i.e. even if SomeMethod is static

Decorator(SomeMethod); // not cached
Decorator(() => SomeMethod()); // cached

You can see the difference here

This is because the difference is detectable (different object refs vs same object ref) and could in theory lead to different program behavior in existing code that used the original (non-lambda) syntax; so the cache provision has not to-date been applied retrospectively to the old syntax. Compatibility reasons. This has been discussed for years, though; IMO it is one of those things like the change to foreach L-value captures, that could probably be changed without breaking the world as much as we imagine.

To see the theoretical difference in an example based on the edited question:

using System;

class A
{
    static void Main()
    {
        var obj = new A();
        Console.WriteLine("With cache...");
        for (int i = 0; i < 5; i++) obj.WithCache();
        Console.WriteLine("And without cache...");
        for (int i = 0; i < 5; i++) obj.WithoutCache();
    }
    Action _m2;
    B b = new B();
    public void WithCache() => b.Decorate(_m2 ??= M2);
    public void WithoutCache() => b.Decorate(M2);
    public void M2() => Console.WriteLine("I'm M2");
}

 class B
{
    private object _last;
    public void Decorate(Action a)
    {
        if (_last != (object)a)
        {
            a();
            _last = a;
        }
        else
        {
            Console.WriteLine("No do-overs!");
        }
    }
}

This currently outputs:

With cache...
I'm M2
No do-overs!
No do-overs!
No do-overs!
No do-overs!
And without cache...
I'm M2
I'm M2
I'm M2
I'm M2
I'm M2


问:
python word frequencies for dictionary with values and key
I am a first-time learner of python, I understand how to use word frequencies to count the number of each unique variable of a list, like this

```<code>sentence = ['hello', 'people', 'are', 'the', 'most', 'common', 'word', 'people', 'use', 'for', 'language ', 'learning']

words_freq ={} #dictionary for the counts
for word in sentence:
    if word not in words_freq:

        words_freq[word] =1
    else:

        words_freq[word] +=1

print (words_freq)
</code>```

however, I wonder how could a word frequencies do on the dictionary by using a double for loop?

for example, I have a dictionary like this

```<code>Food = {
2015: ["Apple", "Milk", "Cookie", "Banana", "Orange" ],
2016: ["Potato", "Orange", "Chocolate", "Milk", "Mango"],
2017: ["Fish", "Potato", "Orange", "Mango", "Banana"],
2018: ["Beef", "Pork", "Fish", "Apple", "Cookie"],
2019: ["Pork", "Orange", "Apple", "Mango", "Chocolate"]
}
</code>```

how to do a word frequencies/count and print something like this? Or store the highest value in list form ?
apple : 3
milk : 2
orange : 3
..
..
..

答:
You don't need a double loop, but you can do something like this:</p>

```<code>food = {
    2015: ["Apple", "Milk", "Cookie", "Banana", "Orange" ],
    2016: ["Potato", "Orange", "Chocolate", "Milk", "Mango"],
    2017: ["Fish", "Potato", "Orange", "Mango", "Banana"],
    2018: ["Beef", "Porn", "Fish", "Apple", "Cookie"],
    2019: ["Pork", "Orange", "Apple", "Mango", "Chocolate"]
}

words_freq = {}
for year in food.keys():
    for fruit in food[year]:

        if fruit in words_freq.keys():
            words_freq[fruit] += 1
        else:
            words_freq[fruit] = 1
</code>```

Body:
I am a first-time learner of python, I understand how to use word frequencies to count the number of each unique variable of a list, like this

sentence = ['hello', 'people', 'are', 'the', 'most', 'common', 'word', 'people', 'use', 'for', 'language ', 'learning']

words_freq ={} #dictionary for the counts
for word in sentence:
    if word not in words_freq:

        words_freq[word] =1
    else:

        words_freq[word] +=1

print (words_freq)

however, I wonder how could a word frequencies do on the dictionary by using a double for loop?

for example, I have a dictionary like this

Food = {
2015: ["Apple", "Milk", "Cookie", "Banana", "Orange" ],
2016: ["Potato", "Orange", "Chocolate", "Milk", "Mango"],
2017: ["Fish", "Potato", "Orange", "Mango", "Banana"],
2018: ["Beef", "Pork", "Fish", "Apple", "Cookie"],
2019: ["Pork", "Orange", "Apple", "Mango", "Chocolate"]
}

how to do a word frequencies/count and print something like this? Or store the highest value in list form ?
apple : 3
milk : 2
orange : 3
..
..
..

Body:
You don't need a double loop, but you can do something like this:

food = {
    2015: ["Apple", "Milk", "Cookie", "Banana", "Orange" ],
    2016: ["Potato", "Orange", "Chocolate", "Milk", "Mango"],
    2017: ["Fish", "Potato", "Orange", "Mango", "Banana"],
    2018: ["Beef", "Porn", "Fish", "Apple", "Cookie"],
    2019: ["Pork", "Orange", "Apple", "Mango", "Chocolate"]
}

words_freq = {}
for year in food.keys():
    for fruit in food[year]:

        if fruit in words_freq.keys():
            words_freq[fruit] += 1
        else:
            words_freq[fruit] = 1


问:
What is best way to create elements and append them to the dom in jquery?
Let's say I am adding li elements in javascript code with jQuery.

Example 1:

```<code>for(var i=0 i<=5; i++){

    var li = $("<li/>");
    li.html("teest "+i);
    $("#ulid").append(li);

}
</code>```

I've learned that the above example is a bad practice due to the fact that the loop rebuilds dom each time it hits append(li).

If that is the case, what is the best way to do the exact same thing as the above example?

答:
What you're doing is probably fine for the vast majority of use cases. Your code will eventually call the DOM appendChild function once for each li, and I'm pretty sure that's also what all of the answers so far will do. And again, it's probably fine, though it may cause a reflow each time.

In those situations where you absolutely, positively need to avoid causing a DOM reflow on each pass through the loop, you probably need a document fragment.

```<code>var i, li, frag = document.createDocumentFragment();
for(i=0; i<=5; i++){
    li = $("<li>" + "teest "+i + "</li>");
    frag.appendChild(li[0]);
}
$("#ulid").append(frag); // Or $("#ulid")[0].appendChild(frag);
</code>```

When you append a fragment, the fragment's children are appended, not the actual fragment. The advantage here being that being a single DOM call, you're giving the DOM engine the opportunity to add all the elements and only do a reflow at the end.

ContentLicense: CC BY-SA 3.0

Body:
Let's say I am adding li elements in javascript code with jQuery.

Example 1:

for(var i=0 i<=5; i++){

    var li = $("
");
    li.html("teest "+i);
    $("#ulid").append(li);

}

I've learned that the above example is a bad practice due to the fact that the loop rebuilds dom each time it hits append(li).

If that is the case, what is the best way to do the exact same thing as the above example?

Body:
What you're doing is probably fine for the vast majority of use cases. Your code will eventually call the DOM appendChild function once for each li, and I'm pretty sure that's also what all of the answers so far will do. And again, it's probably fine, though it may cause a reflow each time.

In those situations where you absolutely, positively need to avoid causing a DOM reflow on each pass through the loop, you probably need a document fragment.

var i, li, frag = document.createDocumentFragment();
for(i=0; i<=5; i++){
    li = $("<li>" + "teest "+i + "</li>");
    frag.appendChild(li[0]);
}
$("#ulid").append(frag); // Or $("#ulid")[0].appendChild(frag);

When you append a fragment, the fragment's children are appended, not the actual fragment. The advantage here being that being a single DOM call, you're giving the DOM engine the opportunity to add all the elements and only do a reflow at the end.


问:
javafx label message showing with timer does not work
So im trying to show a message in javafx on a label and then make it disapear after 1 second. Im able to show the message as desired but i cannot make it dissapear. Actually my problem is that i never appear. So if i use only this:

```<code>lbReserva.setText("RESERVA REALITZADA");
</code>```

Works as expected but obviously it just stay like that. So then i tried this:

```<code>        try {
        lbReserva.setText("RESERVA REALITZADA");
        TimeUnit.SECONDS.sleep(1);
        lbReserva.setText("");
    } catch (InterruptedException e) {
        System.err.format("IOException: %s%n", e);
    }
</code>```

But then the label it just never appears. I've tried placing the first set text outside right before the try block. I've tried placing the second set text just after the catch. In any case i got the same result, the label never appears, or probably appears and straight away dissapear. Any clues what im doing wrong? thank you so much in advance.

pd: i have tried using Thread.sleep instead of TimeUnit but i got the same result.

答:
Use PauseTransition.

```<code>import javafx.animation.PauseTransition;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;

public class TestingGround extends Application
{
    @Override
    public void start(Stage stage) throws Exception
    {
        Label label = new Label("Hello World!");
        PauseTransition wait = new PauseTransition(Duration.seconds(1));
        wait.setOnFinished((e) -> {
            label.setVisible(false);
        });
        wait.play();
        VBox root = new VBox(label);
        stage.setScene(new Scene(root, 700, 500));
        stage.show();
    }

    public static void main(String[] args)
    {
        launch(args);
    }
}
</code>```

Body:
So im trying to show a message in javafx on a label and then make it disapear after 1 second. Im able to show the message as desired but i cannot make it dissapear. Actually my problem is that i never appear. So if i use only this:

lbReserva.setText("RESERVA REALITZADA");

Works as expected but obviously it just stay like that. So then i tried this:

        try {
        lbReserva.setText("RESERVA REALITZADA");
        TimeUnit.SECONDS.sleep(1);
        lbReserva.setText("");
    } catch (InterruptedException e) {
        System.err.format("IOException: %s%n", e);
    }

But then the label it just never appears. I've tried placing the first set text outside right before the try block. I've tried placing the second set text just after the catch. In any case i got the same result, the label never appears, or probably appears and straight away dissapear. Any clues what im doing wrong? thank you so much in advance.

pd: i have tried using Thread.sleep instead of TimeUnit but i got the same result.

Body:
Use PauseTransition.

import javafx.animation.PauseTransition;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;

public class TestingGround extends Application
{
    @Override
    public void start(Stage stage) throws Exception
    {
        Label label = new Label("Hello World!");
        PauseTransition wait = new PauseTransition(Duration.seconds(1));
        wait.setOnFinished((e) -> {
            label.setVisible(false);
        });
        wait.play();
        VBox root = new VBox(label);
        stage.setScene(new Scene(root, 700, 500));
        stage.show();
    }

    public static void main(String[] args)
    {
        launch(args);
    }
}


问:
Is it possible to return js PROMISE value in selenium as the variable?
I do use JS script to get one thing via xmlhttprequests. I need to pass this value back to the selenium where I can proceed further actions. My code returns None all the time, eventhough the global variable has been assigned and returned. I read somewhere that it is impossible to retrieve raw PROMISE value ? </p>

```<code>    var request = ""

    function send(method,url,data){
        const xhr = new XMLHttpRequest();
        const promise = new Promise(function(resolve,reject){
            xhr.open(method, url)
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.onload = function(){
                const raw_content = String(xhr.response)
                const start_index = raw_content.indexOf("request")
                const end_index = raw_content.indexOf("</settings>")
                const x_request = raw_content.substring(start_index+("request=").length+1, end_index-3)
                resolve(x_request)
            };
            xhr.send(data)
        });
        return promise;
    };

    async function final(){
        await send("POST", "https://www.thecrims.com/login",data).then((responseData)=>{
            request = responseData
            return responseData
        });
    };

final();
return request
</code>```

<p>When I put the above code to driver.execute_script and attempt to print it, it returns nothing or None. Is there any another way to get this value out of it ? </p>

答:
Well, you have to make small change to your final method.

```<code>async function final(){
        const val = await send("POST", "https://www.thecrims.com/login",data).then((responseData)=>{
            request = responseData
            return responseData
        });
     return val;
    };
</code>```

This should return the value.

Here is the sample test I did to validate the scenario.

```<code>jsFunction1 = """window.send =function(method,url){ const xhr = new XMLHttpRequest();
        const promise = new Promise(function(resolve,reject){
            xhr.open(method, url)
            xhr.setRequestHeader("Content-type", "application/json");
            xhr.onload = function(){
                const raw_content = String(xhr.response)
                resolve(raw_content)
            };
            xhr.send()
        }); return promise }; """

jsFunction2 = """window.final =function(){const val =send("get","https://jsonplaceholder.typicode.com/users").then((responseData)=>{
            return responseData
        }); return val}; """

# load the function so that you can call where ever you want
driver.execute_script(jsFunction1)
driver.execute_script(jsFunction2)
value = driver.execute_script("return final()")
print(value)
</code>```

Body:
I do use JS script to get one thing via xmlhttprequests. I need to pass this value back to the selenium where I can proceed further actions. My code returns None all the time, eventhough the global variable has been assigned and returned. I read somewhere that it is impossible to retrieve raw PROMISE value ?

    var request = ""

    function send(method,url,data){
        const xhr = new XMLHttpRequest();
        const promise = new Promise(function(resolve,reject){
            xhr.open(method, url)
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.onload = function(){
                const raw_content = String(xhr.response)
                const start_index = raw_content.indexOf("request")
                const end_index = raw_content.indexOf("</settings>")
                const x_request = raw_content.substring(start_index+("request=").length+1, end_index-3)
                resolve(x_request)
            };
            xhr.send(data)
        });
        return promise;
    };

    async function final(){
        await send("POST", "https://www.thecrims.com/login",data).then((responseData)=>{
            request = responseData
            return responseData
        });
    };

final();
return request

When I put the above code to driver.execute_script and attempt to print it, it returns nothing or None. Is there any another way to get this value out of it ?

Body:
Well, you have to make small change to your final method.

async function final(){
        const val = await send("POST", "https://www.thecrims.com/login",data).then((responseData)=>{
            request = responseData
            return responseData
        });
     return val;
    };

This should return the value.

Here is the sample test I did to validate the scenario.

jsFunction1 = """window.send =function(method,url){ const xhr = new XMLHttpRequest();
        const promise = new Promise(function(resolve,reject){
            xhr.open(method, url)
            xhr.setRequestHeader("Content-type", "application/json");
            xhr.onload = function(){
                const raw_content = String(xhr.response)
                resolve(raw_content)
            };
            xhr.send()
        }); return promise }; """

jsFunction2 = """window.final =function(){const val =send("get","https://jsonplaceholder.typicode.com/users").then((responseData)=>{
            return responseData
        }); return val}; """

# load the function so that you can call where ever you want
driver.execute_script(jsFunction1)
driver.execute_script(jsFunction2)
value = driver.execute_script("return final()")
print(value)


问:
How to set different styles for Android and iOS in Ionic
Is it possible to set different styles when my app is on an IOS or Android device in HTML or CSS?

For example, IOS devices space out <ion-title> differently than Android devices.

答:
In that case you can use something like this.

```<code>.ios ion-title {
    color: black;
}
.md ion-title {
    color: blue;
}
</code>```

Also you can check it out the official documentation here Ionic Platform Style

Body:
In that case you can use something like this.

.ios ion-title {
    color: black;
}
.md ion-title {
    color: blue;
}

Also you can check it out the official documentation here Ionic Platform Style


问:
Error: Apple pay not completed
I have implemented apple pay in my iOS application using Passkit framework. I did all of  these things fully to set up apple pay. I am using sandbox account. I added cards in Wallet application and these cards are testing cards which I copied from this link. This code I am using:

```<code> print("\(((self.grandTotalLabel.text!).replacingOccurrences(of: "$", with: "")))")

        let paymentNetworks = [PKPaymentNetwork.amex]

        if PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: paymentNetworks){

            paymentRequest.supportedNetworks = paymentNetworks
            paymentRequest.merchantCapabilities = .capability3DS
            paymentRequest.requiredShippingAddressFields = [.all]
            paymentRequest.paymentSummaryItems = self.itemToSell(shipping: 10.0)

                            let sameDayShipping = PKShippingMethod(label: "Same day divilery", amount: 12.99)
            sameDayShipping.detail = "Same day divilery Detail"
            sameDayShipping.identifier = "sameDay"

            let twDaysShipping = PKShippingMethod(label: "Two days divilery", amount: 4.99)
            twDaysShipping.detail = "Two days divilery Detail"
            twDaysShipping.identifier = "twoDays"

            let freeShipping = PKShippingMethod(label: "Free shipping divilery", amount: 0.0)
            freeShipping.detail = "Free shipping divilery Detail"
            freeShipping.identifier = "freeShipping"

           // paymentRequest.shippingMethods = [sameDayShipping,twDaysShipping, freeShipping]
            let applePayVC = PKPaymentAuthorizationViewController(paymentRequest: paymentRequest)

            applePayVC?.delegate = self

            self.present(applePayVC!, animated: true) {

                print("ApplePayViewcontroller")

            }
        }
        else{

            print("Please set up for apple pay")

        }

func itemToSell(shipping:Float) -> [PKPaymentSummaryItem]{

        print(Double("\(((self.grandTotalLabel.text!).replacingOccurrences(of: "$", with: "")))") as Any)

        let dishItems = PKPaymentSummaryItem(label: "FoodKonnect", amount: NSDecimalNumber(string: "21.00"))
        let discount = PKPaymentSummaryItem(label: "Discount", amount: 1.0)
        let shipping = PKPaymentSummaryItem(label: "Shipping", amount: NSDecimalNumber(string: "\(shipping)"))

        let totalAmount = dishItems.amount.adding(discount.amount)

        let totalPrice = PKPaymentSummaryItem(label: "FoodKonnect application", amount: totalAmount)

        return [dishItems, discount,shipping, totalPrice]

    }
</code>```

These all delegates I am using of  PKPaymentAuthorizationViewControllerDelegate :

```<code>extension CartViewController:PKPaymentAuthorizationViewControllerDelegate{

    func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) {

        controller.dismiss(animated: true, completion: nil)

    }

   // @available(iOS 11.0, *)

    func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didSelectShippingContact contact: PKContact, completion: @escaping (PKPaymentAuthorizationStatus, [PKShippingMethod], [PKPaymentSummaryItem]) -> Void) {
        print("\(#function)")

    }
    @available(iOS 11.0, *)
    func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didSelect shippingMethod: PKShippingMethod, handler completion: @escaping (PKPaymentRequestShippingMethodUpdate) -> Void) {
        print("\(#function)")

    }

    @available(iOS 11.0, *)
    func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, handler completion: @escaping (PKPaymentAuthorizationResult) -> Void) {

        print("\(#function)")

    }

}
</code>```

Apple pay viewcontroller is showing and this screen is showing with a processing circle view.

But after few seconds I got this error message:

I am not able to figure what exactly I am doing wrong.

答:
There are still cases when you do have completion/handler properly called in PKPaymentAuthorizationViewControllerDelegate functions that expect this handler, but your internal payment API happen to be set to a longer timeout time than ApplePay dialog expects (as of iOS 13 it would timeout in around 30 secs).

In these cases you may get "Apple pay not completed" error in slow networks (try to block your API artificially to simulate such a situation).

A solution might be in proactively dismissing the ApplePay dialog yourself just before it gives up and shows the error. More details on how to do this can be found in this answer to a similar question being discussed.

Title: Error: Apple pay not completed

Body:
I have implemented apple pay in my iOS application using Passkit framework. I did all of  these things fully to set up apple pay. I am using sandbox account. I added cards in Wallet application and these cards are testing cards which I copied from this link. This code I am using:

 print("\(((self.grandTotalLabel.text!).replacingOccurrences(of: "$", with: "")))")

        let paymentNetworks = [PKPaymentNetwork.amex]

        if PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: paymentNetworks){

            paymentRequest.supportedNetworks = paymentNetworks
            paymentRequest.merchantCapabilities = .capability3DS
            paymentRequest.requiredShippingAddressFields = [.all]
            paymentRequest.paymentSummaryItems = self.itemToSell(shipping: 10.0)

                            let sameDayShipping = PKShippingMethod(label: "Same day divilery", amount: 12.99)
            sameDayShipping.detail = "Same day divilery Detail"
            sameDayShipping.identifier = "sameDay"

            let twDaysShipping = PKShippingMethod(label: "Two days divilery", amount: 4.99)
            twDaysShipping.detail = "Two days divilery Detail"
            twDaysShipping.identifier = "twoDays"

            let freeShipping = PKShippingMethod(label: "Free shipping divilery", amount: 0.0)
            freeShipping.detail = "Free shipping divilery Detail"
            freeShipping.identifier = "freeShipping"

           // paymentRequest.shippingMethods = [sameDayShipping,twDaysShipping, freeShipping]
            let applePayVC = PKPaymentAuthorizationViewController(paymentRequest: paymentRequest)

            applePayVC?.delegate = self

            self.present(applePayVC!, animated: true) {

                print("ApplePayViewcontroller")

            }
        }
        else{

            print("Please set up for apple pay")

        }

func itemToSell(shipping:Float) -> [PKPaymentSummaryItem]{

        print(Double("\(((self.grandTotalLabel.text!).replacingOccurrences(of: "$", with: "")))") as Any)

        let dishItems = PKPaymentSummaryItem(label: "FoodKonnect", amount: NSDecimalNumber(string: "21.00"))
        let discount = PKPaymentSummaryItem(label: "Discount", amount: 1.0)
        let shipping = PKPaymentSummaryItem(label: "Shipping", amount: NSDecimalNumber(string: "\(shipping)"))

        let totalAmount = dishItems.amount.adding(discount.amount)

        let totalPrice = PKPaymentSummaryItem(label: "FoodKonnect application", amount: totalAmount)

        return [dishItems, discount,shipping, totalPrice]

    }

These all delegates I am using of  PKPaymentAuthorizationViewControllerDelegate :

extension CartViewController:PKPaymentAuthorizationViewControllerDelegate{

    func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) {

        controller.dismiss(animated: true, completion: nil)

    }

   // @available(iOS 11.0, *)

    func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didSelectShippingContact contact: PKContact, completion: @escaping (PKPaymentAuthorizationStatus, [PKShippingMethod], [PKPaymentSummaryItem]) -> Void) {
        print("\(#function)")

    }
    @available(iOS 11.0, *)
    func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didSelect shippingMethod: PKShippingMethod, handler completion: @escaping (PKPaymentRequestShippingMethodUpdate) -> Void) {
        print("\(#function)")

    }

    @available(iOS 11.0, *)
    func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, handler completion: @escaping (PKPaymentAuthorizationResult) -> Void) {

        print("\(#function)")

    }

}

Apple pay viewcontroller is showing and this screen is showing with a processing circle view.

But after few seconds I got this error message:

I am not able to figure what exactly I am doing wrong.


问:
How do you include a CSRF token in a Vue.js application with a Spring Boot backend?
I'm trying to do a POST request to my backend REST API using the browser's Fetch API like this:

```<code>   submitRegistration() {
         const formElement = document.getElementById('register-form');
         fetch('http://localhost:8080/register', {
             method: 'POST',
             body: new FormData(formElement),
         });
     }
</code>```

I'm taking the data from this form:

```<code><v-form id="register-form" @submit.prevent="submitRegistration" class="text-center" ref="form" v-model="valid" lazy-validation>
    <v-text-field type="text" name="username" v-model="form.username" :counter="25" :rules="usernameRules" label="Username" required></v-text-field>
    <v-text-field type="password" name="userPassword" v-model="form.password" :counter="25" :rules="passwordRules" label="Password" required></v-text-field>
    <v-text-field type="text" name="userEmail" v-model="form.email" :rules="emailRules" label="E-mail" required></v-text-field>
    <v-btn type="submit" text class="primary">Register</v-btn>
</v-form>
</code>```

However, as a response I get 403 Forbidden by my backend server. The problem is the CSRF token but I have no idea how to generate it to include it in the POST request to the backend API.

EDIT: In Spring Boot, my CORS mapping is configured like this:

```<code>@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("http://localhost:9000").allowCredentials(true);
        }
    };
}
</code>```

I'm posting this because the Response object that is returned gives me a 403 status and is of type "cors" even though the error is resolved if I completely disable CSRF using HttpSecurity - http.csrf().disable();

答:
This could be solved by making a GET call first to the server and then following the solution here with the following additions / corrections:

In the submitRegistration() method, add the following at the top:

```<code>    // Do a fetch to GET the XSRF-TOKEN as a cookie
    fetch('http://localhost:8080/register');
    const csrfToken = this.getCookie('XSRF-TOKEN');
    const headers = new Headers({
        'X-XSRF-TOKEN': csrfToken
    });
</code>```

Our POST request now looks like this:

```<code>   fetch('http://localhost:8080/register', {
        method: 'POST',
        headers,
        credentials: 'include',
        body: new FormData(formElement),
    })
</code>```

In the backend, we need to add the following to our overriden configure() method:

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
</code>```

This tells the server to send back the CSRF token as a cookie called "XSRF-TOKEN" and reads the CSRF token from a header called "X-XSRF-TOKEN".

Body:
I'm trying to do a POST request to my backend REST API using the browser's Fetch API like this:

   submitRegistration() {
         const formElement = document.getElementById('register-form');
         fetch('http://localhost:8080/register', {
             method: 'POST',
             body: new FormData(formElement),
         });
     }

I'm taking the data from this form:

<v-form id="register-form" @submit.prevent="submitRegistration" class="text-center" ref="form" v-model="valid" lazy-validation>
    <v-text-field type="text" name="username" v-model="form.username" :counter="25" :rules="usernameRules" label="Username" required></v-text-field>
    <v-text-field type="password" name="userPassword" v-model="form.password" :counter="25" :rules="passwordRules" label="Password" required></v-text-field>
    <v-text-field type="text" name="userEmail" v-model="form.email" :rules="emailRules" label="E-mail" required></v-text-field>
    <v-btn type="submit" text class="primary">Register</v-btn>
</v-form>

However, as a response I get 403 Forbidden by my backend server. The problem is the CSRF token but I have no idea how to generate it to include it in the POST request to the backend API.

EDIT: In Spring Boot, my CORS mapping is configured like this:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("http://localhost:9000").allowCredentials(true);
        }
    };
}

I'm posting this because the Response object that is returned gives me a 403 status and is of type "cors" even though the error is resolved if I completely disable CSRF using HttpSecurity - http.csrf().disable();

Body:
This could be solved by making a GET call first to the server and then following the solution here with the following additions / corrections:

In the submitRegistration() method, add the following at the top:

    // Do a fetch to GET the XSRF-TOKEN as a cookie
    fetch('http://localhost:8080/register');
    const csrfToken = this.getCookie('XSRF-TOKEN');
    const headers = new Headers({
        'X-XSRF-TOKEN': csrfToken
    });

Our POST request now looks like this:

   fetch('http://localhost:8080/register', {
        method: 'POST',
        headers,
        credentials: 'include',
        body: new FormData(formElement),
    })

In the backend, we need to add the following to our overriden configure() method:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}

This tells the server to send back the CSRF token as a cookie called "XSRF-TOKEN" and reads the CSRF token from a header called "X-XSRF-TOKEN".


问:
Unreachable statement after conditional
The following code gives the error: Unreachable statement for current= current.getmNextNode();
 How can it be solved?

```<code>public int indexOf(E element) {

    Node current = head;
    for (int i = 0; i < size; i++) {
        if (current.getmElement().equals(element)) ;
        {
            return i;
        }
        current = current.getmNextNode();
    }

    return -1;
}
</code>```

答:
You have an extra semicolon between the if statement, and what is supposed to be its body. The way you wrote it, the return i; statement will be executed regardless of the result of the condition.

```<code>public int indexOf(E element) {
  Node current = head;

  for (int i = 0; i < size; i++) {
    if (current.getmElement().equals(element)) {
      return i;
    }

    current= current.getmNextNode();
  }
  return -1;
}
</code>```

Title: Unreachable statement after conditional

Body:
The following code gives the error: Unreachable statement for current= current.getmNextNode();
 How can it be solved?

public int indexOf(E element) {

    Node current = head;
    for (int i = 0; i < size; i++) {
        if (current.getmElement().equals(element)) ;
        {
            return i;
        }
        current = current.getmNextNode();
    }

    return -1;
}

Body:
You have an extra semicolon between the if statement, and what is supposed to be its body. The way you wrote it, the return i; statement will be executed regardless of the result of the condition.

public int indexOf(E element) {
  Node current = head;

  for (int i = 0; i < size; i++) {
    if (current.getmElement().equals(element)) {
      return i;
    }

    current= current.getmNextNode();
  }
  return -1;
}


问:
Website skipping when new element is loaded
I have a fixed header at my page which apears when user scroll down the page (170 pixels down when page width is less then 992 pixels and 320 pixels down when page is greater then 992 pixels width).

In the moment when header apears there is a "jump" / "skips" of the whole page on the height of this header so it's looks bad - content goes rapiddly down.
How to remove this jump and display smoothly fixed header?

This is a code :

```<code>
   function responsivecolumn(){

     if ($(document).width() <= 991)
     {
       $('.container #columns_inner #left-column').appendTo('.container #columns_inner');
       // ---------------- Fixed header responsive ----------------------
       $(window).bind('scroll', function () {
         if ($(window).scrollTop() > 170) {
           $('.header-top').addClass('fixed');
         } else {
           $('.header-top').removeClass('fixed');
         }
       });
     }
     else if($(document).width() >= 992)
     {
       $('.container #columns_inner #left-column').prependTo('.container #columns_inner');
       $(window).bind('scroll', function () {
         if ($(window).scrollTop() > 320) {
           $('.header-top').addClass('fixed');
         } else {
           $('.header-top').removeClass('fixed');
         }
       });
     }
   }
   $(document).ready(function(){responsivecolumn();});
   $(window).resize(function(){responsivecolumn();});

</code>```

```<code>#header .header-top.fixed {
   position: fixed;
   top: 0;
   width: 100%;
   margin: 0px;
   background: #FFF;
   padding: 3px 0px;
   z-index: 9999;
   left: 0px;
   border-bottom: 1px solid #ddd;
   -webkit-transition: all 0.3s ease;
   -moz-transition: all 0.3s ease;
   -o-transition: all 0.3s ease;
   transition: all 0.3s ease;
   -webkit-box-shadow: 0 0px 2px 1px rgba(0, 0, 0, 0.1);
   box-shadow: 0 0px 2px 1px rgba(0, 0, 0, 0.1);

</code>```

```<code>#header .header-top {
   padding-bottom: 0px;
   min-height: 48px;
}
</code>```

答:
Thanks for help. Solution is simple:</p>

```<code>function responsivecolumn(){

  if ($(document).width() <= 991)
  {
    $('.container #columns_inner #left-column').appendTo('.container #columns_inner');
    // ---------------- Fixed header responsive ----------------------
    $(window).bind('scroll', function () {
      if ($(window).scrollTop() > 170) {
        $('.header-top').addClass('fixed');
        $('#header').css('padding-top', '48px');
      } else {
        $('.header-top').removeClass('fixed');
        $('#header').css('padding-top', '0px');
      }
    });
  }
  else if($(document).width() >= 992)
  {
    $('.container #columns_inner #left-column').prependTo('.container #columns_inner');
    $(window).bind('scroll', function () {
      if ($(window).scrollTop() > 320) {
        $('.header-top').addClass('fixed');
        $('#header').css('padding-top', '48px');
      } else {
        $('.header-top').removeClass('fixed');
         $('#header').css('padding-top', '0px');
      }
    });
  }
}
$(document).ready(function(){responsivecolumn();});
$(window).resize(function(){responsivecolumn();});

</code>```

Body:
I have a fixed header at my page which apears when user scroll down the page (170 pixels down when page width is less then 992 pixels and 320 pixels down when page is greater then 992 pixels width).

In the moment when header apears there is a "jump" / "skips" of the whole page on the height of this header so it's looks bad - content goes rapiddly down.
How to remove this jump and display smoothly fixed header?

This is a code :

   function responsivecolumn(){

     if ($(document).width() <= 991)
     {
       $('.container #columns_inner #left-column').appendTo('.container #columns_inner');
       // ---------------- Fixed header responsive ----------------------
       $(window).bind('scroll', function () {
         if ($(window).scrollTop() > 170) {
           $('.header-top').addClass('fixed');
         } else {
           $('.header-top').removeClass('fixed');
         }
       });
     }
     else if($(document).width() >= 992)
     {
       $('.container #columns_inner #left-column').prependTo('.container #columns_inner');
       $(window).bind('scroll', function () {
         if ($(window).scrollTop() > 320) {
           $('.header-top').addClass('fixed');
         } else {
           $('.header-top').removeClass('fixed');
         }
       });
     }
   }
   $(document).ready(function(){responsivecolumn();});
   $(window).resize(function(){responsivecolumn();});

#header .header-top.fixed {
   position: fixed;
   top: 0;
   width: 100%;
   margin: 0px;
   background: #FFF;
   padding: 3px 0px;
   z-index: 9999;
   left: 0px;
   border-bottom: 1px solid #ddd;
   -webkit-transition: all 0.3s ease;
   -moz-transition: all 0.3s ease;
   -o-transition: all 0.3s ease;
   transition: all 0.3s ease;
   -webkit-box-shadow: 0 0px 2px 1px rgba(0, 0, 0, 0.1);
   box-shadow: 0 0px 2px 1px rgba(0, 0, 0, 0.1);

#header .header-top {
   padding-bottom: 0px;
   min-height: 48px;
}

Body:
Thanks for help. Solution is simple:

function responsivecolumn(){

  if ($(document).width() <= 991)
  {
    $('.container #columns_inner #left-column').appendTo('.container #columns_inner');
    // ---------------- Fixed header responsive ----------------------
    $(window).bind('scroll', function () {
      if ($(window).scrollTop() > 170) {
        $('.header-top').addClass('fixed');
        $('#header').css('padding-top', '48px');
      } else {
        $('.header-top').removeClass('fixed');
        $('#header').css('padding-top', '0px');
      }
    });
  }
  else if($(document).width() >= 992)
  {
    $('.container #columns_inner #left-column').prependTo('.container #columns_inner');
    $(window).bind('scroll', function () {
      if ($(window).scrollTop() > 320) {
        $('.header-top').addClass('fixed');
        $('#header').css('padding-top', '48px');
      } else {
        $('.header-top').removeClass('fixed');
         $('#header').css('padding-top', '0px');
      }
    });
  }
}
$(document).ready(function(){responsivecolumn();});
$(window).resize(function(){responsivecolumn();});


问:
how to make an iphone application which works only in a specific wifi network
hi  i want to make an application which could work only a particular ip(network).

not in other wifi reachable by iphone.

please help me in this.

thanks

答:
I was curious about this as well. The posts below explain things in more detail. There are undocumented ways of getting WiFi information, but it'll get your app rejected on the iTunes Store.

Can the iPhone SDK obtain the Wi-Fi SSID currently connected to?

Accessing iPhone WiFi Information via SDK


问:
Insert daily table to main table and update row in main table if key exists
I am attempting to insert a daily table to a main table that has primary keys in it. I have the following architecture:

A python scripts that generates data in a pandas dataframe-> drops the daily table -> pushes to the daily table -> pushes the data from the daily table to the main table.

I cannot drop the main table but I can drop the daily table. At the moment I am using the following query to perform this:

```<code> REPLACE INTO
    mydb.{to_table}
 SELECT
    *
 FROM
     mydb.{from_table};
</code>```

but I am getting the following error message:

```<code>ERROR (1062, "Duplicate entry '2147483647' for key 'PRIMARY'") with sql
                REPLACE INTO
                    mydb.book_authors_v2
                SELECT
                    *
                FROM
                    mybd.books_authors_v2_daily;
</code>```

I've tried using INSERT ... UPDATE ON DUPLICATE KEY but it did not manage to get it to work.

Is there any way of inserting the new rows from the daily table to the main table and updating the existing rows in the main table? There are nearly daily changes to the structure of the table, I would like to avoid having to manually define the columns.

答:
Yes, this looks like a good use case for the the INSERT ... ON DUPLICATE KEY syntax.

Assuming that the primary key of your table is called id, and you have 3 other columns col1, col2, col3 that you want to update on duplicate id, that would look like:

```<code>insert into mydb.book_authors_v2(id, col1, col2, col3)
select id, col1, col2, col3
from mybd.books_authors_v2_daily d
on duplicate key update set col1 = d.col1, col2 = d.col2, col3 = d.col3
</code>```

Body:
I am attempting to insert a daily table to a main table that has primary keys in it. I have the following architecture:

A python scripts that generates data in a pandas dataframe-> drops the daily table -> pushes to the daily table -> pushes the data from the daily table to the main table.

I cannot drop the main table but I can drop the daily table. At the moment I am using the following query to perform this:

 REPLACE INTO
    mydb.{to_table}
 SELECT
    *
 FROM
     mydb.{from_table};

but I am getting the following error message:

ERROR (1062, "Duplicate entry '2147483647' for key 'PRIMARY'") with sql
                REPLACE INTO
                    mydb.book_authors_v2
                SELECT
                    *
                FROM
                    mybd.books_authors_v2_daily;

I've tried using INSERT ... UPDATE ON DUPLICATE KEY but it did not manage to get it to work.

Is there any way of inserting the new rows from the daily table to the main table and updating the existing rows in the main table? There are nearly daily changes to the structure of the table, I would like to avoid having to manually define the columns.

Body:
Yes, this looks like a good use case for the the INSERT ... ON DUPLICATE KEY syntax.

Assuming that the primary key of your table is called id, and you have 3 other columns col1, col2, col3 that you want to update on duplicate id, that would look like:

insert into mydb.book_authors_v2(id, col1, col2, col3)
select id, col1, col2, col3
from mybd.books_authors_v2_daily d
on duplicate key update set col1 = d.col1, col2 = d.col2, col3 = d.col3


问:
React native API data problem: TypeError:undefined is not a function
I'm having some trouble accessing an API that return a JSON. I want to list the information from the API on the screen but i'm getting that error : TypeError:undefined is not a function(near '... this.state.dataSource.map...').
That's what the API is returning:

```<code>{"rates":
{"CAD":1.3229349331,"HKD":7.7674203969,"ISK":127.0881402861,"PHP":50.564836179,"DKK":6.8944162437,
"HUF":308.8509460083,"CZK":22.882325796,"GBP":0.7682325796,"RON":4.4086755884,"SEK":9.7206275958,
"IDR":13652.496538994,"INR":71.3816335948,"BRL":4.3137055838,"RUB":63.4567604984,"HRK":6.8726349792,
"JPY":109.875403784,"THB":31.1748961698,"CHF":0.9820950623,"EUR":0.9229349331,"MYR":4.144993078,
"BGN":1.8050761421,"TRY":6.0491001384,"CNY":6.9815413013,"NOK":9.2637748039,"NZD":1.5564374712,
"ZAR":14.9603137979,"USD":1.0,"MXN":18.5734194739,"SGD":1.3887401938,"AUD":1.4886017536,
"ILS":3.4269497,"KRW":1183.848638671,"PLN":3.9335486848},
"base":"USD",
"date":"2020-02-17"}
</code>```

Code:

```<code>import React, { Component } from 'react';
import { StyleSheet, Text, View, ActivityIndicator } from 'react-native';

export default class ConvertScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      dataSource: []
    }
  }

  //API
  componentDidMount() {
    return fetch("https://api.exchangeratesapi.io/latest?base=USD")
      .then((response) => response.json())
      .then((responseJson) => {

        this.setState({
          isLoading: false,
          dataSource:responseJson.rates
        })
      })
      .catch((error) => {
        return error
      })
  }
  render() {
    if (!this.state.isLoading) {
      return (
        <View style={style.container}>
          <View>
              {this.state.dataSource.map((item, id) => (
              <Text> {item} </Text>
            ))}
          </View>
        </View >
      );
    }

    else {

      return (
        <View style={style.container}>
          <View style={style.viewInit}>
            <ActivityIndicator />
          </View>
        </View>
      );
    }
  }
}
</code>```

How to iterate over the 'rates' data from the API?

答:
You're getting this error because the .map function is only available on array.

It is {} but you are expecting [] so you may need to return array of a given object's own enumerable string-keyed property [key, value] pairs using Object.entries(obj):

```<code>Object.entries(stats).map(([key, value]) => console.log(key, value))
</code>```

Using for..in loop is also a solution for your problem, it iterates over all enumerable properties of an object that are keyed by strings

```<code>for (const rate in rates) {
  console.log(`${rate}: ${rates[rate]}`);
}
</code>```

Body:
I'm having some trouble accessing an API that return a JSON. I want to list the information from the API on the screen but i'm getting that error : TypeError:undefined is not a function(near '... this.state.dataSource.map...').
That's what the API is returning:

{"rates":
{"CAD":1.3229349331,"HKD":7.7674203969,"ISK":127.0881402861,"PHP":50.564836179,"DKK":6.8944162437,
"HUF":308.8509460083,"CZK":22.882325796,"GBP":0.7682325796,"RON":4.4086755884,"SEK":9.7206275958,
"IDR":13652.496538994,"INR":71.3816335948,"BRL":4.3137055838,"RUB":63.4567604984,"HRK":6.8726349792,
"JPY":109.875403784,"THB":31.1748961698,"CHF":0.9820950623,"EUR":0.9229349331,"MYR":4.144993078,
"BGN":1.8050761421,"TRY":6.0491001384,"CNY":6.9815413013,"NOK":9.2637748039,"NZD":1.5564374712,
"ZAR":14.9603137979,"USD":1.0,"MXN":18.5734194739,"SGD":1.3887401938,"AUD":1.4886017536,
"ILS":3.4269497,"KRW":1183.848638671,"PLN":3.9335486848},
"base":"USD",
"date":"2020-02-17"}

Code:

import React, { Component } from 'react';
import { StyleSheet, Text, View, ActivityIndicator } from 'react-native';

export default class ConvertScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      dataSource: []
    }
  }

  //API
  componentDidMount() {
    return fetch("https://api.exchangeratesapi.io/latest?base=USD")
      .then((response) => response.json())
      .then((responseJson) => {

        this.setState({
          isLoading: false,
          dataSource:responseJson.rates
        })
      })
      .catch((error) => {
        return error
      })
  }
  render() {
    if (!this.state.isLoading) {
      return (
        <View style={style.container}>
          <View>
              {this.state.dataSource.map((item, id) => (
              <Text> {item} </Text>
            ))}
          </View>
        </View >
      );
    }

    else {

      return (
        <View style={style.container}>
          <View style={style.viewInit}>
            <ActivityIndicator />
          </View>
        </View>
      );
    }
  }
}

How to iterate over the 'rates' data from the API?

Body:
You're getting this error because the .map function is only available on array.

It is {} but you are expecting [] so you may need to return array of a given object's own enumerable string-keyed property [key, value] pairs using Object.entries(obj):

Object.entries(stats).map(([key, value]) => console.log(key, value))

Using for..in loop is also a solution for your problem, it iterates over all enumerable properties of an object that are keyed by strings

for (const rate in rates) {
  console.log(`${rate}: ${rates[rate]}`);
}


问:
Django Choice Field HTML Custom Output
I'm currently working on a Django project and I'm facing a bit of headache. I need to "convert" an HTML page (form) to a proper functioning Django Form App. The problem comes exactly in the ChoiceField (the two choices Manhã and Tarde). On the left, it's the Django Form HTML output and on the right, there's the original HTML page. The styling is different and I can't figure out how I can make them equal. Also, I wanted to make them horizontally aligned, but Django it's not so flexible as I thought in this matter.

I hope you can give me clear tips and light in this strange darkness, I have a couple of frontend skills but nothing above the average.

答:
You could you use something like bootstrap.

Put both choices in a row (read bootstrap grid documentation). Also, could use bootstrap styling to change the appearance of choice field.

```<code><div class="row">
  <div class="col"></div>
  <div class="col"></div>
</div>
</code>```

Could also use Django Crispy forms, there's tutorials online on how to use it.

Title: Django Choice Field HTML Custom Output

Body:
You could you use something like bootstrap.

Put both choices in a row (read bootstrap grid documentation). Also, could use bootstrap styling to change the appearance of choice field.

<div class="row">
  <div class="col"></div>
  <div class="col"></div>
</div>

Could also use Django Crispy forms, there's tutorials online on how to use it.


问:
Page count of Pdf with Java
at the moment I am using itext to read the page count of a pdf. This takes quite long because the lib seems to scan the whole file.

Is the page information somewhere in the header of the pdf, or is a full filescan needed?

答:
```<code>PdfReader document = new PdfReader(new FileInputStream(new File("filename")));
int noPages = document.getNumberOfPages();
</code>```

Title: Page count of Pdf with Java


问:
Slow MariaDB when Query Joining Million of Records
I installed a plug in and I have done optimisation on the back end (SSD, single column indexing for columns called in GROUP BY  & WHERE)
but when running this query

```<code>SELECT  u.user_id, u.profile_page_id, u.server_id AS user_server_id, u.user_name, u.full_name, u.gender, u.user_image, u.is_invisible, u.user_group_id, u.language_id, u.birthday, u.country_iso, m.*
FROM(
(SELECT m.*
FROM phpfox_channel_video AS m
INNER JOIN phpfox_channel_category AS mc
    ON(mc.category_id = mc.category_id)
INNER JOIN phpfox_channel_category_data AS mcd
    ON(mcd.video_id = m.video_id)

WHERE m.in_process = 0 AND m.view_id = 0 AND m.module_id = 'videochannel' AND m.item_id = 0 AND m.privacy IN(0) AND mcd.category_id = 17
GROUP BY m.video_id
ORDER BY m.time_stamp DESC
)) AS m
JOIN phpfox_user AS u
    ON(u.user_id = m.user_id)

ORDER BY m.time_stamp DESC
LIMIT 24;
</code>```

it takes 20 seconds, while changing it to this instead

```<code>SELECT  u.user_id, u.profile_page_id, u.server_id AS user_server_id, u.user_name, u.full_name, u.gender, u.user_image, u.is_invisible, u.user_group_id, u.language_id, u.birthday, u.country_iso, m.*
FROM(
(SELECT  m.*
FROM phpfox_channel_video AS m
INNER JOIN phpfox_channel_category_data AS mcd
    ON(mcd.video_id = m.video_id AND mcd.category_id = 17)
WHERE m.in_process = 0 AND m.view_id = 0 AND m.module_id = 'videochannel' AND m.item_id = 0 AND m.privacy IN(0)
GROUP BY m.video_id
ORDER BY m.time_stamp DESC
)) AS m
JOIN phpfox_user AS u
    ON(u.user_id = m.user_id)

ORDER BY m.time_stamp DESC
LIMIT 24;
</code>```

This runs about 5-6 seconds

The phpfox_channel_video contains 2 million rows (and will keep on adding quickly, its a social media site and user can upload files too) so caching isn't quite useful (but activated).

Any hints on how to optimise this ? I have minimum experience with MariaDB/MySQL as I've been accustomed to MS SQL for big data, and creating my own structure. Any recommended method without needing much altering to the tables (adding tables is OK).

Or should I need to restructure the PHP & table to optimise the query to be below 1 second / query.
Thank you!

I found these links
http://mysql.rjweb.org/doc.php/memory &
http://mysql.rjweb.org/doc.php/ricksrots#indexing

Are they still relevant ?

attached is the explain results
And as for the Index, the current config is set to index every column is stated as an index key, all all the tables involved in the query above.

Would a print out of my current server configuration be helpful ? Thanks !

答:
I managed to clean up the query, after checking the table, turns out that

```<code>WHERE m.in_process = 0
  AND m.view_id = 0
  AND m.module_id = 'videochannel'
  AND m.item_id = 0
  AND m.privacy IN(0)
</code>```

Doesn't need to be run, because all the table matches that condition .. (for the current case of this website).. So I just optimize those long queries. And Manage to hit < 1 second now ..

Body:
I installed a plug in and I have done optimisation on the back end (SSD, single column indexing for columns called in GROUP BY  & WHERE)
but when running this query

SELECT  u.user_id, u.profile_page_id, u.server_id AS user_server_id, u.user_name, u.full_name, u.gender, u.user_image, u.is_invisible, u.user_group_id, u.language_id, u.birthday, u.country_iso, m.*
FROM(
(SELECT m.*
FROM phpfox_channel_video AS m
INNER JOIN phpfox_channel_category AS mc
    ON(mc.category_id = mc.category_id)
INNER JOIN phpfox_channel_category_data AS mcd
    ON(mcd.video_id = m.video_id)

WHERE m.in_process = 0 AND m.view_id = 0 AND m.module_id = 'videochannel' AND m.item_id = 0 AND m.privacy IN(0) AND mcd.category_id = 17
GROUP BY m.video_id
ORDER BY m.time_stamp DESC
)) AS m
JOIN phpfox_user AS u
    ON(u.user_id = m.user_id)

ORDER BY m.time_stamp DESC
LIMIT 24;

it takes 20 seconds, while changing it to this instead

SELECT  u.user_id, u.profile_page_id, u.server_id AS user_server_id, u.user_name, u.full_name, u.gender, u.user_image, u.is_invisible, u.user_group_id, u.language_id, u.birthday, u.country_iso, m.*
FROM(
(SELECT  m.*
FROM phpfox_channel_video AS m
INNER JOIN phpfox_channel_category_data AS mcd
    ON(mcd.video_id = m.video_id AND mcd.category_id = 17)
WHERE m.in_process = 0 AND m.view_id = 0 AND m.module_id = 'videochannel' AND m.item_id = 0 AND m.privacy IN(0)
GROUP BY m.video_id
ORDER BY m.time_stamp DESC
)) AS m
JOIN phpfox_user AS u
    ON(u.user_id = m.user_id)

ORDER BY m.time_stamp DESC
LIMIT 24;

This runs about 5-6 seconds

The phpfox_channel_video contains 2 million rows (and will keep on adding quickly, its a social media site and user can upload files too) so caching isn't quite useful (but activated).

Any hints on how to optimise this ? I have minimum experience with MariaDB/MySQL as I've been accustomed to MS SQL for big data, and creating my own structure. Any recommended method without needing much altering to the tables (adding tables is OK).

Or should I need to restructure the PHP & table to optimise the query to be below 1 second / query.
Thank you!

I found these links
http://mysql.rjweb.org/doc.php/memory &
http://mysql.rjweb.org/doc.php/ricksrots#indexing

Are they still relevant ?

attached is the explain results
And as for the Index, the current config is set to index every column is stated as an index key, all all the tables involved in the query above.

Would a print out of my current server configuration be helpful ? Thanks !

Body:
I managed to clean up the query, after checking the table, turns out that

WHERE m.in_process = 0
  AND m.view_id = 0
  AND m.module_id = 'videochannel'
  AND m.item_id = 0
  AND m.privacy IN(0)

Doesn't need to be run, because all the table matches that condition .. (for the current case of this website).. So I just optimize those long queries. And Manage to hit < 1 second now ..


问:
Sort a linked list, handling pairs as a single item
I am working on this challenge:

Sort a Linked list in increasing order by considering two nodes as a two digit number. (in place sorting)

4 ≤ n ≤ 1000

The length of the linked list is always even.

Example 1:

Input

  1→3→4→2→1→2

Output

  1→2→1→3→4→2

Explanation:

  12 > 13 > 42

Example 2:

Input

  1→3→0→3

Output

  0→3→1→3

Here is my linked list template implementation; which anyone can start coding:

```<code> class Node():
    def __init__(self,val):
        self.data = val
        self.next = None

 class Linkedlist():
    def __init__(self):
        self.head = None

    def add(self,x):
        t = Node(x)
        t.next = self.head
        self.head = t

    def display(self):
        p = self.head
        while p != None:
            print(p.data)
            p=p.next

    def sort(self):
        curr = self.head
        # your logic here

m = Linkedlist()
m.add(1)
m.add(3)
m.add(4)
m.add(2)
m.add(1)
m.add(2)
m.display()
</code>```

Which is the algorithm to sort the pairs in a linked list (in place), and how can I code it?

答:
First write a function that accepts a linked list of single digit nodes and merges each pair of adjacent single digit nodes into a linked list of half as many nodes, where each node contains a double digit number.

Then sort the resulting linked list using bubble sort, which is O(n^2), or mergesort, which is O(nlogn).

Then, if need be, write a third function that takes apart the double digit nodes and creates a new list of twice as many single digit nodes.

Doing it with two or three functions like this will really simplify the sort.

Body:
I am working on this challenge:

Sort a Linked list in increasing order by considering two nodes as a two digit number. (in place sorting)

4 ≤ n ≤ 1000

The length of the linked list is always even.

Example 1:

Input

  1→3→4→2→1→2

Output

  1→2→1→3→4→2

Explanation:

  12 > 13 > 42

Example 2:

Input

  1→3→0→3

Output

  0→3→1→3

Here is my linked list template implementation; which anyone can start coding:

 class Node():
    def __init__(self,val):
        self.data = val
        self.next = None

 class Linkedlist():
    def __init__(self):
        self.head = None

    def add(self,x):
        t = Node(x)
        t.next = self.head
        self.head = t

    def display(self):
        p = self.head
        while p != None:
            print(p.data)
            p=p.next

    def sort(self):
        curr = self.head
        # your logic here

m = Linkedlist()
m.add(1)
m.add(3)
m.add(4)
m.add(2)
m.add(1)
m.add(2)
m.display()

Which is the algorithm to sort the pairs in a linked list (in place), and how can I code it?


问:
nisNetgroupTriple not returned by getent -s sss netgroup
I'm testing openldap as a source for ssh logins and sudo rules using sssd.

So far i can use LDAP to auth (password and key) and sudo based on rules from LDAP.

But i want to be able to use netgroups as well to control where users have access to login to.

When using ALL for the host in the LDAP sudo rule the user can sudo. If i create a nisNetgroup that i will use in the sudo rule then the user cannot sudo.

This is what i have in my sssd conf for netgroups:

```<code>sudo_provider = ldap

####-- netgroups
ldap_sudo_include_netgroups = True
ldap_netgroup_search_base = ou=HostGroups,dc=redacted,dc=com
ldap_netgroup_object_class = nisNetgroup
ldap_netgroup_triple = nisNetgroupTriple
</code>```

i have netgroup: sss in /etc/nsswitch.conf file

My nisNetgroup in LDAP:

```<code>dn: cn=blabla,ou=HostGroups,dc=redacted,dc=com
cn: blabla
nisNetgroupTriple: test-app01,,
objectClass: nisNetgroup
objectClass: top
</code>```

in sssd log i can see the triple beign recorded:

```<code>[sdap_attrs_add_ldap_attr] (0x2000): Adding netgroup triple [test-app01,,] to attributes of [blabla].
</code>```

But when i run getent i don't see the triple:

```<code>$getent -s sss netgroup blabla
blabla
</code>```

And the user cannot sudo.

Any help would be appreciated. Thanks.

答: Ok, the problem was with the triple, it needs to be encompassed by parentheses to work.</p>

Body:
I'm testing openldap as a source for ssh logins and sudo rules using sssd.

So far i can use LDAP to auth (password and key) and sudo based on rules from LDAP.

But i want to be able to use netgroups as well to control where users have access to login to.

When using ALL for the host in the LDAP sudo rule the user can sudo. If i create a nisNetgroup that i will use in the sudo rule then the user cannot sudo.

This is what i have in my sssd conf for netgroups:

sudo_provider = ldap

####-- netgroups
ldap_sudo_include_netgroups = True
ldap_netgroup_search_base = ou=HostGroups,dc=redacted,dc=com
ldap_netgroup_object_class = nisNetgroup
ldap_netgroup_triple = nisNetgroupTriple

i have netgroup: sss in /etc/nsswitch.conf file

My nisNetgroup in LDAP:

dn: cn=blabla,ou=HostGroups,dc=redacted,dc=com
cn: blabla
nisNetgroupTriple: test-app01,,
objectClass: nisNetgroup
objectClass: top

in sssd log i can see the triple beign recorded:

[sdap_attrs_add_ldap_attr] (0x2000): Adding netgroup triple [test-app01,,] to attributes of [blabla].

But when i run getent i don't see the triple:

$getent -s sss netgroup blabla
blabla

And the user cannot sudo.

Any help would be appreciated. Thanks.


问:
Replace one line of clob
I have clob variable in Oracle SQL containing something like this.

```<code><catalog>
   <book id="bk101">
      <author>Joe</author>
       <genre>Fantasy</genre>
      <title>XML Developer  Guide</title>
      <price>44.95</price>
   </book>
   <book id="bk102">
      <author>Gregor</author>
      <genre>Fantasy</genre>
      <title>Midnight Rain</title>
      <price>5.95</price>
   </book>
</catalog>
</code>```

I want to change Fantasy to something else, only when author's name is Gregor. I think that REGEXP_REPLACE function will be good for this but don't know how to use it properly in this case
Can you help me with it?

答:
After I did all this work, I discovered a stack overflow page with a more concise answer. Check out Oracle-XMLTYPE : How to update a value.

I am including two methods, a brute force replace method using straight SQL, followed by converting the CLOB from XML to row/column, doing the replace, and converting it back to XML.

Brute Force SQl

```<code>DECLARE
-- This probably isn't what you want as it converts all "Fantasy" to "Something Else"
-- if author Gregory appears anywhere in the XML
-- Define clob for test
l_clob                   CLOB;
-- Define text including string to replace
c_text          CONSTANT VARCHAR2( 512 ) := '<catalog>
<book id="bk101">
  <author>Joe</author>
   <genre>Fantasy</genre>
  <title>XML Developer  Guide</title>
  <price>44.95</price>
</book>
<book id="bk102">
  <author>Gregor</author>
  <genre>Fantasy</genre>
  <title>Midnight Rain</title>
  <price>5.95</price>
</book>
</catalog>';
-- Define text to replace
c_replace       CONSTANT VARCHAR2( 100 ) := '<genre>Fantasy</genre>';
--Define text to replace string
c_replacewith   CONSTANT VARCHAR2( 100 ) := '<genre>Something Else</genre>';
-- Define search string
c_search        CONSTANT VARCHAR2( 100 ) := '<author>Gregor</author>';
BEGIN
    -- Initialize l_clob
    DBMS_LOB.createtemporary( l_clob, TRUE );
    l_clob   := c_text;

    -- replace the text
    -- replace function works on strings and clobs
    IF DBMS_LOB.INSTR( l_clob, c_search ) > 0
    THEN
        l_clob   :=
            REPLACE( l_clob
                   , c_replace
                   , c_replacewith );
    END IF;

    -- Write the replace string out.
    -- put_line only outputs first 20,000 characters
    DBMS_OUTPUT.put_line( l_clob );
    DBMS_LOB.freetemporary( l_clob );
END;
</code>```

XML to table to XML

```<code>-- Create table with clob
CREATE TABLE deleteme_table
(
    xml_data    CLOB
);

-- Insert XML into table
INSERT INTO deleteme_table
     VALUES ( '<catalog>
   <book id="bk101">
      <author>Joe</author>
       <genre>Fantasy</genre>
      <title>XML Developer  Guide</title>
      <price>44.95</price>
   </book>
   <book id="bk102">
      <author>Gregor</author>
      <genre>Fantasy</genre>
      <title>Midnight Rain</title>
      <price>5.95</price>
   </book>
</catalog>' );

-- Do the conversion
WITH
    aset AS
        (-- convert xml value to row/column
         SELECT xt.*
           FROM deleteme_table  x
              , XMLTABLE( '/catalog/book'
                          PASSING xmltype( x.xml_data )
                          COLUMNS id VARCHAR2( 10 ) PATH '@id'
                                , author VARCHAR2( 30 ) PATH 'author'
                                , genre VARCHAR2( 30 ) PATH 'genre'
                                , title VARCHAR2( 30 ) PATH 'title'
                                , price NUMBER PATH 'price' ) xt),
    bset AS
        ( -- replace the value
         SELECT id
              , author
              , CASE WHEN author = 'Gregor' THEN 'Something Else' ELSE genre END     AS genre
              , title
              , price
           FROM aset)
-- convert results back to XML
SELECT XMLELEMENT( "catalog"
                 , XMLELEMENT( "book"
                             , xmlattributes( bset.id AS "id" )
                             , XMLELEMENT( "author", bset.author )
                             , XMLELEMENT( "genre", bset.genre )
                             , XMLELEMENT( "title", bset.title )
                             , XMLELEMENT( "price", bset.price ) ) )
  FROM bset;
</code>```

Title: Replace one line of clob

Body:
I have clob variable in Oracle SQL containing something like this.

<catalog>
   <book id="bk101">
      <author>Joe</author>
       <genre>Fantasy</genre>
      <title>XML Developer  Guide</title>
      <price>44.95</price>
   </book>
   <book id="bk102">
      <author>Gregor</author>
      <genre>Fantasy</genre>
      <title>Midnight Rain</title>
      <price>5.95</price>
   </book>
</catalog>

I want to change Fantasy to something else, only when author's name is Gregor. I think that REGEXP_REPLACE function will be good for this but don't know how to use it properly in this case
Can you help me with it?

Body:
After I did all this work, I discovered a stack overflow page with a more concise answer. Check out Oracle-XMLTYPE : How to update a value.

I am including two methods, a brute force replace method using straight SQL, followed by converting the CLOB from XML to row/column, doing the replace, and converting it back to XML.

Brute Force SQl

DECLARE
-- This probably isn't what you want as it converts all "Fantasy" to "Something Else"
-- if author Gregory appears anywhere in the XML
-- Define clob for test
l_clob                   CLOB;
-- Define text including string to replace
c_text          CONSTANT VARCHAR2( 512 ) := '<catalog>
<book id="bk101">
  <author>Joe</author>
   <genre>Fantasy</genre>
  <title>XML Developer  Guide</title>
  <price>44.95</price>
</book>
<book id="bk102">
  <author>Gregor</author>
  <genre>Fantasy</genre>
  <title>Midnight Rain</title>
  <price>5.95</price>
</book>
</catalog>';
-- Define text to replace
c_replace       CONSTANT VARCHAR2( 100 ) := '<genre>Fantasy</genre>';
--Define text to replace string
c_replacewith   CONSTANT VARCHAR2( 100 ) := '<genre>Something Else</genre>';
-- Define search string
c_search        CONSTANT VARCHAR2( 100 ) := '<author>Gregor</author>';
BEGIN
    -- Initialize l_clob
    DBMS_LOB.createtemporary( l_clob, TRUE );
    l_clob   := c_text;

    -- replace the text
    -- replace function works on strings and clobs
    IF DBMS_LOB.INSTR( l_clob, c_search ) > 0
    THEN
        l_clob   :=
            REPLACE( l_clob
                   , c_replace
                   , c_replacewith );
    END IF;

    -- Write the replace string out.
    -- put_line only outputs first 20,000 characters
    DBMS_OUTPUT.put_line( l_clob );
    DBMS_LOB.freetemporary( l_clob );
END;

XML to table to XML

-- Create table with clob
CREATE TABLE deleteme_table
(
    xml_data    CLOB
);

-- Insert XML into table
INSERT INTO deleteme_table
     VALUES ( '<catalog>
   <book id="bk101">
      <author>Joe</author>
       <genre>Fantasy</genre>
      <title>XML Developer  Guide</title>
      <price>44.95</price>
   </book>
   <book id="bk102">
      <author>Gregor</author>
      <genre>Fantasy</genre>
      <title>Midnight Rain</title>
      <price>5.95</price>
   </book>
</catalog>' );

-- Do the conversion
WITH
    aset AS
        (-- convert xml value to row/column
         SELECT xt.*
           FROM deleteme_table  x
              , XMLTABLE( '/catalog/book'
                          PASSING xmltype( x.xml_data )
                          COLUMNS id VARCHAR2( 10 ) PATH '@id'
                                , author VARCHAR2( 30 ) PATH 'author'
                                , genre VARCHAR2( 30 ) PATH 'genre'
                                , title VARCHAR2( 30 ) PATH 'title'
                                , price NUMBER PATH 'price' ) xt),
    bset AS
        ( -- replace the value
         SELECT id
              , author
              , CASE WHEN author = 'Gregor' THEN 'Something Else' ELSE genre END     AS genre
              , title
              , price
           FROM aset)
-- convert results back to XML
SELECT XMLELEMENT( "catalog"
                 , XMLELEMENT( "book"
                             , xmlattributes( bset.id AS "id" )
                             , XMLELEMENT( "author", bset.author )
                             , XMLELEMENT( "genre", bset.genre )
                             , XMLELEMENT( "title", bset.title )
                             , XMLELEMENT( "price", bset.price ) ) )
  FROM bset;


问:
Filterpredicate with json array filter
I have a filter that is pretty simple:

```<code>this.dataSource.filter = JSON.stringify({
    state: this.searchForm.controls['stateInputControl'].value,
    product: this.searchForm.controls['productInputControl'].value
});
</code>```

However, I need to add a filter predicate because I need to have an or statement for the state.  If I just had the state being passed, the filter predicate would be simple:

```<code>this.dataSource.filterPredicate = (data,filter:string ) => {
        return (data.state == filter || data.state == "AL")
      };
</code>```

However, the filter isn't just a string it's a json array. So I need to do something like this:

```<code>this.dataSource.filterPredicate = (data,filter:{state:string,product:string} ) => {
        return ((data.state == filter.state || data.state == "AL") && data.product == filter.product)
      };
</code>```

This throws an error however:

Type '(data: Guide, filter: { state: string; product: string; }) => boolean' is not assignable to type '(data: Guide, filter: string) => boolean'.

  Types of parameters 'filter' and 'filter' are incompatible.

  Type 'string' is not assignable to type '{ state: string; product: string; }'.

How do I use filterPredicate with a filter that is a json array?

答:
I determined the solution.  You simply take in the serialized JSON and then parse the JSON inside of the filter predicate declaration, like so:

```<code>this.dataSource.filterPredicate = (data,filter:string ) => {
        var s = JSON.Parse(filter);
        return ((data.state == s.state || data.state == "AL") && data.product == s.product)
      };
</code>```

filterPredicate should also handle null/unknown/blank values as well which are possible and will screw up filtering.  A better formatting of this filterpredicate would be:

```<code>     var s = JSON.parse(filter);
      if (s.state && s.state.length && data.state !== s.state && data.state !== 'AL' && data.state !== '') { return false }
      else if (s.product && s.product.length && data.product !== s.product) { return false }
      return true;
</code>```

Title: Filterpredicate with json array filter

Body:
I have a filter that is pretty simple:

this.dataSource.filter = JSON.stringify({
    state: this.searchForm.controls['stateInputControl'].value,
    product: this.searchForm.controls['productInputControl'].value
});

However, I need to add a filter predicate because I need to have an or statement for the state.  If I just had the state being passed, the filter predicate would be simple:

this.dataSource.filterPredicate = (data,filter:string ) => {
        return (data.state == filter || data.state == "AL")
      };

However, the filter isn't just a string it's a json array. So I need to do something like this:

this.dataSource.filterPredicate = (data,filter:{state:string,product:string} ) => {
        return ((data.state == filter.state || data.state == "AL") && data.product == filter.product)
      };

This throws an error however:

Type '(data: Guide, filter: { state: string; product: string; }) => boolean' is not assignable to type '(data: Guide, filter: string) => boolean'.

  Types of parameters 'filter' and 'filter' are incompatible.

  Type 'string' is not assignable to type '{ state: string; product: string; }'.

How do I use filterPredicate with a filter that is a json array?

Body:
I determined the solution.  You simply take in the serialized JSON and then parse the JSON inside of the filter predicate declaration, like so:

this.dataSource.filterPredicate = (data,filter:string ) => {
        var s = JSON.Parse(filter);
        return ((data.state == s.state || data.state == "AL") && data.product == s.product)
      };

filterPredicate should also handle null/unknown/blank values as well which are possible and will screw up filtering.  A better formatting of this filterpredicate would be:

     var s = JSON.parse(filter);
      if (s.state && s.state.length && data.state !== s.state && data.state !== 'AL' && data.state !== '') { return false }
      else if (s.product && s.product.length && data.product !== s.product) { return false }
      return true;


问:
React Navigation V5 Hide Bottom Tabs
I would like to be able to hide the tabs on a screen using React Native Navigation v5.

I've been reading the documentation but it doesn't seem like they've updated this for v5 and it refers to the < v4 way of doing things.

here is my code:

```<code>import Home from './components/Home';
import SettingsScreen from './components/Settings';
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { createStackNavigator } from '@react-navigation/stack';

const SettingsStack = createStackNavigator();
const ProfileStack  = createStackNavigator();

function SettingsStackScreen() {
    return (
        <SettingsStack.Navigator>
            <SettingsStack.Screen name="Settings" component={SettingsScreen} />
        </SettingsStack.Navigator>
    )
}

function ProfileStackScreen() {
    return (
        <ProfileStack.Navigator>
            <ProfileStack.Screen name="Home" component={Home} />
        </ProfileStack.Navigator>
    )
}

const Tab = createBottomTabNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Tab.Navigator>
        <Tab.Screen name="Home" component={ProfileStackScreen} />
        <Tab.Screen name="Settings" component={SettingsStackScreen} />
      </Tab.Navigator>
    </NavigationContainer>
  );
}
</code>```

Things I have tried:

Accessing the options of the function and hiding that way.

Passing tabBarVisible as a prop to the Screen.

What I am asking for is, what is the correct way of hiding tabs on screens in React Navigation v5.

答:
You have API reference exactly for this.
Read: tabBarVisible</p>

Title: React Navigation V5 Hide Bottom Tabs

Body:
I would like to be able to hide the tabs on a screen using React Native Navigation v5.

I've been reading the documentation but it doesn't seem like they've updated this for v5 and it refers to the < v4 way of doing things.

here is my code:

import Home from './components/Home';
import SettingsScreen from './components/Settings';
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { createStackNavigator } from '@react-navigation/stack';

const SettingsStack = createStackNavigator();
const ProfileStack  = createStackNavigator();

function SettingsStackScreen() {
    return (
        <SettingsStack.Navigator>
            <SettingsStack.Screen name="Settings" component={SettingsScreen} />
        </SettingsStack.Navigator>
    )
}

function ProfileStackScreen() {
    return (
        <ProfileStack.Navigator>
            <ProfileStack.Screen name="Home" component={Home} />
        </ProfileStack.Navigator>
    )
}

const Tab = createBottomTabNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Tab.Navigator>
        <Tab.Screen name="Home" component={ProfileStackScreen} />
        <Tab.Screen name="Settings" component={SettingsStackScreen} />
      </Tab.Navigator>
    </NavigationContainer>
  );
}

Things I have tried:

Accessing the options of the function and hiding that way.

Passing tabBarVisible as a prop to the Screen.

What I am asking for is, what is the correct way of hiding tabs on screens in React Navigation v5.