问:
Creating an async stream source
I have an expensive method to call for creating a batch of source items:

```<code>private Task<List<SourceItem>> GetUnprocessedBatch(int batchSize)
{
    //impl
}
</code>```

I want to populate new items only when there is no item to process(or it falls below a certain threshold). I couldn't figure out which Source method to use so far.

I have implemented a crude stream that would keep returning new items:

```<code>public class Stream
{
    private readonly Queue<SourceItem> scrapeAttempts;
    private int batchSize = 100;
    private int minItemCount = 10;

    public Stream()
    {
        scrapeAttempts = new Queue<SourceItem>();
    }

    public async Task<SourceItem> Next()
    {
        if (scrapeAttempts.Count < minItemCount)
        {
            var entryScrapeAttempts = await GetUnprocessedBatch(batchSize);
            entryScrapeAttempts.ForEach(attempt => scrapeAttempts.Enqueue(attempt));
        }

        return scrapeAttempts.Dequeue();
    }

}
</code>```

I expected Source.Task would work but it looks like it calls it only once. How can I create a source for this scenario?

答:
So, conceptually what you want is a Source stage, that fetches elements asynchronously in batches, buffers the batch and propagates events downstream one by one. When the buffer is close to being empty, we want to eagerly call the next fetch on the side thread (but not more than once), so it could complete while we're emptying current batch.

This sort of behavior will require building a custom GraphStage. One that could look like this:

```<code>sealed class PreFetch<T> : GraphStage<SourceShape<T>>
{
    private readonly int threshold;
    private readonly Func<Task<IEnumerable<T>>> fetch;
    private readonly Outlet<T> outlet = new Outlet<T>("prefetch");

    public PreFetch(int threshold, Func<Task<IEnumerable<T>>> fetch)
    {
        this.threshold = threshold;
        this.fetch = fetch;
        this.Shape = new SourceShape<T>(this.outlet);
    }

    public override SourceShape<T> Shape { get; }

    protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);

    private sealed class Logic : GraphStageLogic
    {
        public Logic(PreFetch<T> stage) : base(stage.Shape)
        {
            // queue for batched elements
            var queue = new Queue<T>();
            // flag which indicates, that pull from downstream was made,
            // but we didn't have any elements at that moment
            var wasPulled = false;
            // determines if fetch was already called
            var fetchInProgress = false;

            // in order to cooperate with async calls without data races,
            // we need to register async callbacks for success and failure scenarios
            var onSuccess = this.GetAsyncCallback<IEnumerable<T>>(batch =>
            {
                foreach (var item in batch) queue.Enqueue(item);
                if (wasPulled)
                {
                    // if pull was requested but not fulfilled, we need to push now, as we have elements
                    // it assumes that fetch returned non-empty batch
                    Push(stage.outlet, queue.Dequeue());
                    wasPulled = false;
                }
                fetchInProgress = false;
            });
            var onFailure = this.GetAsyncCallback<Exception>(this.FailStage);

            SetHandler(stage.outlet, onPull: () => {
                if (queue.Count < stage.threshold && !fetchInProgress)
                {
                    // if queue occupation reached bellow expected capacity
                    // call fetch on a side thread and handle its result asynchronously
                    stage.fetch().ContinueWith(task =>
                    {
                        // depending on if task was failed or not, we call corresponding callback
                        if (task.IsFaulted || task.IsCanceled)
                            onFailure(task.Exception as Exception ?? new TaskCanceledException(task));
                        else onSuccess(task.Result);
                    });
                    fetchInProgress = true;
                }

                // if queue is empty, we cannot push immediatelly, so we only mark
                // that pull request has been made but not fulfilled
                if (queue.Count == 0)
                    wasPulled = true;
                else
                {
                    Push(stage.outlet, queue.Dequeue());
                    wasPulled = false;
                }
            });
        }
    }
}
</code>```

Title: Creating an async stream source

Body:
I have an expensive method to call for creating a batch of source items:

private Task<List<SourceItem>> GetUnprocessedBatch(int batchSize)
{
    //impl
}

I want to populate new items only when there is no item to process(or it falls below a certain threshold). I couldn't figure out which Source method to use so far.

I have implemented a crude stream that would keep returning new items:

public class Stream
{
    private readonly Queue<SourceItem> scrapeAttempts;
    private int batchSize = 100;
    private int minItemCount = 10;

    public Stream()
    {
        scrapeAttempts = new Queue<SourceItem>();
    }

    public async Task<SourceItem> Next()
    {
        if (scrapeAttempts.Count < minItemCount)
        {
            var entryScrapeAttempts = await GetUnprocessedBatch(batchSize);
            entryScrapeAttempts.ForEach(attempt => scrapeAttempts.Enqueue(attempt));
        }

        return scrapeAttempts.Dequeue();
    }

}

I expected Source.Task would work but it looks like it calls it only once. How can I create a source for this scenario?

Body:
So, conceptually what you want is a Source stage, that fetches elements asynchronously in batches, buffers the batch and propagates events downstream one by one. When the buffer is close to being empty, we want to eagerly call the next fetch on the side thread (but not more than once), so it could complete while we're emptying current batch.

This sort of behavior will require building a custom GraphStage. One that could look like this:

sealed class PreFetch<T> : GraphStage<SourceShape<T>>
{
    private readonly int threshold;
    private readonly Func<Task<IEnumerable<T>>> fetch;
    private readonly Outlet<T> outlet = new Outlet<T>("prefetch");

    public PreFetch(int threshold, Func<Task<IEnumerable<T>>> fetch)
    {
        this.threshold = threshold;
        this.fetch = fetch;
        this.Shape = new SourceShape<T>(this.outlet);
    }

    public override SourceShape<T> Shape { get; }

    protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);

    private sealed class Logic : GraphStageLogic
    {
        public Logic(PreFetch<T> stage) : base(stage.Shape)
        {
            // queue for batched elements
            var queue = new Queue<T>();
            // flag which indicates, that pull from downstream was made,
            // but we didn't have any elements at that moment
            var wasPulled = false;
            // determines if fetch was already called
            var fetchInProgress = false;

            // in order to cooperate with async calls without data races,
            // we need to register async callbacks for success and failure scenarios
            var onSuccess = this.GetAsyncCallback<IEnumerable<T>>(batch =>
            {
                foreach (var item in batch) queue.Enqueue(item);
                if (wasPulled)
                {
                    // if pull was requested but not fulfilled, we need to push now, as we have elements
                    // it assumes that fetch returned non-empty batch
                    Push(stage.outlet, queue.Dequeue());
                    wasPulled = false;
                }
                fetchInProgress = false;
            });
            var onFailure = this.GetAsyncCallback<Exception>(this.FailStage);

            SetHandler(stage.outlet, onPull: () => {
                if (queue.Count < stage.threshold && !fetchInProgress)
                {
                    // if queue occupation reached bellow expected capacity
                    // call fetch on a side thread and handle its result asynchronously
                    stage.fetch().ContinueWith(task =>
                    {
                        // depending on if task was failed or not, we call corresponding callback
                        if (task.IsFaulted || task.IsCanceled)
                            onFailure(task.Exception as Exception ?? new TaskCanceledException(task));
                        else onSuccess(task.Result);
                    });
                    fetchInProgress = true;
                }

                // if queue is empty, we cannot push immediatelly, so we only mark
                // that pull request has been made but not fulfilled
                if (queue.Count == 0)
                    wasPulled = true;
                else
                {
                    Push(stage.outlet, queue.Dequeue());
                    wasPulled = false;
                }
            });
        }
    }
}


来源: stackexchange

问:
How can I remove this element from the list?
There are total 9 elements which contains the name of drinks. What I need to do is remove any elements that contains "Americano"

However, I am not able to debug my code and it keep shows an error. How can I remove list1's element [0,2,3,6] which contains "Americano"?

```<code>list1 = [ ['3', 'Americano', '7', '14000'], ['4', 'Smoothie_queen', '4', '12000'], ['5', 'Americano', '2', '4000'], ['6', 'Americano', '17', '34000'], ['7', 'Cafe_mocha', '4', '11200'], ['8', 'Cafe_latte', '11', '27500'], ['9', 'Americano', '17', '34000'], ['10', 'Amorparty', '2', '4000'], ['11', 'Plain_yogurt', '13', '45500']]

while True:
        if " Americano" in list1[i]:
            del list1[0]
    if i < x:
        i = i + 1
        continue

    if i >= x:
        break

print(list1)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
There are total 9 elements which contains the name of drinks. What I need to do is remove any elements that contains "Americano"

However, I am not able to debug my code and it keep shows an error. How can I remove list1's element [0,2,3,6] which contains "Americano"?

list1 = [ ['3', 'Americano', '7', '14000'], ['4', 'Smoothie_queen', '4', '12000'], ['5', 'Americano', '2', '4000'], ['6', 'Americano', '17', '34000'], ['7', 'Cafe_mocha', '4', '11200'], ['8', 'Cafe_latte', '11', '27500'], ['9', 'Americano', '17', '34000'], ['10', 'Amorparty', '2', '4000'], ['11', 'Plain_yogurt', '13', '45500']]

while True:
        if " Americano" in list1[i]:
            del list1[0]
    if i < x:
        i = i + 1
        continue

    if i >= x:
        break

print(list1)

Body:
if you don't want to be confused Here is Step by Step code

list1 = [['3', 'Americano', '7', '14000'], ['4', 'Smoothie_queen', '4', '12000'], ['5', 'Americano', '2', '4000'],
         ['6', 'Americano', '17', '34000'], ['7', 'Cafe_mocha', '4', '11200'], ['8', 'Cafe_latte', '11', '27500'],
         ['9', 'Americano', '17', '34000'], ['10', 'Amorparty', '2', '4000'], ['11', 'Plain_yogurt', '13', '45500']]
lis = []
for row in list1:
    if 'Americano' not in row:
        lis.append(row)
print lis

Output

[['4', 'Smoothie_queen', '4', '12000'], ['7', 'Cafe_mocha', '4', '11200'], ['8', 'Cafe_latte', '11', '27500'], ['10', 'Amorparty', '2', '4000'], ['11', 'Plain_yogurt', '13', '45500']]


问:
How do I create a proper while loop?
I'm trying to create a simple number guessing game. It's to my understanding that I can use a while loop as a proper goto function if the user input does not equal the number generated by the RNG. Included is the code I've created. What I'm trying to do is tell the program If x<y, print("Too low. Try again"), then loop back to ask the user for input. Same principle if x>y. When the number is guessed correctly, it's supposed to display a message, ask for a Y/N input, then close the program or loop back to the beginning. How would I go about doing this?

I've tried including a while loop, but I'm faced with the following problem: Let's say the RNG generates 50. If I guess 49, it prints the x<y message, asks for another input, but it will keep displayed the x<y message even if in the new input x>y or x==y.

Also, when the answer is guessed correctly, I'm not sure how to make it so the program restarts if they answer Y.

Lastly, when the game prompts users to answer Y/N, the terminal will display the letter "Y" for some reason before the user has a chance to input.

```<code>print()
print("Guess an integer between 1-100.")
import random
y=random.randint(1,101)
print(y)
x=int(input())
if x==y:
    print(x, "is correct! Would you like to try again? Y/N")
    if input("Y"):
        print("Too bad! This game isn't finished yet!")
        exit()
    if input("N"):
        print("Good! This game isn't finished yet!")
        exit()
else:
    if x<y:
        print("Too low. Try again.")
    if x>y:
        print("Too high. Try again.")
</code>```

答:
Ok, so I'm not sure how your system of if statements and while loops works, but I do know that you are using the input function incorrectly.

If you want to check that an input is equal to a thing, you should do: if input('>>> ') == 'a thing'

That will output >>>, the user can input their response, and it will return true if it is equal to a thing.

I think I know what this does, but I am not sure. I will include what I would do to do this at the end of this.

```<code>if x==y:
    print(x, "is correct! Would you like to try again? Y/N")
    if input("Y"):
        print("Too bad! This game isn't finished yet!")
        exit()
    if input("N"):
        print("Good! This game isn't finished yet!")
        exit()
while True:
    if x<y:
        print("Too low. Try again.")
        int(input())
    if x>y:
        print("Too high. Try again.")
        int(input())
</code>```

I think you are trying to check if the user can guess it in one go, and then tell them if their guess is too high or too low on any following guesses.
I would do it like this:

```<code>import random

print('guess a number game (1-100 range)')

y = random.randint(1, 101)

x = int(input('>>> '))

if x == y:
    print('yay, you got it first try')
    exit()
else:
    print('nope')
    while x != y:
        x = int(input('>>> '))
        if x < y:
            print('Too low!')
        elif x > y:
            print('Too high!')
        elif x == y:
            print('E P I C')
            exit()
</code>```

Here is an example output:

```<code>guess a number game (1-100 range)
>>> 48
nope
>>> 50
Too high!
>>> 25
Too low!
>>> 35
Too low!
>>> 45
Too high!
>>> 40
Too low!
>>> 44
E P I C
</code>```

I have not been on here in a while (haha), so this might not be the best answer. Hope this helps, though!

Title: How do I create a proper while loop?

Body:
I'm trying to create a simple number guessing game. It's to my understanding that I can use a while loop as a proper goto function if the user input does not equal the number generated by the RNG. Included is the code I've created. What I'm trying to do is tell the program If x<y, print("Too low. Try again"), then loop back to ask the user for input. Same principle if x>y. When the number is guessed correctly, it's supposed to display a message, ask for a Y/N input, then close the program or loop back to the beginning. How would I go about doing this?

I've tried including a while loop, but I'm faced with the following problem: Let's say the RNG generates 50. If I guess 49, it prints the x<y message, asks for another input, but it will keep displayed the x<y message even if in the new input x>y or x==y.

Also, when the answer is guessed correctly, I'm not sure how to make it so the program restarts if they answer Y.

Lastly, when the game prompts users to answer Y/N, the terminal will display the letter "Y" for some reason before the user has a chance to input.

print()
print("Guess an integer between 1-100.")
import random
y=random.randint(1,101)
print(y)
x=int(input())
if x==y:
    print(x, "is correct! Would you like to try again? Y/N")
    if input("Y"):
        print("Too bad! This game isn't finished yet!")
        exit()
    if input("N"):
        print("Good! This game isn't finished yet!")
        exit()
else:
    if x<y:
        print("Too low. Try again.")
    if x>y:
        print("Too high. Try again.")

Body:
Ok, so I'm not sure how your system of if statements and while loops works, but I do know that you are using the input function incorrectly.

If you want to check that an input is equal to a thing, you should do: if input('>>> ') == 'a thing'

That will output >>>, the user can input their response, and it will return true if it is equal to a thing.

I think I know what this does, but I am not sure. I will include what I would do to do this at the end of this.

if x==y:
    print(x, "is correct! Would you like to try again? Y/N")
    if input("Y"):
        print("Too bad! This game isn't finished yet!")
        exit()
    if input("N"):
        print("Good! This game isn't finished yet!")
        exit()
while True:
    if x<y:
        print("Too low. Try again.")
        int(input())
    if x>y:
        print("Too high. Try again.")
        int(input())

I think you are trying to check if the user can guess it in one go, and then tell them if their guess is too high or too low on any following guesses.
I would do it like this:

import random

print('guess a number game (1-100 range)')

y = random.randint(1, 101)

x = int(input('>>> '))

if x == y:
    print('yay, you got it first try')
    exit()
else:
    print('nope')
    while x != y:
        x = int(input('>>> '))
        if x < y:
            print('Too low!')
        elif x > y:
            print('Too high!')
        elif x == y:
            print('E P I C')
            exit()

Here is an example output:

guess a number game (1-100 range)
>>> 48
nope
>>> 50
Too high!
>>> 25
Too low!
>>> 35
Too low!
>>> 45
Too high!
>>> 40
Too low!
>>> 44
E P I C

I have not been on here in a while (haha), so this might not be the best answer. Hope this helps, though!


问:
Vector iterator
I have a vector like this

```<code>std::vector<Sprite*> mDrawings;
std::vector<Sprite*>::iterator it = mDrawings.begin();
</code>```

This gives an error

```<code>Error: no suitable user-defined conversion from std::_Vector_iterator<std::_Vector_val<Sprite *, std::allocator<Sprite *>>> to std::_Vector_iterator<std::_Vector_val<Sprite *, std::allocator<Sprite *>>> exists
</code>```

But if i do the following

```<code>typedef std::vector<Sprite*> list;
list mDrawings;
list::iterator it = mDrawings.begin();
</code>```

Then it works ???.

UPDATE:
Im sorry it seems like the error was generated because of errors not related to the current code. I just saw the IDE underline with red and i thought that was the reason my application would not compile.

答:
I think you pasted the wrong code - I think perhaps you did std::vector<Sprite>::iterator it = mDrawings.begin(); without the *

EDIT: In response to updated question:

Always look at the first compiler error - Your code, as posted on ideone, lacks an #include which makes Sprite visible.

ContentLicense: CC BY-SA 3.0

Title: Vector iterator

Body:
I have a vector like this

std::vector<Sprite*> mDrawings;
std::vector<Sprite*>::iterator it = mDrawings.begin();

This gives an error

Error: no suitable user-defined conversion from std::_Vector_iterator<std::_Vector_val<Sprite *, std::allocator<Sprite *>>> to std::_Vector_iterator<std::_Vector_val<Sprite *, std::allocator<Sprite *>>> exists

But if i do the following

typedef std::vector<Sprite*> list;
list mDrawings;
list::iterator it = mDrawings.begin();

Then it works ???.

UPDATE:
Im sorry it seems like the error was generated because of errors not related to the current code. I just saw the IDE underline with red and i thought that was the reason my application would not compile.


问:
Convert Float to String without losing precision - Java
I want to convert a Float number to String without losing its precision.

When I convert 40075016.68557849 to String, it is being represented as 4.0075016E7.

I need to get it represented exactly as the entered value, that is "40075016.68557849".

I've tried String.valueOf(), Float(40075016.68557849f).toString() but nothing is working in the proper way.

答:
If the number does not have to be human-readable then you can use Double.doubleToLongBits() and Double.longBitsToDouble() and then print the long. This preserves the exact bit pattern of the value. In particular, it preserves the exact pattern of a NaN, in case that is important.

Another option may be Double.toHexString().

If the number needs to be human readable then check this document. It explains that printing to 17 decimal digits (%.17g or %.17f) is enough to guarantee that reading back the string will produce the same number.


问:
Trove4j library cannot be resolved
I'm getting the following error when trying to compile my app:

```<code>FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':myProject'.
> Could not resolve all files for configuration ':myProject:classpath'.
   > Could not find org.jetbrains.trove4j:trove4j:20160824.
     Searched in the following locations:
         https://repo1.maven.org/maven2/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.pom
         https://repo1.maven.org/maven2/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.jar
         https://maven.fabric.io/public/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.pom
         https://maven.fabric.io/public/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.jar
         https://maven.google.com/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.pom
         https://maven.google.com/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.jar
     Required by:
         project :metam > com.android.tools.build:gradle:3.0.0-beta2 > com.android.tools.build:gradle-core:3.0.0-beta2 >
com.android.tools.lint:lint:26.0.0-beta2 > com.android.tools.lint:lint-checks:26.0.0-beta2 > com.android.tools.lint:lint-
api:26.0.0-beta2 > com.android.tools.external.com-intellij:intellij-core:26.0.0-beta2
</code>```

It appears a library the IDE needs is missing?

答:
Try to replace mavenCentral() with jcenter() in your build.gradle file

```<code>allprojects {
    repositories {

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

Title: Trove4j library cannot be resolved

Body:
I'm getting the following error when trying to compile my app:

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':myProject'.
> Could not resolve all files for configuration ':myProject:classpath'.
   > Could not find org.jetbrains.trove4j:trove4j:20160824.
     Searched in the following locations:
         https://repo1.maven.org/maven2/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.pom
         https://repo1.maven.org/maven2/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.jar
         https://maven.fabric.io/public/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.pom
         https://maven.fabric.io/public/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.jar
         https://maven.google.com/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.pom
         https://maven.google.com/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.jar
     Required by:
         project :metam > com.android.tools.build:gradle:3.0.0-beta2 > com.android.tools.build:gradle-core:3.0.0-beta2 >
com.android.tools.lint:lint:26.0.0-beta2 > com.android.tools.lint:lint-checks:26.0.0-beta2 > com.android.tools.lint:lint-
api:26.0.0-beta2 > com.android.tools.external.com-intellij:intellij-core:26.0.0-beta2

It appears a library the IDE needs is missing?

Body:
Try to replace mavenCentral() with jcenter() in your build.gradle file

allprojects {
    repositories {

        jcenter()
      //.......
    }
}


问:
How to make play and pause the video in react-native?
i am uploading the video from my gallery , in this case video is automatically playing but i want to control the video using play and pause button and also how to delete the uploaded file. here i am using image picker from expo.

This is my code which plays automatically

```<code>  selectVideo = async () => {
            let result = await ImagePicker.launchImageLibraryAsync({
               mediaTypes:"Videos"
            });
              if (!result.cancelled) {
                this.setState({ video: result.uri });
              }
          };
    render(){
return(
<Avatar xlarge rounded source={require('../../../assets/arrows.png')} onPress={this.selectVideo.bind(this)}/>
    {video &&
         <Video
                  source={{ uri: video }}
                  rate={1.0}
                  volume={1.0}
                  isMuted={false}
                  resizeMode="cover"
                  shouldPlay
                  isLooping
                  style={{ width:100, height:100 }}
                />
    }
</code>```

答:
WELL,i have solved this problem.i have installed expo-video-player

command: npm install expo-video-player.

Body:
i am uploading the video from my gallery , in this case video is automatically playing but i want to control the video using play and pause button and also how to delete the uploaded file. here i am using image picker from expo.

This is my code which plays automatically

  selectVideo = async () => {
            let result = await ImagePicker.launchImageLibraryAsync({
               mediaTypes:"Videos"
            });
              if (!result.cancelled) {
                this.setState({ video: result.uri });
              }
          };
    render(){
return(
<Avatar xlarge rounded source={require('../../../assets/arrows.png')} onPress={this.selectVideo.bind(this)}/>
    {video &&
         <Video
                  source={{ uri: video }}
                  rate={1.0}
                  volume={1.0}
                  isMuted={false}
                  resizeMode="cover"
                  shouldPlay
                  isLooping
                  style={{ width:100, height:100 }}
                />
    }


问:
queryset filter between 2 values whit foreing keys?
I have problems with the following queryset, I probe it in django shell and it returns an empty list.

The situation is that I'm occupying a lforeing key, I did the same exercise with the model "Tarifa_Sem" and returns the value without any problem, just replace the F ('') by a variable x = 1000

The situation is that the table of the model "Tarifa_Sem" is only for consultation.

Where I am going to manage and save the response of the queryset is in the "Calculadora_isr" model

Model 1

```<code>class Tarifa_Sem(models.Model):
limite_inferior_isr = models.DecimalField(max_digits=10, decimal_places=2)
limite_inferior_subsidio = models.DecimalField(max_digits=10, decimal_places=2)
limite_superior = models.DecimalField(max_digits=10, decimal_places=2)
</code>```

Model 2

```<code>class Calculadora_isr(models.Model):
tarifa = models.ForeignKey(Tarifa_Sem, on_delete=models.CASCADE, blank=True)
base_gravada = models.DecimalField(max_digits=10, decimal_places=2, blank=True)
limite_inf_calculo = models.DecimalField(max_digits=10, decimal_places=2, blank=True)
</code>```

Queryset and save()

```<code>def limite_inferior(self):
    queryset = Calculadora_isr.objects.filter(tarifa__limite_superior__gte=F('base_gravada'),tarifa__limite_inferior_isr__lte=F('base_gravada')).distinct().values('tarifa__limite_inferior_isr')
    return queryset

def save(self):
    self.limite_inf_calculo = self.limite_inferior
    super (Calculadora_isr, self).save()
</code>```

In the shell of django the list appears empty.

```<code>>>> queryset = Calculadora_isr.objects.filter(tarifa__limite_superior__gte=F('base_gravada'),tarifa__limite_inferior_isr__lte=F('base_gravada')).distinct().values('tarifa__limite_inferior_isr')
</code>```

And in the admin when I give him save he tells me:

conversion from method to Decimal is not supported

thanks for the support

答:
I finally found the solution.

To solve the problem of passing the "base_gravada" field, use another variable that returns all the values of "base_gravada"

```<code>qs1 = Calculadora_isr.objects.values_list('base_gravada')
</code>```

And in my second query, use the variable qs1:

```<code>qs2 = Tarifa_Sem.objects.filter(limite_superior__gte=qs1,limite_inferior_isr__lte=qs1).distinct().values('limite_inferior_isr')
</code>```

Body:
I have problems with the following queryset, I probe it in django shell and it returns an empty list.

The situation is that I'm occupying a lforeing key, I did the same exercise with the model "Tarifa_Sem" and returns the value without any problem, just replace the F ('') by a variable x = 1000

The situation is that the table of the model "Tarifa_Sem" is only for consultation.

Where I am going to manage and save the response of the queryset is in the "Calculadora_isr" model

Model 1

class Tarifa_Sem(models.Model):
limite_inferior_isr = models.DecimalField(max_digits=10, decimal_places=2)
limite_inferior_subsidio = models.DecimalField(max_digits=10, decimal_places=2)
limite_superior = models.DecimalField(max_digits=10, decimal_places=2)

Model 2

class Calculadora_isr(models.Model):
tarifa = models.ForeignKey(Tarifa_Sem, on_delete=models.CASCADE, blank=True)
base_gravada = models.DecimalField(max_digits=10, decimal_places=2, blank=True)
limite_inf_calculo = models.DecimalField(max_digits=10, decimal_places=2, blank=True)

Queryset and save()

def limite_inferior(self):
    queryset = Calculadora_isr.objects.filter(tarifa__limite_superior__gte=F('base_gravada'),tarifa__limite_inferior_isr__lte=F('base_gravada')).distinct().values('tarifa__limite_inferior_isr')
    return queryset

def save(self):
    self.limite_inf_calculo = self.limite_inferior
    super (Calculadora_isr, self).save()

In the shell of django the list appears empty.

>>> queryset = Calculadora_isr.objects.filter(tarifa__limite_superior__gte=F('base_gravada'),tarifa__limite_inferior_isr__lte=F('base_gravada')).distinct().values('tarifa__limite_inferior_isr')

And in the admin when I give him save he tells me:

conversion from method to Decimal is not supported

thanks for the support

Body:
I finally found the solution.

To solve the problem of passing the "base_gravada" field, use another variable that returns all the values of "base_gravada"

qs1 = Calculadora_isr.objects.values_list('base_gravada')

And in my second query, use the variable qs1:

qs2 = Tarifa_Sem.objects.filter(limite_superior__gte=qs1,limite_inferior_isr__lte=qs1).distinct().values('limite_inferior_isr')


问:
How to align text vertically in middle in UITextView
I'm trying to align text in UITextView vertically in middle. After search I found code and it seems to work until we start to type and hit enter when cursor jumps. When we hit enter key while typing inside text view the cursor jumps to adjust its position which I'm assuming due to the way it's called/implemented.

Is there a better and more elegant solution to this?

I've implemented it as UITextView extension. This code is taken from one of the solutions suggested on Center text vertically in a UITextView

My question is to fix the jumping issue. It's not a duplicate of above question.

```<code>extension UITextView {
    func alignTextVerticallyInContainer() {
        let fittingSize = CGSize(width: bounds.width, height: CGFloat.greatestFiniteMagnitude)
        let size = sizeThatFits(fittingSize)
        let topOffset = ((bounds.size.height - size.height * zoomScale) / 2)
        let positiveTopOffset = max(1, topOffset)
        contentOffset.y = -positiveTopOffset + 1
    }
}
</code>```

And calling it from

```<code>override func viewDidLayoutSubviews() {
    textView.alignTextVerticallyInContainer()
}
</code>```

答:
Please check this link for center text alignment. </p>

```<code> textView.textAlignment = .center
</code>```

Body:
I'm trying to align text in UITextView vertically in middle. After search I found code and it seems to work until we start to type and hit enter when cursor jumps. When we hit enter key while typing inside text view the cursor jumps to adjust its position which I'm assuming due to the way it's called/implemented.

Is there a better and more elegant solution to this?

I've implemented it as UITextView extension. This code is taken from one of the solutions suggested on Center text vertically in a UITextView

My question is to fix the jumping issue. It's not a duplicate of above question.

extension UITextView {
    func alignTextVerticallyInContainer() {
        let fittingSize = CGSize(width: bounds.width, height: CGFloat.greatestFiniteMagnitude)
        let size = sizeThatFits(fittingSize)
        let topOffset = ((bounds.size.height - size.height * zoomScale) / 2)
        let positiveTopOffset = max(1, topOffset)
        contentOffset.y = -positiveTopOffset + 1
    }
}

And calling it from

override func viewDidLayoutSubviews() {
    textView.alignTextVerticallyInContainer()
}

Body:
Please check this link for center text alignment.

 textView.textAlignment = .center


问:
How can I know which radio button is selected via jQuery?
I have two radio buttons and want to post the value of the selected one.
How can I get the value with jQuery?

I can get all of them like this:

```<code>$("form :radio")
</code>```

How do I know which one is selected?

答:
**Please try below example to check which radio button in selected ** </p>

```<code><script>
    $('#form1 input').on('change', function() {
       alert($('input[name=age]:checked', '#form1 ').val());
    });
</script>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    <form id="form1">
      <input type="radio" name="age" value="18" /> 18 <br />
      <input type="radio" name="age" value="20" /> 20 <br />
      <input type="radio" name="age" value="22" /> 22 <br />
    </form>
</code>```

OwnerDisplayName: Juan Manuel

Body:
I have two radio buttons and want to post the value of the selected one.
How can I get the value with jQuery?

I can get all of them like this:

$("form :radio")

How do I know which one is selected?

LastEditorDisplayName: Juan Manuel

Body:
**Please try below example to check which radio button in selected **

<script>
    $('#form1 input').on('change', function() {
       alert($('input[name=age]:checked', '#form1 ').val());
    });
</script>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    <form id="form1">
      <input type="radio" name="age" value="18" /> 18 <br />
      <input type="radio" name="age" value="20" /> 20 <br />
      <input type="radio" name="age" value="22" /> 22 <br />
    </form>


问:
.net library does not pick keys from app.config
I am working on a error reporting library in c#, and its a static class.
When I am running this library from other applications by adding a reference. It does not pick the AppSetting Keys from app.config.

In that case I need to add the keys to all main applications to make it working.

Are their any other solution to sortout this problem?

Thanks and Regards

答:
That is correct. When you develop an library, you need to configure the AppSettings keys in the main application that uses the library.

You should always have default values or throw an exception right away, if there is no value configure (the option that suites better for you).

You can use Settings, I think that will "pick" the values of the library and you can overrite this in the main application also.


问:
Is there a solution for finding SQL Query with join of 3 tables and do some opperations in a period?
Is there a way of finding SQL Query with join of 3 tables and do some operations in a period?
Query below:

https://i.stack.imgur.com/SpWkt.png

```<code>SELECT ST.code,ST.Plant,ST.STINT,E.code,E.Plant,SUM(E.Quantite) AS E_Qte,S.code,S.Plant,S.S_Qte
    FROM `enter` E
    INNER JOIN (SELECT code,Plant,SUM(Quantite) AS S_Qte FROM `sortie` group by code,Plant) S
    INNER JOIN
    (SELECT code,plant,sum(stockinitiale) AS STINT
    FROM `stockinitiale` group by code,Plant) ST ON E.Code= S.Code=ST.Code AND E.Plant= S.Plant=ST.Plant
    WHERE date BETWEEN '2019-05-17' AND '2019-05-28'
    GROUP BY E.code,S.code,ST.code,E.Plant,S.Plant,ST.Plant
</code>```

Expected output:

```<code>+------+-------+-------+------+-------+-------+------+-------+--------+
| code | Plant | STINT | code | Plant | E_Qte | code | Plant | S_Qte  |
+------+-------+-------+------+-------+-------+------+-------+--------+
| 1001 | P1    |   122 | 1001 | P1    |   662 | 1001 | P1    |     19 |
| 1001 | P3    |   108 | 1001 | P3    |    10 | 1001 | P3    |      2 |
| 1002 | P1    |     0 | 1002 | P1    |     4 | 1002 | P1    |     15 |
| 1002 | P3    |     6 | 1002 | P3    |     7 | 1002 | P3    |     12 |
| 1008 | P1    |    12 | 1001 | P1    |    66 | 1001 | P1    |     17 |
+------+-------+-------+------+-------+-------+------+-------+--------+
</code>```

答:
I didn't check anything else, just for the case of your join you may try this...

```<code>    SELECT ST.code,ST.Plant,ST.STINT,E.code,E.Plant,sum(E.Quantite) AS E_Qte,S.code,S.Plant,S.S_Qte
    FROM enter E
    INNER JOIN
    (SELECT code,Plant,sum(Quantite) As S_Qte FROM sortie group by code,Plant) S ON E.Plant= S.Plant
    INNER JOIN
    (SELECT code,plant,sum(stockinitiale) AS STINT FROM stockinitiale group by code,Plant) ST on S.Plant=ST.Plant
    where date between '2019-05-17' and '2019-05-28' group by E.code,S.code,ST.code,E.Plant,S.Plant,ST.Plant
</code>```

Although it is better if you post your input and expected output, if this is not working for your case.

Body:
Is there a way of finding SQL Query with join of 3 tables and do some operations in a period?
Query below:

https://i.stack.imgur.com/SpWkt.png

SELECT ST.code,ST.Plant,ST.STINT,E.code,E.Plant,SUM(E.Quantite) AS E_Qte,S.code,S.Plant,S.S_Qte
    FROM `enter` E
    INNER JOIN (SELECT code,Plant,SUM(Quantite) AS S_Qte FROM `sortie` group by code,Plant) S
    INNER JOIN
    (SELECT code,plant,sum(stockinitiale) AS STINT
    FROM `stockinitiale` group by code,Plant) ST ON E.Code= S.Code=ST.Code AND E.Plant= S.Plant=ST.Plant
    WHERE date BETWEEN '2019-05-17' AND '2019-05-28'
    GROUP BY E.code,S.code,ST.code,E.Plant,S.Plant,ST.Plant

Expected output:

+------+-------+-------+------+-------+-------+------+-------+--------+
| code | Plant | STINT | code | Plant | E_Qte | code | Plant | S_Qte  |
+------+-------+-------+------+-------+-------+------+-------+--------+
| 1001 | P1    |   122 | 1001 | P1    |   662 | 1001 | P1    |     19 |
| 1001 | P3    |   108 | 1001 | P3    |    10 | 1001 | P3    |      2 |
| 1002 | P1    |     0 | 1002 | P1    |     4 | 1002 | P1    |     15 |
| 1002 | P3    |     6 | 1002 | P3    |     7 | 1002 | P3    |     12 |
| 1008 | P1    |    12 | 1001 | P1    |    66 | 1001 | P1    |     17 |
+------+-------+-------+------+-------+-------+------+-------+--------+

Body:
I didn't check anything else, just for the case of your join you may try this...

    SELECT ST.code,ST.Plant,ST.STINT,E.code,E.Plant,sum(E.Quantite) AS E_Qte,S.code,S.Plant,S.S_Qte
    FROM enter E
    INNER JOIN
    (SELECT code,Plant,sum(Quantite) As S_Qte FROM sortie group by code,Plant) S ON E.Plant= S.Plant
    INNER JOIN
    (SELECT code,plant,sum(stockinitiale) AS STINT FROM stockinitiale group by code,Plant) ST on S.Plant=ST.Plant
    where date between '2019-05-17' and '2019-05-28' group by E.code,S.code,ST.code,E.Plant,S.Plant,ST.Plant

Although it is better if you post your input and expected output, if this is not working for your case.


问:
How to export a DataGrid to Excel in WPF
I am working on a project and I have not been able to export the information that I have in my DataGrid to excel.

how can I do it?

答:
I created an simple app to exporting DataGrid to Excel file.

Xaml:

```<code><StackPanel>
    <!--Export button-->
    <Button Name="ToExcelButton"
            Content="ToExcel"
            Margin="8"
            Padding="8"
            HorizontalAlignment="Center"
            Click="ToExcelButton_OnClick"/>

    <!--Users DataGrid-->
    <DataGrid Name="UsersDataGrid"
              AutoGenerateColumns="False"
              DataContext="{Binding}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="ID" Binding="{Binding Id}" Width="120" />
            <DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="180" />
            <DataGridTextColumn Header="Username" Binding="{Binding Username}" Width="150" />
        </DataGrid.Columns>
    </DataGrid>
</StackPanel>
</code>```

C#:

```<code>public partial class MainWindow
{
    public MainWindow()
    {
        InitializeComponent();
        UsersDataGrid.ItemsSource = GetUsers();
    }

    private static IEnumerable<User> GetUsers()
    {
        var users = new List<User>
        {
            new User {Id = 1, Name = "User1", Username = "u123"},
            new User {Id = 2, Name = "User2", Username = "u321"},
            new User {Id = 3, Name = "User3", Username = "u852"},
        };

        return users;
    }

    private void ToExcelButton_OnClick(object sender, RoutedEventArgs e)
    {
        var d = UsersDataGrid.ItemsSource.Cast<User>();
        var data = ToDataTable(d.ToList());
        ToExcelFile(data, "test.xlsx");
    }

    public static DataTable ToDataTable<T>(List<T> items)
    {
        var dataTable = new DataTable(typeof(T).Name);

        //Get all the properties
        var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (var prop in properties)
        {
            //Defining type of data column gives proper data table
            var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name, type);
        }
        foreach (var item in items)
        {
            var values = new object[properties.Length];
            for (var i = 0; i < properties.Length; i++)
            {
                //inserting property values to data table rows
                values[i] = properties[i].GetValue(item, null);
            }
            dataTable.Rows.Add(values);
        }
        //put a breakpoint here and check data table
        return dataTable;
    }

    public static void ToExcelFile(DataTable dataTable, string filePath, bool overwriteFile = true)
    {
        if (File.Exists(filePath) && overwriteFile)
            File.Delete(filePath);

        using (var connection = new OleDbConnection())
        {
            connection.ConnectionString = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={filePath};" +
                                          "Extended Properties='Excel 12.0 Xml;HDR=YES;'";
            connection.Open();
            using (var command = new OleDbCommand())
            {
                command.Connection = connection;
                var columnNames = (from DataColumn dataColumn in dataTable.Columns select dataColumn.ColumnName).ToList();
                var tableName = !string.IsNullOrWhiteSpace(dataTable.TableName) ? dataTable.TableName : Guid.NewGuid().ToString();
                command.CommandText = $"CREATE TABLE [{tableName}] ({string.Join(",", columnNames.Select(c => $"[{c}] VARCHAR").ToArray())});";
                command.ExecuteNonQuery();
                foreach (DataRow row in dataTable.Rows)
                {
                    var rowValues = (from DataColumn column in dataTable.Columns select (row[column] != null && row[column] != DBNull.Value) ? row[column].ToString() : string.Empty).ToList();
                    command.CommandText = $"INSERT INTO [{tableName}]({string.Join(",", columnNames.Select(c => $"[{c}]"))}) VALUES ({string.Join(",", rowValues.Select(r => $"'{r}'").ToArray())});";
                    command.ExecuteNonQuery();
                }
            }

            connection.Close();
        }
    }
}
</code>```

User class:

```<code>public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Username { get; set; }
}
</code>```

Body:
I created an simple app to exporting DataGrid to Excel file.

Xaml:

<StackPanel>
    <!--Export button-->
    <Button Name="ToExcelButton"
            Content="ToExcel"
            Margin="8"
            Padding="8"
            HorizontalAlignment="Center"
            Click="ToExcelButton_OnClick"/>

    <!--Users DataGrid-->
    <DataGrid Name="UsersDataGrid"
              AutoGenerateColumns="False"
              DataContext="{Binding}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="ID" Binding="{Binding Id}" Width="120" />
            <DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="180" />
            <DataGridTextColumn Header="Username" Binding="{Binding Username}" Width="150" />
        </DataGrid.Columns>
    </DataGrid>
</StackPanel>

C#:

public partial class MainWindow
{
    public MainWindow()
    {
        InitializeComponent();
        UsersDataGrid.ItemsSource = GetUsers();
    }

    private static IEnumerable<User> GetUsers()
    {
        var users = new List<User>
        {
            new User {Id = 1, Name = "User1", Username = "u123"},
            new User {Id = 2, Name = "User2", Username = "u321"},
            new User {Id = 3, Name = "User3", Username = "u852"},
        };

        return users;
    }

    private void ToExcelButton_OnClick(object sender, RoutedEventArgs e)
    {
        var d = UsersDataGrid.ItemsSource.Cast<User>();
        var data = ToDataTable(d.ToList());
        ToExcelFile(data, "test.xlsx");
    }

    public static DataTable ToDataTable<T>(List<T> items)
    {
        var dataTable = new DataTable(typeof(T).Name);

        //Get all the properties
        var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (var prop in properties)
        {
            //Defining type of data column gives proper data table
            var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name, type);
        }
        foreach (var item in items)
        {
            var values = new object[properties.Length];
            for (var i = 0; i < properties.Length; i++)
            {
                //inserting property values to data table rows
                values[i] = properties[i].GetValue(item, null);
            }
            dataTable.Rows.Add(values);
        }
        //put a breakpoint here and check data table
        return dataTable;
    }

    public static void ToExcelFile(DataTable dataTable, string filePath, bool overwriteFile = true)
    {
        if (File.Exists(filePath) && overwriteFile)
            File.Delete(filePath);

        using (var connection = new OleDbConnection())
        {
            connection.ConnectionString = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={filePath};" +
                                          "Extended Properties='Excel 12.0 Xml;HDR=YES;'";
            connection.Open();
            using (var command = new OleDbCommand())
            {
                command.Connection = connection;
                var columnNames = (from DataColumn dataColumn in dataTable.Columns select dataColumn.ColumnName).ToList();
                var tableName = !string.IsNullOrWhiteSpace(dataTable.TableName) ? dataTable.TableName : Guid.NewGuid().ToString();
                command.CommandText = $"CREATE TABLE [{tableName}] ({string.Join(",", columnNames.Select(c => $"[{c}] VARCHAR").ToArray())});";
                command.ExecuteNonQuery();
                foreach (DataRow row in dataTable.Rows)
                {
                    var rowValues = (from DataColumn column in dataTable.Columns select (row[column] != null && row[column] != DBNull.Value) ? row[column].ToString() : string.Empty).ToList();
                    command.CommandText = $"INSERT INTO [{tableName}]({string.Join(",", columnNames.Select(c => $"[{c}]"))}) VALUES ({string.Join(",", rowValues.Select(r => $"'{r}'").ToArray())});";
                    command.ExecuteNonQuery();
                }
            }

            connection.Close();
        }
    }
}

User class:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Username { get; set; }
}


答:
I think this is the pattern what you looking for.

```<code>import random

EXIT = False

while True:
  if EXIT:
     break
  y=random.randint(1,101)
  print("Random ",y)
  while not EXIT:
    print("Guess an integer between 1-100.")
    x=int(input())
    if x==y:
        print(x, "is correct! Would you like to try again? (Y/N)\n")
        z = input()
        if z == 'Y':
            print("Too bad! This game isn't finished yet!\n")
            break
        if z == 'N':
            print("Good! This game isn't finished yet!\n")
            EXIT = True
            break
    else:
        if x<y:
            print("Too low. Try again.\n")
        if x>y:
            print("Too high. Try again.\n")
</code>```

The output will be .

```<code>Random  89
Guess an integer between 1-100.
20
Too low. Try again.

Guess an integer between 1-100.
100
Too high. Try again.

Guess an integer between 1-100.
89
89 is correct! Would you like to try again? (Y/N)

Y
Too bad! This game isn't finished yet!

Random  36
Guess an integer between 1-100.
36
36 is correct! Would you like to try again? (Y/N)

N
Good! This game isn't finished yet!
</code>```

Title: How do I create a proper while loop?

Body:
I think this is the pattern what you looking for.

import random

EXIT = False

while True:
  if EXIT:
     break
  y=random.randint(1,101)
  print("Random ",y)
  while not EXIT:
    print("Guess an integer between 1-100.")
    x=int(input())
    if x==y:
        print(x, "is correct! Would you like to try again? (Y/N)\n")
        z = input()
        if z == 'Y':
            print("Too bad! This game isn't finished yet!\n")
            break
        if z == 'N':
            print("Good! This game isn't finished yet!\n")
            EXIT = True
            break
    else:
        if x<y:
            print("Too low. Try again.\n")
        if x>y:
            print("Too high. Try again.\n")

The output will be .

Random  89
Guess an integer between 1-100.
20
Too low. Try again.

Guess an integer between 1-100.
100
Too high. Try again.

Guess an integer between 1-100.
89
89 is correct! Would you like to try again? (Y/N)

Y
Too bad! This game isn't finished yet!

Random  36
Guess an integer between 1-100.
36
36 is correct! Would you like to try again? (Y/N)

N
Good! This game isn't finished yet!


问:
Receiving Error Message, despite data being sent
I have recently implemented a number of if statements that check to see if the require data has been entered, if not then I receive the error message something is wrong with.... But after implementing them I now recieve that error message regardless of whether the data is in fact being sent to the database (the data that is being sent is all correct) and I can't for the life of me figure out why.

```<code>$query = "insert into $sql_table (Eoi, Job_reference_number, First_Name, Last_Name, Street_Address, Suburb, State, Postcode, Email, Phone_Number, Skills) values ('$eoi','$jobNumber', '$firstName', '$lastName', '$streetAddress', '$suburb', '$state', '$postcode', '$emailAddress', '$phoneNumber', '$skills')";

$result = mysqli_query($conn, $query);
    if($jobNumber = ''){
       $result = false;
    }
    if($firstName = ''){
    $result = false;
    echo "<p> Something is wrong with your First Name </p>";
    }

    if($lastName = ''){
    $result = false;
    echo "<p> Something is wrong with your Last Name </p>";
    }

    if($streetAddress = ''){
    $result = false;
    echo "<p> Something is wrong with your Street Address </p>";
    }
    if($suburb = ''){
    $result = false;
    echo "<p> Something is wrong with your Suburb </p>";
    }
    if($postcode = ''){
    $result = false;
    echo "<p> Something is wrong with your Postcode </p>";
    }
    if($email = ''){
    $result = false;
    echo "<p> Something is wrong with your Email </p>";
    }
    if($phoneNumber = ''){
    $result = false;
        echo "<p> Something is wrong with your Phone Number </p>";
    }
    if($skills = ''){
    $result = false;
    echo "<p> Something is wrong with your Skills </p>";
    }

if($result != mysqli_query($conn, $query)) {
    echo "<p>Something is wrong with ", $query, "</p>";
}else {
    echo "<p class=\"ok\">Successfully added a New EOI record</p>";
    }
    }
}
        mysqli_close($conn);
</code>```

I expect the result to be Successfully added a new EOI record when the user inputs valid data but instead I get the error message.

答:
First you have a syntax error in if statement
  if statement should be == not =

```<code>if($yourVariable == ''){
  echo "<p> Something is wrong with your yourVariable </p>";//no meaning of this line
  $result = false;
}
</code>```

it means if your variable is empty then $result will false and you're can check it in your last if

Second you are checking all variable after DB insertion, you need to do it before insertion in db

Body:
I have recently implemented a number of if statements that check to see if the require data has been entered, if not then I receive the error message something is wrong with.... But after implementing them I now recieve that error message regardless of whether the data is in fact being sent to the database (the data that is being sent is all correct) and I can't for the life of me figure out why.

$query = "insert into $sql_table (Eoi, Job_reference_number, First_Name, Last_Name, Street_Address, Suburb, State, Postcode, Email, Phone_Number, Skills) values ('$eoi','$jobNumber', '$firstName', '$lastName', '$streetAddress', '$suburb', '$state', '$postcode', '$emailAddress', '$phoneNumber', '$skills')";

$result = mysqli_query($conn, $query);
    if($jobNumber = ''){
       $result = false;
    }
    if($firstName = ''){
    $result = false;
    echo "
 Something is wrong with your First Name
";
    }

    if($lastName = ''){
    $result = false;
    echo "
 Something is wrong with your Last Name
";
    }

    if($streetAddress = ''){
    $result = false;
    echo "
 Something is wrong with your Street Address
";
    }
    if($suburb = ''){
    $result = false;
    echo "
 Something is wrong with your Suburb
";
    }
    if($postcode = ''){
    $result = false;
    echo "
 Something is wrong with your Postcode
";
    }
    if($email = ''){
    $result = false;
    echo "
 Something is wrong with your Email
";
    }
    if($phoneNumber = ''){
    $result = false;
        echo "
 Something is wrong with your Phone Number
";
    }
    if($skills = ''){
    $result = false;
    echo "
 Something is wrong with your Skills
";
    }

if($result != mysqli_query($conn, $query)) {
    echo "
Something is wrong with ", $query, "
";
}else {
    echo "
Successfully added a New EOI record
";
    }
    }
}
        mysqli_close($conn);

I expect the result to be Successfully added a new EOI record when the user inputs valid data but instead I get the error message.

Body:
First you have a syntax error in if statement
  if statement should be == not =

if($yourVariable == ''){
  echo "<p> Something is wrong with your yourVariable </p>";//no meaning of this line
  $result = false;
}

it means if your variable is empty then $result will false and you're can check it in your last if

Second you are checking all variable after DB insertion, you need to do it before insertion in db


问:
How to call global or external function into child function?
I am using below code and when i am calling onMessageRender() function, so it says "this is not a function"

request = new Atmosphere.AtmosphereRequest(); // Global Function

Calling below code in ngONinIt

this.createSSE();

```<code>//Main function
 createSSE(){ this.request.onMessage = function (response) {
        console.log('request.onMessage trigger');
         try {
           let jsonData = JSON.parse(message);
          console.log('Normal Message JSON this.request.util', jsonData);
          this.onMessageRender();
        }catch (e) {
           console.log('Error in websocket onmessage: ', e);
           return;
         } }
</code>```

Created below function globally

```<code>onMessageRender(){

}
</code>```

Please let me know if you need more information. Thanks!

答:
Assuming this is an Angular/typescript question,

if createSSE is declared as part of an Angular module, and if onMessageRender() is a global function which is not declared as part of an Angular module, calling onMessageRender() should be without this, as onMessageRender() may not be part of the same object that createSSE is declared.

If onMessageRender() is indeed part of the same object, I think more detail is required to answer your question.

Body:
I am using below code and when i am calling onMessageRender() function, so it says "this is not a function"

request = new Atmosphere.AtmosphereRequest(); // Global Function

Calling below code in ngONinIt

this.createSSE();

//Main function
 createSSE(){ this.request.onMessage = function (response) {
        console.log('request.onMessage trigger');
         try {
           let jsonData = JSON.parse(message);
          console.log('Normal Message JSON this.request.util', jsonData);
          this.onMessageRender();
        }catch (e) {
           console.log('Error in websocket onmessage: ', e);
           return;
         } }

Created below function globally

onMessageRender(){

}

Please let me know if you need more information. Thanks!


问:
Speeding up the query with multiple joins, group by and order by
I have a SQL query as:

```<code>SELECT
title,
(COUNT(DISTINCT A.id)) AS "count_title"

FROM
B
INNER JOIN D ON B.app = D.app
INNER JOIN A ON D.number = A.number
INNER JOIN C ON A.id = C.id

GROUP BY C.title
ORDER BY count_title DESC
LIMIT 10
;
</code>```

Table D contains 50M records, A contains 30M records, B & C contains 30k records each. Indexes are defined on all columns used in joins, group by, order by.

The query works fine without the order by statement and returns results in around 2-3 sec.

But, with the sorting operation(order by) the query time increases to 10-12 seconds.

I understand the reason behind this, that executor has to traverse all the records for sorting operation and index will hardly help here.

Are there some other ways to speed up this query?

Here is the explain analyze of this query:

```<code>"QUERY PLAN"
"Limit  (cost=974652.20..974652.22 rows=10 width=54) (actual time=2817.579..2825.071 rows=10 loops=1)"
"  Buffers: shared hit=120299 read=573195"
"  ->  Sort  (cost=974652.20..974666.79 rows=5839 width=54) (actual time=2817.578..2817.578 rows=10 loops=1)"
"        Sort Key: (count(DISTINCT A.id)) DESC"
"        Sort Method: top-N heapsort  Memory: 26kB"
"        Buffers: shared hit=120299 read=573195"
"        ->  GroupAggregate  (cost=974325.65..974526.02 rows=5839 width=54) (actual time=2792.465..2817.097 rows=3618 loops=1)"
"              Group Key: C.title"
"              Buffers: shared hit=120299 read=573195"
"              ->  Sort  (cost=974325.65..974372.97 rows=18931 width=32) (actual time=2792.451..2795.161 rows=45175 loops=1)"
"                    Sort Key: C.title"
"                    Sort Method: quicksort  Memory: 5055kB"
"                    Buffers: shared hit=120299 read=573195"
"                    ->  Gather  (cost=968845.30..972980.74 rows=18931 width=32) (actual time=2753.402..2778.648 rows=45175 loops=1)"
"                          Workers Planned: 1"
"                          Workers Launched: 1"
"                          Buffers: shared hit=120299 read=573195"
"                          ->  Parallel Hash Join  (cost=967845.30..970087.64 rows=11136 width=32) (actual time=2751.725..2764.832 rows=22588 loops=2)"
"                                Hash Cond: ((C.id)::text = (A.id)::text)"
"                                Buffers: shared hit=120299 read=573195"
"                                ->  Parallel Seq Scan on C  (cost=0.00..1945.87 rows=66687 width=32) (actual time=0.017..4.316 rows=56684 loops=2)"
"                                      Buffers: shared read=1279"
"                                ->  Parallel Hash  (cost=966604.55..966604.55 rows=99260 width=9) (actual time=2750.987..2750.987 rows=20950 loops=2)"
"                                      Buckets: 262144  Batches: 1  Memory Usage: 4032kB"
"                                      Buffers: shared hit=120266 read=571904"
"                                      ->  Nested Loop  (cost=219572.23..966604.55 rows=99260 width=9) (actual time=665.832..2744.270 rows=20950 loops=2)"
"                                            Buffers: shared hit=120266 read=571904"
"                                            ->  Parallel Hash Join  (cost=219571.79..917516.91 rows=99260 width=4) (actual time=665.804..2583.675 rows=20950 loops=2)"
"                                                  Hash Cond: ((D.app)::text = (B.app)::text)"
"                                                  Buffers: shared hit=8 read=524214"
"                                                  ->  Parallel Bitmap Heap Scan on D  (cost=217542.51..895848.77 rows=5126741 width=13) (actual time=661.254..1861.862 rows=6160441 loops=2)"
"                                                        Recheck Cond: ((action_type)::text = ANY ('{10,11}'::text[]))"
"                                                        Heap Blocks: exact=242152"
"                                                        Buffers: shared hit=3 read=523925"
"                                                        ->  Bitmap Index Scan on D_index_action_type  (cost=0.00..214466.46 rows=12304178 width=0) (actual time=546.470..546.471 rows=12320882 loops=1)"
"                                                              Index Cond: ((action_type)::text = ANY ('{10,11}'::text[]))"
"                                                              Buffers: shared hit=3 read=33669"
"                                                  ->  Parallel Hash  (cost=1859.36..1859.36 rows=13594 width=12) (actual time=4.337..4.337 rows=16313 loops=2)"
"                                                        Buckets: 32768  Batches: 1  Memory Usage: 1152kB"
"                                                        Buffers: shared hit=5 read=289"
"                                                        ->  Parallel Index Only Scan using B_index_app on B  (cost=0.29..1859.36 rows=13594 width=12) (actual time=0.015..2.218 rows=16313 loops=2)"
"                                                              Heap Fetches: 0"
"                                                              Buffers: shared hit=5 read=289"
"                                            ->  Index Scan using A_index_number on A  (cost=0.43..0.48 rows=1 width=24) (actual time=0.007..0.007 rows=1 loops=41900)"
"                                                  Index Cond: ((number)::text = (D.number)::text)"
"                                                  Buffers: shared hit=120258 read=47690"
"Planning Time: 0.747 ms"
"Execution Time: 2825.118 ms"
</code>```

答:
You could try to aim for a nested loop join between b and d because b is so much smaller:

```<code>CREATE INDEX ON d (app);
</code>```

If d is vacuumed frequently enough, you could see if an index only scan is even faster. For that, include number in the index (in v11, use the INCLUDE clause for that!). The EXPLAIN output suggests that you have an extra condition on action_type; you'd have to include that column too for an index only scan.

Body:
I have a SQL query as:

SELECT
title,
(COUNT(DISTINCT A.id)) AS "count_title"

FROM
B
INNER JOIN D ON B.app = D.app
INNER JOIN A ON D.number = A.number
INNER JOIN C ON A.id = C.id

GROUP BY C.title
ORDER BY count_title DESC
LIMIT 10
;

Table D contains 50M records, A contains 30M records, B & C contains 30k records each. Indexes are defined on all columns used in joins, group by, order by.

The query works fine without the order by statement and returns results in around 2-3 sec.

But, with the sorting operation(order by) the query time increases to 10-12 seconds.

I understand the reason behind this, that executor has to traverse all the records for sorting operation and index will hardly help here.

Are there some other ways to speed up this query?

Here is the explain analyze of this query:

"QUERY PLAN"
"Limit  (cost=974652.20..974652.22 rows=10 width=54) (actual time=2817.579..2825.071 rows=10 loops=1)"
"  Buffers: shared hit=120299 read=573195"
"  ->  Sort  (cost=974652.20..974666.79 rows=5839 width=54) (actual time=2817.578..2817.578 rows=10 loops=1)"
"        Sort Key: (count(DISTINCT A.id)) DESC"
"        Sort Method: top-N heapsort  Memory: 26kB"
"        Buffers: shared hit=120299 read=573195"
"        ->  GroupAggregate  (cost=974325.65..974526.02 rows=5839 width=54) (actual time=2792.465..2817.097 rows=3618 loops=1)"
"              Group Key: C.title"
"              Buffers: shared hit=120299 read=573195"
"              ->  Sort  (cost=974325.65..974372.97 rows=18931 width=32) (actual time=2792.451..2795.161 rows=45175 loops=1)"
"                    Sort Key: C.title"
"                    Sort Method: quicksort  Memory: 5055kB"
"                    Buffers: shared hit=120299 read=573195"
"                    ->  Gather  (cost=968845.30..972980.74 rows=18931 width=32) (actual time=2753.402..2778.648 rows=45175 loops=1)"
"                          Workers Planned: 1"
"                          Workers Launched: 1"
"                          Buffers: shared hit=120299 read=573195"
"                          ->  Parallel Hash Join  (cost=967845.30..970087.64 rows=11136 width=32) (actual time=2751.725..2764.832 rows=22588 loops=2)"
"                                Hash Cond: ((C.id)::text = (A.id)::text)"
"                                Buffers: shared hit=120299 read=573195"
"                                ->  Parallel Seq Scan on C  (cost=0.00..1945.87 rows=66687 width=32) (actual time=0.017..4.316 rows=56684 loops=2)"
"                                      Buffers: shared read=1279"
"                                ->  Parallel Hash  (cost=966604.55..966604.55 rows=99260 width=9) (actual time=2750.987..2750.987 rows=20950 loops=2)"
"                                      Buckets: 262144  Batches: 1  Memory Usage: 4032kB"
"                                      Buffers: shared hit=120266 read=571904"
"                                      ->  Nested Loop  (cost=219572.23..966604.55 rows=99260 width=9) (actual time=665.832..2744.270 rows=20950 loops=2)"
"                                            Buffers: shared hit=120266 read=571904"
"                                            ->  Parallel Hash Join  (cost=219571.79..917516.91 rows=99260 width=4) (actual time=665.804..2583.675 rows=20950 loops=2)"
"                                                  Hash Cond: ((D.app)::text = (B.app)::text)"
"                                                  Buffers: shared hit=8 read=524214"
"                                                  ->  Parallel Bitmap Heap Scan on D  (cost=217542.51..895848.77 rows=5126741 width=13) (actual time=661.254..1861.862 rows=6160441 loops=2)"
"                                                        Recheck Cond: ((action_type)::text = ANY ('{10,11}'::text[]))"
"                                                        Heap Blocks: exact=242152"
"                                                        Buffers: shared hit=3 read=523925"
"                                                        ->  Bitmap Index Scan on D_index_action_type  (cost=0.00..214466.46 rows=12304178 width=0) (actual time=546.470..546.471 rows=12320882 loops=1)"
"                                                              Index Cond: ((action_type)::text = ANY ('{10,11}'::text[]))"
"                                                              Buffers: shared hit=3 read=33669"
"                                                  ->  Parallel Hash  (cost=1859.36..1859.36 rows=13594 width=12) (actual time=4.337..4.337 rows=16313 loops=2)"
"                                                        Buckets: 32768  Batches: 1  Memory Usage: 1152kB"
"                                                        Buffers: shared hit=5 read=289"
"                                                        ->  Parallel Index Only Scan using B_index_app on B  (cost=0.29..1859.36 rows=13594 width=12) (actual time=0.015..2.218 rows=16313 loops=2)"
"                                                              Heap Fetches: 0"
"                                                              Buffers: shared hit=5 read=289"
"                                            ->  Index Scan using A_index_number on A  (cost=0.43..0.48 rows=1 width=24) (actual time=0.007..0.007 rows=1 loops=41900)"
"                                                  Index Cond: ((number)::text = (D.number)::text)"
"                                                  Buffers: shared hit=120258 read=47690"
"Planning Time: 0.747 ms"
"Execution Time: 2825.118 ms"

Body:
You could try to aim for a nested loop join between b and d because b is so much smaller:

CREATE INDEX ON d (app);

If d is vacuumed frequently enough, you could see if an index only scan is even faster. For that, include number in the index (in v11, use the INCLUDE clause for that!). The EXPLAIN output suggests that you have an extra condition on action_type; you'd have to include that column too for an index only scan.


问:
Scroll Position GUI with Silverlight
I have a text chat application developed in Silverlight. The app is polling the server every 2 seconds for incoming data and thats when I set my scroll bar's position to the last message.

There is something fishy with the scroll bar's position which I cannot understand. I have hosted the app here, http://bit.ly/h2yopt

Can you please help me work out the scroll position.

PS: Please try entering the message and then move the scroll bar.

Thank you.

答:
I have a text chat application
  developed in Silverlight. The app is
  polling the server every 2 seconds for
  incoming data and thats when I set my
  scroll bar's position to the last
  message.

Then don't adjust the scrolling every time you poll, adjust it only when you need to like maybe when you enter a message yourself or whenever. Also, is the list DataBound? I think you would have more control if you do this control level.

Hope this helps.

Title: Scroll Position GUI with Silverlight


问:
Requested registry access is not allowed. even with signed exe and admin Privileged in manifest
I am trying to access HKEY_LOCAL_MACHINE registry,

This is the manifest file:

```<code><?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
    <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
    </requestedPrivileges>
    </security>
</trustInfo>

<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
    <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />
    <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />
    <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />
    <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />
    <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
    </application>
</compatibility>

<application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
    <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
    </windowsSettings>
</application>
<dependency>
    <dependentAssembly>
    <assemblyIdentity
        type="win32"
        name="Microsoft.Windows.Common-Controls"
        version="6.0.0.0"
        processorArchitecture="*"
        publicKeyToken="6595b64144ccf1df"
        language="*"
        />
    </dependentAssembly>
</dependency>
</assembly>
</code>```

I also sign the executable with Test Certificate

this is the function:

```<code>static string GetDeviceGuid()
{
    const string AdapterKey = "SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}";
    RegistryKey regAdapters = Registry.LocalMachine.OpenSubKey(AdapterKey, RegistryKeyPermissionCheck.ReadSubTree, System.Security.AccessControl.RegistryRights.ReadKey);
    string[] keyNames = regAdapters.GetSubKeyNames();
    string devGuid = "";
    foreach (string x in keyNames)
    {
        RegistryKey regAdapter = regAdapters.OpenSubKey(x);
        object id = regAdapter.GetValue("ComponentId");
        if (id != null && id.ToString() == "tap0901") devGuid = regAdapter.GetValue("NetCfgInstanceId").ToString();
    }
    return devGuid;
}
</code>```

this is the result:

```<code>at System.ThrowHelper.ThrowSecurityException(ExceptionResource resource)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name)
at TestTun.TunTap.GetDeviceGuid()
</code>```

what should I do to read the registry without Security Exception

答:
I found the problem but I don't know why access to this address is impossible

```<code>Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}\Properties
</code>```

Registry Error on Regedit
Visual Studio Debug

I fixed my code with regex

```<code>static string GetDeviceGuid()
    {
        const string AdapterKey = "SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}";
        RegistryKey regAdapters = Registry.LocalMachine.OpenSubKey(AdapterKey);
        string[] keyNames = regAdapters.GetSubKeyNames();
        foreach (string x in keyNames) {
            Console.WriteLine(x);
        }
        string devGuid = "";
        Regex rx = new Regex(@"\d{4}",
      RegexOptions.Compiled | RegexOptions.IgnoreCase);
        foreach (string x in keyNames)
        {
            if (!rx.IsMatch(x)) {
                continue;
            }
            RegistryKey regAdapter = regAdapters.OpenSubKey(x);
            object id = regAdapter.GetValue("ComponentId");
            if (id != null && id.ToString() == "tap0901") devGuid = regAdapter.GetValue("NetCfgInstanceId").ToString();
        }
        return devGuid;
    }
</code>```

Body:
I am trying to access HKEY_LOCAL_MACHINE registry,

This is the manifest file:

<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
    <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
    </requestedPrivileges>
    </security>
</trustInfo>

<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
    <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />
    <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />
    <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />
    <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />
    <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
    </application>
</compatibility>

<application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
    <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
    </windowsSettings>
</application>
<dependency>
    <dependentAssembly>
    <assemblyIdentity
        type="win32"
        name="Microsoft.Windows.Common-Controls"
        version="6.0.0.0"
        processorArchitecture="*"
        publicKeyToken="6595b64144ccf1df"
        language="*"
        />
    </dependentAssembly>
</dependency>
</assembly>

I also sign the executable with Test Certificate

this is the function:

static string GetDeviceGuid()
{
    const string AdapterKey = "SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}";
    RegistryKey regAdapters = Registry.LocalMachine.OpenSubKey(AdapterKey, RegistryKeyPermissionCheck.ReadSubTree, System.Security.AccessControl.RegistryRights.ReadKey);
    string[] keyNames = regAdapters.GetSubKeyNames();
    string devGuid = "";
    foreach (string x in keyNames)
    {
        RegistryKey regAdapter = regAdapters.OpenSubKey(x);
        object id = regAdapter.GetValue("ComponentId");
        if (id != null && id.ToString() == "tap0901") devGuid = regAdapter.GetValue("NetCfgInstanceId").ToString();
    }
    return devGuid;
}

this is the result:

at System.ThrowHelper.ThrowSecurityException(ExceptionResource resource)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name)
at TestTun.TunTap.GetDeviceGuid()

what should I do to read the registry without Security Exception

Body:
I found the problem but I don't know why access to this address is impossible

Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}\Properties

Registry Error on Regedit
Visual Studio Debug

I fixed my code with regex

static string GetDeviceGuid()
    {
        const string AdapterKey = "SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}";
        RegistryKey regAdapters = Registry.LocalMachine.OpenSubKey(AdapterKey);
        string[] keyNames = regAdapters.GetSubKeyNames();
        foreach (string x in keyNames) {
            Console.WriteLine(x);
        }
        string devGuid = "";
        Regex rx = new Regex(@"\d{4}",
      RegexOptions.Compiled | RegexOptions.IgnoreCase);
        foreach (string x in keyNames)
        {
            if (!rx.IsMatch(x)) {
                continue;
            }
            RegistryKey regAdapter = regAdapters.OpenSubKey(x);
            object id = regAdapter.GetValue("ComponentId");
            if (id != null && id.ToString() == "tap0901") devGuid = regAdapter.GetValue("NetCfgInstanceId").ToString();
        }
        return devGuid;
    }


问:
Can't Connect to Server via IntegrationServices
I am trying to connect to my SQL Server to run a SSIS package.  I admit that this is the first time I've tried this, so I'm not exactly confident that I have everything correct.

I get a generic error of "Failed to connect to server BSQL_01" on the line:

```<code>IntegrationServices ssisServer = new IntegrationServices(ssisConnection);
</code>```

Here is my SQL Server, and the only package there is the one I'm trying to run:

Here is the code I'm having issues with.

```<code>// Connection to the database server where the packages are located
SqlConnection ssisConnection = new SqlConnection("Data Source=BSQL_01;Initial Catalog=master;Integrated Security=SSPI;");

// SSIS server object with connection
IntegrationServices ssisServer = new IntegrationServices(ssisConnection);

// The reference to the package which you want to execute
PackageInfo ssisPackage = ssisServer.Catalogs["SSISDB"].Folders["PORGImport"].Projects["PORGImport"].Packages["PORGImport.dtsx"];

long executionIdentifier = ssisPackage.Execute(false, null, executionParameter);

ExecutionOperation executionOperation = ssisServer.Catalogs["SSISDB"].Executions[executionIdentifier];

while (!executionOperation.Completed) {
    System.Threading.Thread.Sleep(5000);
    executionOperation.Refresh();
}

if (executionOperation.Status == Operation.ServerOperationStatus.Success) {
    Console.WriteLine("Success");
    MessageBox.Show("Success");

} else if (executionOperation.Status == Operation.ServerOperationStatus.Failed) {
    Console.WriteLine("Failed");
    MessageBox.Show("Failed");

} else {
    Console.WriteLine("Something Went Really Wrong");
    MessageBox.Show("Oh Crap");
}
</code>```

Update

Ok, I changed the Initial Catalog in my ConnectionString to 'Mmaster' and I no longer get the error.  It APPEARS to run as I get the "Success", however, when I check the tables that are supposed to be populated, nothing is there.

答:
The "Initial Catalog" of the ConnectionString needed to be "master", not "SSISDB"</p>

```<code>SqlConnection ssisConnection = new SqlConnection("Data Source=BSQL_01;Initial Catalog=master;Integrated Security=SSPI;");
</code>```

Body:
I am trying to connect to my SQL Server to run a SSIS package.  I admit that this is the first time I've tried this, so I'm not exactly confident that I have everything correct.

I get a generic error of "Failed to connect to server BSQL_01" on the line:

IntegrationServices ssisServer = new IntegrationServices(ssisConnection);

Here is my SQL Server, and the only package there is the one I'm trying to run:

Here is the code I'm having issues with.

// Connection to the database server where the packages are located
SqlConnection ssisConnection = new SqlConnection("Data Source=BSQL_01;Initial Catalog=master;Integrated Security=SSPI;");

// SSIS server object with connection
IntegrationServices ssisServer = new IntegrationServices(ssisConnection);

// The reference to the package which you want to execute
PackageInfo ssisPackage = ssisServer.Catalogs["SSISDB"].Folders["PORGImport"].Projects["PORGImport"].Packages["PORGImport.dtsx"];

long executionIdentifier = ssisPackage.Execute(false, null, executionParameter);

ExecutionOperation executionOperation = ssisServer.Catalogs["SSISDB"].Executions[executionIdentifier];

while (!executionOperation.Completed) {
    System.Threading.Thread.Sleep(5000);
    executionOperation.Refresh();
}

if (executionOperation.Status == Operation.ServerOperationStatus.Success) {
    Console.WriteLine("Success");
    MessageBox.Show("Success");

} else if (executionOperation.Status == Operation.ServerOperationStatus.Failed) {
    Console.WriteLine("Failed");
    MessageBox.Show("Failed");

} else {
    Console.WriteLine("Something Went Really Wrong");
    MessageBox.Show("Oh Crap");
}

Update

Ok, I changed the Initial Catalog in my ConnectionString to 'Mmaster' and I no longer get the error.  It APPEARS to run as I get the "Success", however, when I check the tables that are supposed to be populated, nothing is there.

Body:
The "Initial Catalog" of the ConnectionString needed to be "master", not "SSISDB"

SqlConnection ssisConnection = new SqlConnection("Data Source=BSQL_01;Initial Catalog=master;Integrated Security=SSPI;");


问:
How do I encode and decode a base64 string?

How do I return a base64 encoded string given a string?

How do I decode a base64 encoded string into a string?

答:
```<code>    using System;
    using System.Text;

    public static class Base64Conversions
    {
        public static string EncodeBase64(this string text, Encoding encoding = null)
        {
            if (text == null) return null;

            encoding = encoding ?? Encoding.UTF8;
            var bytes = encoding.GetBytes(text);
            return Convert.ToBase64String(bytes);
        }

        public static string DecodeBase64(this string encodedText, Encoding encoding = null)
        {
            if (encodedText == null) return null;

            encoding = encoding ?? Encoding.UTF8;
            var bytes = Convert.FromBase64String(encodedText);
            return encoding.GetString(bytes);
        }
    }
</code>```

Usage

```<code>    var text = "Sample Text";
    var base64 = text.EncodeBase64();
    base64 = text.EncodeBase64(Encoding.UTF8); //or with Encoding
</code>```

Body:
    using System;
    using System.Text;

    public static class Base64Conversions
    {
        public static string EncodeBase64(this string text, Encoding encoding = null)
        {
            if (text == null) return null;

            encoding = encoding ?? Encoding.UTF8;
            var bytes = encoding.GetBytes(text);
            return Convert.ToBase64String(bytes);
        }

        public static string DecodeBase64(this string encodedText, Encoding encoding = null)
        {
            if (encodedText == null) return null;

            encoding = encoding ?? Encoding.UTF8;
            var bytes = Convert.FromBase64String(encodedText);
            return encoding.GetString(bytes);
        }
    }

Usage

    var text = "Sample Text";
    var base64 = text.EncodeBase64();
    base64 = text.EncodeBase64(Encoding.UTF8); //or with Encoding


问:
Does class ThreadInfo provide more information than reachable from JVMTI?
This is confusing. The ThreadInfo class provides alot of information, especially statistic of a Thread. However I cannot find such functions in the JVMTI. Is this norma? Do I have to gather the data myself? Do I have to iterate to the ThreadInfo object myself?</p>

答:
All of the information available in the ThreadInfo class can be acquired through JVMTI functions:

See:
http://download.oracle.com/javase/1.5.0/docs/guide/jvmti/jvmti.html#GetThreadState

It's everything that's in ThreadInfo, just jammed into a bit vector.


问:
how to return the date as dd-FullMonth-yyyy
I have a date field in SharePoint list as mm/dd/yyyy

I want to list it as dd MonthName yyyy

When I use the below function, it return the date with one month added,
for example, if the field date is 1/1/2019 it will be displayed as 1 February 2019 (instead of January, it displays February)

I tried to subtract 1 from monthindex but it didn't work.

```<code>function formatDate(thedate) {
  var monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
  ];
  var diffrentformat = thedate.split(" ")[0];
  var divideddate = diffrentformat.split("-");
  var d = new Date(divideddate[0], divideddate[1], divideddate[2]);
  //var d = new Date(thedate.split[]);
  var day = d.getDate();
  var monthIndex = d.getMonth();
  var year = d.getFullYear();

  return day + ' ' + monthNames[monthIndex] + ' ' + year;
}
</code>```

I expect the output to be dd MonthName yyyy, but I'm getting dd nextMonthName yyyy

答:
You can format and return using toLocaleDateString like below,

```<code>  return  day + ' ' + d.toLocaleDateString('en-us', { month: 'long' }) + ' ' + year;
</code>```

No need to maintain month names in the list.

Body:
I have a date field in SharePoint list as mm/dd/yyyy

I want to list it as dd MonthName yyyy

When I use the below function, it return the date with one month added,
for example, if the field date is 1/1/2019 it will be displayed as 1 February 2019 (instead of January, it displays February)

I tried to subtract 1 from monthindex but it didn't work.

function formatDate(thedate) {
  var monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
  ];
  var diffrentformat = thedate.split(" ")[0];
  var divideddate = diffrentformat.split("-");
  var d = new Date(divideddate[0], divideddate[1], divideddate[2]);
  //var d = new Date(thedate.split[]);
  var day = d.getDate();
  var monthIndex = d.getMonth();
  var year = d.getFullYear();

  return day + ' ' + monthNames[monthIndex] + ' ' + year;
}

I expect the output to be dd MonthName yyyy, but I'm getting dd nextMonthName yyyy

Body:
You can format and return using toLocaleDateString like below,

  return  day + ' ' + d.toLocaleDateString('en-us', { month: 'long' }) + ' ' + year;

No need to maintain month names in the list.


问:
How to select MAX id and convert Result to int
I would like to get the MAX id from my table and add a number to it. When the result is stored after executing the query, I save it into another variable and add 1. I get an error: "Object of class mysqli_result could not be converted to int"

I have tried:

```<code>$row = mysqli_fetch_assoc($result);
$uniqueCode = $row+1;
</code>```

This is the current code I have to get the maximum reference number:

```<code>    $sql = "SELECT MAX(referenceNo) FROM taxibookings LIMIT 1";
        $result = mysqli_query($conn, $sql);
</code>```

答:
 Try this code</p>

```<code>$sql = "SELECT MAX(referenceNo) as referenceNo FROM taxibookings";
$result = mysqli_query($conn, $sql);
$data = mysqli_fetch_assoc($result);
$uniqueCode = $data['referenceNo']+1;
</code>```

Body:
I would like to get the MAX id from my table and add a number to it. When the result is stored after executing the query, I save it into another variable and add 1. I get an error: "Object of class mysqli_result could not be converted to int"

I have tried:

$row = mysqli_fetch_assoc($result);
$uniqueCode = $row+1;

This is the current code I have to get the maximum reference number:

    $sql = "SELECT MAX(referenceNo) FROM taxibookings LIMIT 1";
        $result = mysqli_query($conn, $sql);

Body:
 Try this code

$sql = "SELECT MAX(referenceNo) as referenceNo FROM taxibookings";
$result = mysqli_query($conn, $sql);
$data = mysqli_fetch_assoc($result);
$uniqueCode = $data['referenceNo']+1;


问:
How to insert/update JSON data into postgreSQL
This is my table schema,

```<code>[column] [type]
tablename json
word  varchar
text  json
</code>```

I implemented using psycopg2 with Python,

```<code>cur.execute("INSERT INTO json (word,text) VALUES (%s,%s);",(word,text))
</code>```

word contains list object type but inside are string,

```<code>['a','b','c']
</code>```

text contains list object type but inside is dict (json),

```<code>[{'a':'b'},{'c':'d'}]
</code>```

When I run the function. I got this error wanring below,

```<code>" can't adapt type 'dict' "
</code>```

The question is, How to insert json into postgreSQL, As you see type of text. It's look like dict, But how to assign text variable is json?. or I'm missing something?

答:
json.dumps() could be used to switch to a string for the database.

```<code>import json
postgres_string = json.dumps(text)
# Save postres_string into postgress here

# When you want to retrieve the dictionary, do so as below:
text = json.loads(postgres_string)
</code>```

Body:
This is my table schema,

[column] [type]
tablename json
word  varchar
text  json

I implemented using psycopg2 with Python,

cur.execute("INSERT INTO json (word,text) VALUES (%s,%s);",(word,text))

word contains list object type but inside are string,

['a','b','c']

text contains list object type but inside is dict (json),

[{'a':'b'},{'c':'d'}]

When I run the function. I got this error wanring below,

" can't adapt type 'dict' "

The question is, How to insert json into postgreSQL, As you see type of text. It's look like dict, But how to assign text variable is json?. or I'm missing something?

Body:
json.dumps() could be used to switch to a string for the database.

import json
postgres_string = json.dumps(text)
# Save postres_string into postgress here

# When you want to retrieve the dictionary, do so as below:
text = json.loads(postgres_string)


问:
Implement Growl in Java Application
I want my Java application to make a growl notification. My IDEs are Eclipse and Netbeans, and I am trying to implement a library in either (so far it worked it neither). How can I just add the library to my project and then reference the classes from within my own classes? Moreover, where can I find an appropriate library?

Thanks in advance!

EDIT: Ok, now I have somehow managed to implement the library ^^ However: the following command fails:

```<code>System.loadLibrary("growl");
</code>```

It returns following error:

Message: no growl in java.library.path

How can I fix this?

答: It's possible to use AppleScript script engine in Java 6 on OS X to communicate with Growl. Here's a blog post describing how to do it.</p>

ContentLicense: CC BY-SA 2.5

Title: Implement Growl in Java Application

Body:
I want my Java application to make a growl notification. My IDEs are Eclipse and Netbeans, and I am trying to implement a library in either (so far it worked it neither). How can I just add the library to my project and then reference the classes from within my own classes? Moreover, where can I find an appropriate library?

Thanks in advance!

EDIT: Ok, now I have somehow managed to implement the library ^^ However: the following command fails:

System.loadLibrary("growl");

It returns following error:

Message: no growl in java.library.path

How can I fix this?


问:
In docusign rest api, while creating envelopes it always send to the other mail except json contained mail?
The post request of creating envelop in docusign api.

https://demo.docusign.net/restapi/v2/accounts/{{accountId}}/envelopes

Request Json Object:

```<code>{
  "enableResponsiveChoice": true,
  "emailSubject": "Guuu",
  "envelopeId": "02c73303-704c-485d-b30f-c6cae3adfa6c",
  "autoNavigation": true,
  "status": "sent",
  "workflow": {
    "currentWorkflowStepId": "",
    "workflowSteps": []
  },
  "signingLocation": "online",
  "allowMarkup": false,
  "createdDateTime": "2019-05-28T06:31:03.150Z",
  "lastModifiedDateTime": "2019-05-28T06:31:03.150Z",
  "statusChangedDateTime": "2019-05-28T06:31:03.150Z",
  "expireEnabled": "true",
  "expireAfter": "120",
  "envelopeIdStamping": true,
  "signerCanSignOnMobile": "true",
  "isSignatureProviderEnvelope": true,
  "allowComments": true,
  "hasComments": false,
  "allowViewHistory": "true",
  "envelopeMetadata": {
    "allowAdvancedCorrect": "true",
    "enableSignWithNotary": "false",
    "allowCorrect": "true"
  },
  "envelopeLocation": "current_site",
  "isDynamicEnvelope": "true",
  "recipients": {
    "signers": [
      {
        "name": "shailesh",
        "email": "shaileshbhurle1221@gmail.com",
        "recipientId": "6",
        "tabs": {
          "signHereTabs": [
            {
              "xPosition": "150",
              "yPosition": "200",
              "documentId": "1",
              "pageNumber": "1"
            }
          ]
        }
      }
    ]
  }
}
</code>```

Response Object:

```<code>{
    "envelopeId": "e88f7f69-34e0-4bfa-b6bf-ce443073f3d6",
    "uri": "/envelopes/e88f7f69-34e0-4bfa-b6bf-ce443073f3d6",
    "statusDateTime": "2019-05-28T19:51:53.0100000Z",
    "status": "sent"
}
</code>```

It envelop wont sent to shaileshbhurle1221@gmail.com else it sent to other mail id. but why?

答:
In Request Json:
{
..
"envelopId":""
}
it means that envelope was already created, and email was locked for that particular envelop Id that why it send to the other mail id rather than XXXXXXXXXXX1221@gmail.com.</p>

Body:
The post request of creating envelop in docusign api.

https://demo.docusign.net/restapi/v2/accounts/{{accountId}}/envelopes

Request Json Object:

{
  "enableResponsiveChoice": true,
  "emailSubject": "Guuu",
  "envelopeId": "02c73303-704c-485d-b30f-c6cae3adfa6c",
  "autoNavigation": true,
  "status": "sent",
  "workflow": {
    "currentWorkflowStepId": "",
    "workflowSteps": []
  },
  "signingLocation": "online",
  "allowMarkup": false,
  "createdDateTime": "2019-05-28T06:31:03.150Z",
  "lastModifiedDateTime": "2019-05-28T06:31:03.150Z",
  "statusChangedDateTime": "2019-05-28T06:31:03.150Z",
  "expireEnabled": "true",
  "expireAfter": "120",
  "envelopeIdStamping": true,
  "signerCanSignOnMobile": "true",
  "isSignatureProviderEnvelope": true,
  "allowComments": true,
  "hasComments": false,
  "allowViewHistory": "true",
  "envelopeMetadata": {
    "allowAdvancedCorrect": "true",
    "enableSignWithNotary": "false",
    "allowCorrect": "true"
  },
  "envelopeLocation": "current_site",
  "isDynamicEnvelope": "true",
  "recipients": {
    "signers": [
      {
        "name": "shailesh",
        "email": "shaileshbhurle1221@gmail.com",
        "recipientId": "6",
        "tabs": {
          "signHereTabs": [
            {
              "xPosition": "150",
              "yPosition": "200",
              "documentId": "1",
              "pageNumber": "1"
            }
          ]
        }
      }
    ]
  }
}

Response Object:

{
    "envelopeId": "e88f7f69-34e0-4bfa-b6bf-ce443073f3d6",
    "uri": "/envelopes/e88f7f69-34e0-4bfa-b6bf-ce443073f3d6",
    "statusDateTime": "2019-05-28T19:51:53.0100000Z",
    "status": "sent"
}

It envelop wont sent to shaileshbhurle1221@gmail.com else it sent to other mail id. but why?


问:
How to get automigrate to work with SQL Server
I can't get automigrate and autoupdate to work.

I created my project, datasource and model. All looks good, but I can't get automigrate to work. If I go to my SQL Server and create the table/schema then all the GET/POST methods work fine.

I went to the server/boot directory. there are currently two files in there authentication and root.

I created a new file called automigrate.js

```<code>'use strict';

 module.exports = function (app) {
   app.dataSources.mysql.automigrate();
   console.log("Performed automigration.");
}
</code>```

When I run it I get an error :

C:\Users\ajmal\loopback\telematics\server\server.js:31 if (err) throw err; ^

TypeError: Cannot read property 'automigrate' of undefined

at Object.module.exports [as func] (C:\Users\ajmal\loopback\telematics\server\boot\automigrate.js:9:26)

  at C:\Users\ajmal\loopback\telematics\node_modules\loopback-boot\lib\executor.js:316:22

答:
You can use grunt-loopback-auto module or build your own by following the document at https://loopback.io/doc/en/lb3/Creating-a-database-schema-from-models.html#auto-update

Notes:

automigrate will drop and re-create the tables. Therefore, data will be lost. It's terrible on production.

autoupdate calculates the difference between the LoopBack model and the database table definition and alters the table accordingly.

So, we should use autoupdate in almost cases.

Body:
I can't get automigrate and autoupdate to work.

I created my project, datasource and model. All looks good, but I can't get automigrate to work. If I go to my SQL Server and create the table/schema then all the GET/POST methods work fine.

I went to the server/boot directory. there are currently two files in there authentication and root.

I created a new file called automigrate.js

'use strict';

 module.exports = function (app) {
   app.dataSources.mysql.automigrate();
   console.log("Performed automigration.");
}

When I run it I get an error :

C:\Users\ajmal\loopback\telematics\server\server.js:31 if (err) throw err; ^

TypeError: Cannot read property 'automigrate' of undefined

at Object.module.exports [as func] (C:\Users\ajmal\loopback\telematics\server\boot\automigrate.js:9:26)

  at C:\Users\ajmal\loopback\telematics\node_modules\loopback-boot\lib\executor.js:316:22