问:
ASP.NET Core, how it handle concurrent request when async involved?
Any idea how ASP.net core handle concurrent request when a async involved. As you can see from the log below, the request finished time seem like in sequence rather than in parallel or concurrently? I might understand the async wrong, hope someone can explain why below request finished timing is in sequence rather identical timing? I was expecting at least each of the request should finish in almost identical time?</p>

```<code>Connection id "0HL9BC18TNP25" started.
Connection id "0HL9BC18TNP26" started.
Connection id "0HL9BC18TNP27" started.
Connection id "0HL9BC18TNP28" started.
Connection id "0HL9BC18TNP29" started.
Connection id "0HL9BC18TNP2A" started.
Connection id "0HL9BC18TNP2B" started.
Connection id "0HL9BC18TNP2C" started.
Connection id "0HL9BC18TNP2D" started.
Connection id "0HL9BC18TNP2E" started.
Connection id "0HL9BC18TNP2C" completed keep alive response.
Request finished in 45.2835ms 200 application/json; charset=utf-8
Connection id "0HL9BC18TNP2C" received FIN.
Connection id "0HL9BC18TNP2C" disconnecting.
Connection id "0HL9BC18TNP2C" sending FIN.
Connection id "0HL9BC18TNP2C" sent FIN with status "0".
Connection id "0HL9BC18TNP2C" stopped.
Connection id "0HL9BC18TNP2D" completed keep alive response.
Request finished in 175.3974ms 200 application/json; charset=utf-8
Connection id "0HL9BC18TNP2D" received FIN.
Connection id "0HL9BC18TNP2D" disconnecting.
Connection id "0HL9BC18TNP2D" sending FIN.
Connection id "0HL9BC18TNP2D" sent FIN with status "0".
Connection id "0HL9BC18TNP2D" stopped.
Connection id "0HL9BC18TNP27" received FIN.
Connection id "0HL9BC18TNP27" completed keep alive response.
Request finished in 171.6836ms 200 application/json; charset=utf-8
Connection id "0HL9BC18TNP27" disconnecting.
Connection id "0HL9BC18TNP27" sending FIN.
Connection id "0HL9BC18TNP27" sent FIN with status "0".
Connection id "0HL9BC18TNP27" stopped.
Connection id "0HL9BC18TNP26" completed keep alive response.
Connection id "0HL9BC18TNP26" received FIN.
Request finished in 179.5263ms 200 application/json; charset=utf-8
Connection id "0HL9BC18TNP26" disconnecting.
Connection id "0HL9BC18TNP29" completed keep alive response.
Request finished in 189.1427ms 200 application/json; charset=utf-8
Connection id "0HL9BC18TNP2B" completed keep alive response.
Request finished in 179.8384ms 200 application/json; charset=utf-8
Connection id "0HL9BC18TNP26" sending FIN.
Connection id "0HL9BC18TNP2E" completed keep alive response.
Connection id "0HL9BC18TNP2E" received FIN.
Request finished in 187.7259ms 200 application/json; charset=utf-8
Connection id "0HL9BC18TNP2B" received FIN.
Connection id "0HL9BC18TNP29" received FIN.
Connection id "0HL9BC18TNP2B" disconnecting.
Connection id "0HL9BC18TNP2E" disconnecting.
Connection id "0HL9BC18TNP29" disconnecting.
Connection id "0HL9BC18TNP26" sent FIN with status "0".
Connection id "0HL9BC18TNP26" stopped.
Connection id "0HL9BC18TNP2B" sending FIN.
Connection id "0HL9BC18TNP2E" sending FIN.
Connection id "0HL9BC18TNP29" sending FIN.
Connection id "0HL9BC18TNP2E" sent FIN with status "0".
Connection id "0HL9BC18TNP2E" stopped.
Connection id "0HL9BC18TNP2B" sent FIN with status "0".
Connection id "0HL9BC18TNP2B" stopped.
Connection id "0HL9BC18TNP29" sent FIN with status "0".
Connection id "0HL9BC18TNP29" stopped.
Connection id "0HL9BC18TNP28" completed keep alive response.
Request finished in 190.027ms 200 application/json; charset=utf-8
Connection id "0HL9BC18TNP28" received FIN.
Connection id "0HL9BC18TNP28" disconnecting.
Connection id "0HL9BC18TNP28" sending FIN.
Connection id "0HL9BC18TNP28" sent FIN with status "0".
Connection id "0HL9BC18TNP28" stopped.
Connection id "0HL9BC18TNP2A" received FIN.
Connection id "0HL9BC18TNP2A" completed keep alive response.
Request finished in 209.3495ms 200 application/json; charset=utf-8
Connection id "0HL9BC18TNP2A" disconnecting.
Connection id "0HL9BC18TNP2A" sending FIN.
Connection id "0HL9BC18TNP2A" sent FIN with status "0".
Connection id "0HL9BC18TNP2A" stopped.
Connection id "0HL9BC18TNP25" completed keep alive response.
Request finished in 223.5798ms 200 application/json; charset=utf-8
Connection id "0HL9BC18TNP25" received FIN.
Connection id "0HL9BC18TNP25" disconnecting.
Connection id "0HL9BC18TNP25" sending FIN.
Connection id "0HL9BC18TNP25" sent FIN with status "0".
Connection id "0HL9BC18TNP25" stopped.
</code>```

答:
Async != parallel. Async does one thing and one thing only, it allows the thread to be returned to the pool when it is idle, so if can do other work instead of sitting idle. Period. That is all. When you await an asynchronous task, you code does not magically move on and keep processing. It "waits" (hence await) for the work to be completed.

If you do want to run a bunch of asynchronous tasks at the same time, you can use Task.WhenAll:

```<code>var tasks = new Task[]
{
    DoFirstAsync(),
    DoSecondAsync(),
    DoThirdAsync()
};
await Task.WhenAll(tasks);
</code>```

This essentially just creates a Task that waits on all the other Tasks to complete, so you can await this instead.

Body:
Any idea how ASP.net core handle concurrent request when a async involved. As you can see from the log below, the request finished time seem like in sequence rather than in parallel or concurrently? I might understand the async wrong, hope someone can explain why below request finished timing is in sequence rather identical timing? I was expecting at least each of the request should finish in almost identical time?

Connection id "0HL9BC18TNP25" started.
Connection id "0HL9BC18TNP26" started.
Connection id "0HL9BC18TNP27" started.
Connection id "0HL9BC18TNP28" started.
Connection id "0HL9BC18TNP29" started.
Connection id "0HL9BC18TNP2A" started.
Connection id "0HL9BC18TNP2B" started.
Connection id "0HL9BC18TNP2C" started.
Connection id "0HL9BC18TNP2D" started.
Connection id "0HL9BC18TNP2E" started.
Connection id "0HL9BC18TNP2C" completed keep alive response.
Request finished in 45.2835ms 200 application/json; charset=utf-8
Connection id "0HL9BC18TNP2C" received FIN.
Connection id "0HL9BC18TNP2C" disconnecting.
Connection id "0HL9BC18TNP2C" sending FIN.
Connection id "0HL9BC18TNP2C" sent FIN with status "0".
Connection id "0HL9BC18TNP2C" stopped.
Connection id "0HL9BC18TNP2D" completed keep alive response.
Request finished in 175.3974ms 200 application/json; charset=utf-8
Connection id "0HL9BC18TNP2D" received FIN.
Connection id "0HL9BC18TNP2D" disconnecting.
Connection id "0HL9BC18TNP2D" sending FIN.
Connection id "0HL9BC18TNP2D" sent FIN with status "0".
Connection id "0HL9BC18TNP2D" stopped.
Connection id "0HL9BC18TNP27" received FIN.
Connection id "0HL9BC18TNP27" completed keep alive response.
Request finished in 171.6836ms 200 application/json; charset=utf-8
Connection id "0HL9BC18TNP27" disconnecting.
Connection id "0HL9BC18TNP27" sending FIN.
Connection id "0HL9BC18TNP27" sent FIN with status "0".
Connection id "0HL9BC18TNP27" stopped.
Connection id "0HL9BC18TNP26" completed keep alive response.
Connection id "0HL9BC18TNP26" received FIN.
Request finished in 179.5263ms 200 application/json; charset=utf-8
Connection id "0HL9BC18TNP26" disconnecting.
Connection id "0HL9BC18TNP29" completed keep alive response.
Request finished in 189.1427ms 200 application/json; charset=utf-8
Connection id "0HL9BC18TNP2B" completed keep alive response.
Request finished in 179.8384ms 200 application/json; charset=utf-8
Connection id "0HL9BC18TNP26" sending FIN.
Connection id "0HL9BC18TNP2E" completed keep alive response.
Connection id "0HL9BC18TNP2E" received FIN.
Request finished in 187.7259ms 200 application/json; charset=utf-8
Connection id "0HL9BC18TNP2B" received FIN.
Connection id "0HL9BC18TNP29" received FIN.
Connection id "0HL9BC18TNP2B" disconnecting.
Connection id "0HL9BC18TNP2E" disconnecting.
Connection id "0HL9BC18TNP29" disconnecting.
Connection id "0HL9BC18TNP26" sent FIN with status "0".
Connection id "0HL9BC18TNP26" stopped.
Connection id "0HL9BC18TNP2B" sending FIN.
Connection id "0HL9BC18TNP2E" sending FIN.
Connection id "0HL9BC18TNP29" sending FIN.
Connection id "0HL9BC18TNP2E" sent FIN with status "0".
Connection id "0HL9BC18TNP2E" stopped.
Connection id "0HL9BC18TNP2B" sent FIN with status "0".
Connection id "0HL9BC18TNP2B" stopped.
Connection id "0HL9BC18TNP29" sent FIN with status "0".
Connection id "0HL9BC18TNP29" stopped.
Connection id "0HL9BC18TNP28" completed keep alive response.
Request finished in 190.027ms 200 application/json; charset=utf-8
Connection id "0HL9BC18TNP28" received FIN.
Connection id "0HL9BC18TNP28" disconnecting.
Connection id "0HL9BC18TNP28" sending FIN.
Connection id "0HL9BC18TNP28" sent FIN with status "0".
Connection id "0HL9BC18TNP28" stopped.
Connection id "0HL9BC18TNP2A" received FIN.
Connection id "0HL9BC18TNP2A" completed keep alive response.
Request finished in 209.3495ms 200 application/json; charset=utf-8
Connection id "0HL9BC18TNP2A" disconnecting.
Connection id "0HL9BC18TNP2A" sending FIN.
Connection id "0HL9BC18TNP2A" sent FIN with status "0".
Connection id "0HL9BC18TNP2A" stopped.
Connection id "0HL9BC18TNP25" completed keep alive response.
Request finished in 223.5798ms 200 application/json; charset=utf-8
Connection id "0HL9BC18TNP25" received FIN.
Connection id "0HL9BC18TNP25" disconnecting.
Connection id "0HL9BC18TNP25" sending FIN.
Connection id "0HL9BC18TNP25" sent FIN with status "0".
Connection id "0HL9BC18TNP25" stopped.

Body:
Async != parallel. Async does one thing and one thing only, it allows the thread to be returned to the pool when it is idle, so if can do other work instead of sitting idle. Period. That is all. When you await an asynchronous task, you code does not magically move on and keep processing. It "waits" (hence await) for the work to be completed.

If you do want to run a bunch of asynchronous tasks at the same time, you can use Task.WhenAll:

var tasks = new Task[]
{
    DoFirstAsync(),
    DoSecondAsync(),
    DoThirdAsync()
};
await Task.WhenAll(tasks);

This essentially just creates a Task that waits on all the other Tasks to complete, so you can await this instead.


来源: stackexchange

问:
how to disable auto resizing in all view controllers
I have to remove the auto-resizing applied on all view controllers in my project. Is there a way to disable auto-resizing applied on all view controllers.</p>

答: You can do it from storyboard by selecting auto layout

ContentLicense: CC BY-SA 3.0


问:
how to only allow letters to be used python statment
I'm making a Morse code program:

```<code>def main ():

    morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
                  "m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}

    phrase = input("please enter your word or words: ")
    for key in phrase:
        print("your word or sentence translated to morse code is : ")
        print(morse_code[key], end = " ")
    if phrase == int or float:
        print("try the input")

    retry()
def retry ():
    main()
retry()
main()
</code>```

How do I print an error if someone enters a number?

Body:
I'm making a Morse code program:

def main ():

    morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
                  "m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}

    phrase = input("please enter your word or words: ")
    for key in phrase:
        print("your word or sentence translated to morse code is : ")
        print(morse_code[key], end = " ")
    if phrase == int or float:
        print("try the input")

    retry()
def retry ():
    main()
retry()
main()

How do I print an error if someone enters a number?

Body:
This is what you need:-

morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
              "m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}

phrase = input("please enter your word or words: ")

if any(char.isdigit() for char in phrase):
    print("try the input")
else:
    print("your word or sentence translated to morse code is : ")
    code = ' '.join(morse_code[key] for key in phrase)
    print(code)


问:
Dynamically add a nested T class and fill it with another T class (GetProperty, GetType, SetValue)
I just want to pass a class T as a parameter. Example:

from:

SetValue (Car.parts, "engine");

to:

SetValue (T.partes, "engine");

simply pass your nested class of a generic as a parameter.

Thank you very much for the help.

HERE THE DETAILED.
but I just need the top one.

Good day, I would like to dynamically fill a class T with some values.
here my example:

This class is familiar.

Class Model model = new ClassModel ();

has a nested class

model.autos = new ClassModel.Auto ();

Write ClassModel = typeof (ClassModel);

var AutoClass = ModelClass.GetProperty ("autos");

var AutoProp = Type.GetType (ClaseAuto.GetMethod.ReturnType.FullName) .GetProperties ();

AutoProp [0] .SetValue (model.autos, 1);

// here this works and passes the parameter, but if it were a class T
How would the value for cars pass?
example:

AutoProp [0] .SetValue (T.autos, 1);

where cars are unknown because the class is T.
and at the same time fill the class T which is easier to identify and fill
since the first T corresponds to a class.

ClassModel.SetValue (T, AutoProp);

after this to corroborate the success of the variable is passed to a
variable when the process ends

/ * Once my class is recovered, I already know all its methods, but inside class T I do not know the methods, but I send the class cars by name = "autos" and so I get to know it but I still do not know how to pass on the values . * /
int result = model.autos.id;

Thank you very much for the help provided.

答:
Simply the class T you get the nested class, then if you want more all its values as a normal class add GetValue (T) and ready to pass the class as if it were a normal class.

the class tests the one daughter class of T

SetValue(T.GetType().GetProperty("proof").GetValue(T) , 1);


问:
Task.Delay in .net fires 125ms early
So I'm having a really strange behavior with a c# task delay that is kind of making me insane.

Context: I'm using C# .net to communicate with one of our devices via R4852. The device needs roughly 200ms to finish each command so I introduced a 250ms delay inside my communication class.

Bug / bad behavior: The delay inside my communication class sometimes waits for 250ms and sometimes only waits for 125ms. This is reproducible and the same behavior occurs when I'm increasing my delay. E.g. if I set my delay to 1000ms every second request will only wait for 875ms, so again there are 125ms missing.
This behavior only occurs if there is no debugger attached and only occurs on some machines. The machine where this software will be used in our production department is having this issue, my machine that I'm working on right now doesn't have this issue. Both are running Windows 10.

How come that there are 125ms missing from time to time?
I already learnt that the Task.Delay method is using a timer with a precision of 15ms. This doesn't explain the missing 125ms as it at most should fire a few milliseconds too late instead of 125m too early.

The following method is the one I use to queue commands to my device. There is a semaphore responsible so that only one command can be executed at a time (_requestSemapohre) so there can only ever be one request being processed.

public async Task<bool> Request(WriteRequest request)
{
    await _requestSemaphore.WaitAsync();    // block incoming calls
    await Task.Delay(Delay);                // delay
    Write(_connectionIdDictionary[request.Connection], request.Request);           // write
    if (request is WriteReadRequest)
    {
        _currentRequest = request as WriteReadRequest;
        var readSuccess = await _readSemaphore.WaitAsync(Timeout); // wait until read of line has finished
        _currentRequest = null;                 // set _currentRequest to null
        _requestSemaphore.Release();            // release next incoming call
        if (!readSuccess)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    else
    {
        if (request is WriteWithDelayRequest)
        {
            await Task.Delay((request as WriteWithDelayRequest).Delay);
        }
        _requestSemaphore.Release();            // release next incoming call
        return true;
    }
}
```

<p>The following code is part of the method that is sending the requests to the method above. I removed some lines to keep it short. The basic stuff (requesting and waiting) is still there</p>

<pre class="lang-cs prettyprint-override"><code>// this command is the first command and will always have a proper delay of 1000ms
var request = new Communication.Requests.WriteRequest(item.Connection, item.Command);
await _translator.Request(request);

// this request is the second request that is missing 125ms
var queryRequest = new Communication.Requests.WriteReadRequest(item.Connection, item.Query);    // query that is being sent to check if the value has been sent properly
if (await _translator.Request(queryRequest))    // send the query to the device and wait for response
{
    if (item.IsQueryValid(queryRequest.Response))   // check result
    {
        item.Success = true;
    }
}
</code>```

The first request that I'm sending to this method is a WriteRequest, the second one a WriteReadRequest.

I discovered this behavior when looking at the serial port communication using a software named Device Monitoring Studio to monitor the serial communication.

Here is a screenshot of the actual serial communication. In this case I was using a delay of 1000ms. You can see that the sens0002 command had a delay of exactly 1 second before it was executed. The next command / query sens?only has a 875ms delay. This screenshot was taken while the debugger was not attached.

Here is another screenshot. The delay was set to 1000ms again but this time the debugger was attached. As you can see the first and second command now both have a delay of roughly 1000ms.

And in the two following screenshots you can see the same behavior with a delay of 250ms (bugged down to 125ms). First screenshot without debugger attached, second one with debugger attached. In the second screenshot you can also see that there is quiet the drift of 35ms but still nowhere close to the 125ms that were missing before.

So what the hell am I looking at here? The quick and dirty solution would be to just increase the delay to 1000ms so that this won't be an issue anymore but I'd rather understand why this issue occurs and how to fix it properly.

Cheers!

答:
As far as I can see, your times are printed as delta to the prev. entry.

In case of the 125/875ms you have 8 intermediate entries with each roughly 15ms (sum roughly 120ms)

In case of 250/1000ms you have 8 intermediate entries with each roughly 5ms (sum roughly 40ms) and the numbers are actually more like 215/960ms.

So, if you add those intermediate delays, the resulting complete delay is roughly the same as far as I can tell.

Answering the question for everyone who just wants a yes / no on the question title: The First Rule of Programming: It's Always Your Fault

It's save to assume, that Task.Delay covers at least the specified amount of time (might be more due to clock resolution). So if it seems to cover a smaller timespan, then the method used to test the actual delay is faulty somehow.

Title: Task.Delay in .net fires 125ms early

Body:
So I'm having a really strange behavior with a c# task delay that is kind of making me insane.

Context: I'm using C# .net to communicate with one of our devices via R4852. The device needs roughly 200ms to finish each command so I introduced a 250ms delay inside my communication class.

Bug / bad behavior: The delay inside my communication class sometimes waits for 250ms and sometimes only waits for 125ms. This is reproducible and the same behavior occurs when I'm increasing my delay. E.g. if I set my delay to 1000ms every second request will only wait for 875ms, so again there are 125ms missing.
This behavior only occurs if there is no debugger attached and only occurs on some machines. The machine where this software will be used in our production department is having this issue, my machine that I'm working on right now doesn't have this issue. Both are running Windows 10.

How come that there are 125ms missing from time to time?
I already learnt that the Task.Delay method is using a timer with a precision of 15ms. This doesn't explain the missing 125ms as it at most should fire a few milliseconds too late instead of 125m too early.

The following method is the one I use to queue commands to my device. There is a semaphore responsible so that only one command can be executed at a time (_requestSemapohre) so there can only ever be one request being processed.

public async Task<bool> Request(WriteRequest request)
{
    await _requestSemaphore.WaitAsync();    // block incoming calls
    await Task.Delay(Delay);                // delay
    Write(_connectionIdDictionary[request.Connection], request.Request);           // write
    if (request is WriteReadRequest)
    {
        _currentRequest = request as WriteReadRequest;
        var readSuccess = await _readSemaphore.WaitAsync(Timeout); // wait until read of line has finished
        _currentRequest = null;                 // set _currentRequest to null
        _requestSemaphore.Release();            // release next incoming call
        if (!readSuccess)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    else
    {
        if (request is WriteWithDelayRequest)
        {
            await Task.Delay((request as WriteWithDelayRequest).Delay);
        }
        _requestSemaphore.Release();            // release next incoming call
        return true;
    }
}

The following code is part of the method that is sending the requests to the method above. I removed some lines to keep it short. The basic stuff (requesting and waiting) is still there

// this command is the first command and will always have a proper delay of 1000ms
var request = new Communication.Requests.WriteRequest(item.Connection, item.Command);
await _translator.Request(request);

// this request is the second request that is missing 125ms
var queryRequest = new Communication.Requests.WriteReadRequest(item.Connection, item.Query);    // query that is being sent to check if the value has been sent properly
if (await _translator.Request(queryRequest))    // send the query to the device and wait for response
{
    if (item.IsQueryValid(queryRequest.Response))   // check result
    {
        item.Success = true;
    }
}

The first request that I'm sending to this method is a WriteRequest, the second one a WriteReadRequest.

I discovered this behavior when looking at the serial port communication using a software named Device Monitoring Studio to monitor the serial communication.

Here is a screenshot of the actual serial communication. In this case I was using a delay of 1000ms. You can see that the sens0002 command had a delay of exactly 1 second before it was executed. The next command / query sens?only has a 875ms delay. This screenshot was taken while the debugger was not attached.

Here is another screenshot. The delay was set to 1000ms again but this time the debugger was attached. As you can see the first and second command now both have a delay of roughly 1000ms.

And in the two following screenshots you can see the same behavior with a delay of 250ms (bugged down to 125ms). First screenshot without debugger attached, second one with debugger attached. In the second screenshot you can also see that there is quiet the drift of 35ms but still nowhere close to the 125ms that were missing before.

So what the hell am I looking at here? The quick and dirty solution would be to just increase the delay to 1000ms so that this won't be an issue anymore but I'd rather understand why this issue occurs and how to fix it properly.

Cheers!


答:
Your first problem you will have is that the if statement is A: after the printing out of the Morsecode version of the letter, and B: it is outside of the for loop completely.

You can rectify this by putting it in the for loop before the printing like so:

```<code>phrase = input("please enter your word or words: ")
print("your word or sentence translated to morse code is : ")
for key in phrase:
if phrase == int or float:
    print("try the input")
else:

    print(morse_code[key], end = " ")
</code>```

However the above code still won't work, as the way you are checking if the current letter being printed out is a int or float isn't how you do it.

The easiest method is to change the codition of the if statement to if key.isdigit():

This will leave you with this final block of code:

```<code>phrase = input("please enter your word or words: ")
print("your word or sentence translated to morse code is : ")
for key in phrase:
    if key.isdigit:
        print("try the input")
    else:

        print(morse_code[key], end = " ")
</code>```

This now works, however, lets say I enter abc123. The output I would get is .-
-...
-.-.
try the input
try the input

as the code is running the forloop regardless of if there are numbers in the input or not. To prevent this, you should check the input for numbers, before you have the for loop printing out the morse code.

```<code>phrase = input("please enter your word or words: ")

while not phrase.isalpha():
    phrase = input("invalid input: ")
print("your word or sentence translated to morse code is : ")
for key in phrase:

    print(morse_code[key], end = " ")
</code>```

If you need any help, let me know!

Title: how to only allow letters to be used python statment

Body:
Your first problem you will have is that the if statement is A: after the printing out of the Morsecode version of the letter, and B: it is outside of the for loop completely.

You can rectify this by putting it in the for loop before the printing like so:

phrase = input("please enter your word or words: ")
print("your word or sentence translated to morse code is : ")
for key in phrase:
if phrase == int or float:
    print("try the input")
else:

    print(morse_code[key], end = " ")

However the above code still won't work, as the way you are checking if the current letter being printed out is a int or float isn't how you do it.

The easiest method is to change the codition of the if statement to if key.isdigit():

This will leave you with this final block of code:

phrase = input("please enter your word or words: ")
print("your word or sentence translated to morse code is : ")
for key in phrase:
    if key.isdigit:
        print("try the input")
    else:

        print(morse_code[key], end = " ")

This now works, however, lets say I enter abc123. The output I would get is .-
-...
-.-.
try the input
try the input

as the code is running the forloop regardless of if there are numbers in the input or not. To prevent this, you should check the input for numbers, before you have the for loop printing out the morse code.

phrase = input("please enter your word or words: ")

while not phrase.isalpha():
    phrase = input("invalid input: ")
print("your word or sentence translated to morse code is : ")
for key in phrase:

    print(morse_code[key], end = " ")

If you need any help, let me know!


问:
Compiler design, creating a language. How?
The Dragon book
is a famous book for designing a compiler. Is there another book like that or a great article about that? And what're the keywords about compilers? I wanna know how a new language is created.</p>

答:
Writing Compilers and Interpreters, by Ronald Mack, is an excellent "practical" text that walks you through the important parts of a compiler and how they are constructed.  The original edition was C, the second edition was C++, and the current edition is Java.

It is a much easier read than the Dragon Book.

ContentLicense: CC BY-SA 2.5


问:
Send email with signature images outlook 2016 VBA
I have followed a tutorial to send automated emails using reminder and calendar appointments.

The "base" is from https://www.extendoffice.com/documents/outlook/1567-outlook-send-schedule-recurring-email.html

The problem with this is the images in signature become html tags.

Ron de Bruin's code here: https://www.rondebruin.nl/win/s1/outlook/signature.htm can add the signature in html and it almost worked.

I get text, font, colors and links correct but the images are empty boxes with red x.

I looked at the source of the message and it seems the code for signature grabs hardcoded relative img sources.

So i tried to add the "replace" code to edit the sources in message to absolute path.

And it worked! But only on my computer.
The images are not added, they are just linked to.

Anyone who has a solution how to add (or attach) the images so that the signature looks correct?

```<code>Private Sub Application_Reminder(ByVal item As Object)
    Dim MItem As MailItem
    Set MItem = Application.CreateItem(olMailItem)

    If item.MessageClass <> "IPM.Appointment" Then
        Exit Sub
    End If
    If item.Categories <> "Beställa material mail" Then ' make sure it's correct category
        Exit Sub
    End If

    If Now > item.End + 6 / 24 Then ' if the appointment time was when computer was off (or long delay) don't email.
        MsgBox item.Subject & " är inte skickat för att det är för sent." ' "subject" is not send because it's too late.
        Exit Sub
    End If

    'Below is from https://www.rondebruin.nl/win/s1/outlook/signature.htm
    SigString = Environ("appdata") & "\Microsoft\Signatures\Axfood.htm"

    If Dir(SigString) <> "" Then
        Signature = GetBoiler(SigString)
    Else
        Signature = ""
    End If

    'replace incorrect img sources.
    Signature = Replace(Signature, "src=" & Chr(34) & "Axfood-filer/image", "src=" & Chr(34) & Environ("appdata") & "/Microsoft/Signatures/Axfood-filer/image")

    ' send email
    MItem.To = item.Location
    MItem.Subject = item.Subject
    MItem.HTMLBody = item.Body & Signature
    MItem.Send
    Set MItem = Nothing
End Sub

Function GetBoiler(ByVal sFile As String) As String
'Dick Kusleika
    Dim fso As Object
    Dim ts As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)
    GetBoiler = ts.readall
    ts.Close
End Function
</code>```

EDIT;

Example img source in the Outlook signature file:

This is edited with the replace function in the code to a absolute path on harddrive.

Signature files can be foung at: C:\Users\<USER>\AppData\Roaming\Microsoft\Signatures

答:
I have found an answer that works on Outlook 2016, and gives an "OK" result on Android/iPhone.

I attach the images through vba and inline them with html code.

```<code>Dim oAttach As Outlook.Attachment
Dim colAttach As Outlook.Attachments

Set colAttach = MItem.Attachments

' attach the images to the email
Set oAttach = colAttach.Add(Environ("appdata") & "/Microsoft/Signatures/Axfood-filer/image001.png")
Set oAttach = colAttach.Add(Environ("appdata") & "/Microsoft/Signatures/Axfood-filer/image003.jpg")
Set oAttach = colAttach.Add(Environ("appdata") & "/Microsoft/Signatures/Axfood-filer/image005.jpg")
Set oAttach = colAttach.Add(Environ("appdata") & "/Microsoft/Signatures/Axfood-filer/image007.jpg")
Set oAttach = colAttach.Add(Environ("appdata") & "/Microsoft/Signatures/Axfood-filer/image009.jpg")

'add the images to signature string with html formatting.
Signature = Signature & "<a href='http://www.axfood.se'><IMG alt='' hspace=0 src='cid:image001.png' align=baseline width=151 border=0></a><br><br>"
Signature = Signature & "<a href='https://www.facebook.com/axfoodkoncernen/'><IMG alt='' hspace=0 src='cid:image003.jpg' align=baseline border=0></a> "
Signature = Signature & "<a href='https://twitter.com/axfood'><IMG alt='' hspace=0 src='cid:image005.jpg' align=baseline border=0></a> "
Signature = Signature & "<a href='https://www.linkedin.com/company/axfood'><IMG alt='' hspace=0 src='cid:image007.jpg' align=baseline border=0></a> "
Signature = Signature & "<a href='https://www.instagram.com/axfoodkoncernen/'><IMG alt='' hspace=0 src='cid:image009.jpg' align=baseline border=0></a> "
</code>```

The result is a correct email for Outlook.

On Android the images are attached but not inlined in email.

On iPhone the images are inlined in email but links are not spanning the images.

iPhone example:

link link link link

image image image image

instead of image beeing the actual link.

Body:
I have followed a tutorial to send automated emails using reminder and calendar appointments.

The "base" is from https://www.extendoffice.com/documents/outlook/1567-outlook-send-schedule-recurring-email.html

The problem with this is the images in signature become html tags.

Ron de Bruin's code here: https://www.rondebruin.nl/win/s1/outlook/signature.htm can add the signature in html and it almost worked.

I get text, font, colors and links correct but the images are empty boxes with red x.

I looked at the source of the message and it seems the code for signature grabs hardcoded relative img sources.

So i tried to add the "replace" code to edit the sources in message to absolute path.

And it worked! But only on my computer.
The images are not added, they are just linked to.

Anyone who has a solution how to add (or attach) the images so that the signature looks correct?

Private Sub Application_Reminder(ByVal item As Object)
    Dim MItem As MailItem
    Set MItem = Application.CreateItem(olMailItem)

    If item.MessageClass <> "IPM.Appointment" Then
        Exit Sub
    End If
    If item.Categories <> "Beställa material mail" Then ' make sure it's correct category
        Exit Sub
    End If

    If Now > item.End + 6 / 24 Then ' if the appointment time was when computer was off (or long delay) don't email.
        MsgBox item.Subject & " är inte skickat för att det är för sent." ' "subject" is not send because it's too late.
        Exit Sub
    End If

    'Below is from https://www.rondebruin.nl/win/s1/outlook/signature.htm
    SigString = Environ("appdata") & "\Microsoft\Signatures\Axfood.htm"

    If Dir(SigString) <> "" Then
        Signature = GetBoiler(SigString)
    Else
        Signature = ""
    End If

    'replace incorrect img sources.
    Signature = Replace(Signature, "src=" & Chr(34) & "Axfood-filer/image", "src=" & Chr(34) & Environ("appdata") & "/Microsoft/Signatures/Axfood-filer/image")

    ' send email
    MItem.To = item.Location
    MItem.Subject = item.Subject
    MItem.HTMLBody = item.Body & Signature
    MItem.Send
    Set MItem = Nothing
End Sub

Function GetBoiler(ByVal sFile As String) As String
'Dick Kusleika
    Dim fso As Object
    Dim ts As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)
    GetBoiler = ts.readall
    ts.Close
End Function

EDIT;

Example img source in the Outlook signature file:

This is edited with the replace function in the code to a absolute path on harddrive.

Signature files can be foung at: C:\Users\<USER>\AppData\Roaming\Microsoft\Signatures

Body:
I have found an answer that works on Outlook 2016, and gives an "OK" result on Android/iPhone.

I attach the images through vba and inline them with html code.

Dim oAttach As Outlook.Attachment
Dim colAttach As Outlook.Attachments

Set colAttach = MItem.Attachments

' attach the images to the email
Set oAttach = colAttach.Add(Environ("appdata") & "/Microsoft/Signatures/Axfood-filer/image001.png")
Set oAttach = colAttach.Add(Environ("appdata") & "/Microsoft/Signatures/Axfood-filer/image003.jpg")
Set oAttach = colAttach.Add(Environ("appdata") & "/Microsoft/Signatures/Axfood-filer/image005.jpg")
Set oAttach = colAttach.Add(Environ("appdata") & "/Microsoft/Signatures/Axfood-filer/image007.jpg")
Set oAttach = colAttach.Add(Environ("appdata") & "/Microsoft/Signatures/Axfood-filer/image009.jpg")

'add the images to signature string with html formatting.
Signature = Signature & "<a href='http://www.axfood.se'><IMG alt='' hspace=0 src='cid:image001.png' align=baseline width=151 border=0></a><br><br>"
Signature = Signature & "<a href='https://www.facebook.com/axfoodkoncernen/'><IMG alt='' hspace=0 src='cid:image003.jpg' align=baseline border=0></a> "
Signature = Signature & "<a href='https://twitter.com/axfood'><IMG alt='' hspace=0 src='cid:image005.jpg' align=baseline border=0></a> "
Signature = Signature & "<a href='https://www.linkedin.com/company/axfood'><IMG alt='' hspace=0 src='cid:image007.jpg' align=baseline border=0></a> "
Signature = Signature & "<a href='https://www.instagram.com/axfoodkoncernen/'><IMG alt='' hspace=0 src='cid:image009.jpg' align=baseline border=0></a> "

The result is a correct email for Outlook.

On Android the images are attached but not inlined in email.

On iPhone the images are inlined in email but links are not spanning the images.

iPhone example:

link link link link

image image image image

instead of image beeing the actual link.


问:
Can't get height-attribute in Bootstrap 4 alpha to work
I'm learning Bootstrap, and I can't get the height attribute in v4 (e.g.: "row h-25") to work.

I've tried to add another CSS which sets the height of "container-fluid" as well as html and body to 100%, which someone proposed as a solution in another answer. Still doesn't work, I'm afraid. I'm using Visual Studio, and when I open "NuGet - Solution", it says that the bootstrap version is 'v4.0.0-alpha'.

Any help would be greatly appreciated.

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <link href="Content/custom.css" rel="stylesheet" />
    <script src="scripts/angular.min.js"></script>
</head>
<body>
    <div class="container-fluid" style="background-color: #e7fdd6">
        <div class="row h-25" style="background-color: #eee">
            <div class="col-xs-6 col-sm-6 col-md-3 col-lg-3"><p>Customer</p><!-- These are just rough drafts while I learn the grid system. --></div>
            <div class="col-md-3 col-lg-3 hidden-xs hidden-sm"><p>Power</p></div>
            <div class="col-md-3 col-lg-3 hidden-xs hidden-sm"><p>Panels</p></div>
            <div class="col-xs-6 col-sm-6 col-md-3 col-lg-3"><p>Projects</p></div>
        </div>

        <div class="row h-25" style="background-color: #eee">
            <div class="col-xs-6 col-sm-6 col-md-3 col-lg-3"><p>Customer-slider</p></div>
            <div class="col-md-3 col-lg-3 hidden-xs hidden-sm"><p>Power amount</p></div>
            <div class="col-md-3 col-lg-3 hidden-xs hidden-sm"><p>Panels</p></div>
            <div class="col-xs-6 col-sm-6 col-md-3 col-lg-3"><p>Projects-slider</p></div>
        </div>

        <div class="row h-25">
            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"><img src="Content/picture.jpg" alt="Park" align="middle" /> <!-- Bilde --></div>
        </div>

        <div class="row h-25">
            <div class="col-lg-6 col-md-6-col-sm-12 col-xs-12"><!-- Graph 1 --></div>
            <div class="col-lg-6 col-md-6 hidden-sm hidden-xs"><!-- Graph 2 --></div>
        </div>

    </div>
</body>
</html>
</code>```

custom.css:

```<code>.container-fluid {
    height: 100%;
}

html, body {
    height: 100%;
}
</code>```

答:
It looks like your NuGet reference is an older alpha version of Bootstrap 4. The latest version, as of right now, is 4.0.0-beta2.

In the VS NuGet Package Manager (right-click the solution and choose "Manage NuGet Packages for Solution..."), you should see that there are updates to the package. If not, make sure the "Include prerelease" checkbox is checked.

Body:
I'm learning Bootstrap, and I can't get the height attribute in v4 (e.g.: "row h-25") to work.

I've tried to add another CSS which sets the height of "container-fluid" as well as html and body to 100%, which someone proposed as a solution in another answer. Still doesn't work, I'm afraid. I'm using Visual Studio, and when I open "NuGet - Solution", it says that the bootstrap version is 'v4.0.0-alpha'.

Any help would be greatly appreciated.

<!DOCTYPE html>

    <title></title>
    <meta charset="utf-8" />
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <link href="Content/custom.css" rel="stylesheet" />

Customer

Power

Panels

Projects

Customer-slider

Power amount

Panels

Projects-slider

custom.css:

.container-fluid {
    height: 100%;
}

html, body {
    height: 100%;
}


问:
performance of unsigned vs signed integers
Is there any performance gain/loss by using unsigned integers over signed integers?

If so, does this goes for short and long as well?

答:
unsigned leads to the same or better performance than signed.
Some examples:

Division by a constant which is a power of 2 (see also the answer from FredOverflow)

Division by a constant number (for example, my compiler implements division by 13 using 2 asm instructions for unsigned, and 6 instructions for signed)

Checking whether a number is even (i have no idea why my MS Visual Studio compiler implements it with 4 instructions for signed numbers; gcc does it with 1 instruction, just like in the unsigned case)

short usually leads to the same or worse performance than int (assuming sizeof(short) < sizeof(int)). Performance degradation happens when you assign a result of an arithmetic operation (which is usually int, never short) to a variable of type short, which is stored in the processor's register (which is also of type int). All the conversions from short to int take time and are annoying.

Note: some DSPs have fast multiplication instructions for the signed short type; in this specific case short is faster than int.

As for the difference between int and long, i can only guess (i am not familiar with 64-bit architectures). Of course, if int and long have the same size (on 32-bit platforms), their performance is also the same.

A very important addition, pointed out by several people:

What really matters for most applications is the memory footprint and utilized bandwidth. You should use the smallest necessary integers (short, maybe even signed/unsigned char) for large arrays.

This will give better performance, but the gain is nonlinear (i.e. not by a factor of 2 or 4) and somewhat unpredictable - it depends on cache size and the relationship between calculations and memory transfers in your application.


问:
Resolving Youtube channel like https://youtube.com/c/xyz
It is fairly easy to request youtube channel or user info when you have a url like yourtube.com/channel/xyz or youtube.com/user/xyz because you can just strip the username/channelid from the url. However I have problems associating an url like https://youtube.com/c/xyz to any kind of resource.

It doesnt seem to be a user, nor a channel?

答:
Okay. It turns out it's a custom url you can manually request from YouTube. It has no connection to a userName or channelID.

There also is currently no way to use the API to get info from a custom url, so instead you would need to request the url and look in the meta tags for the actual channelID. Here is a PHP script to do just that. Hope that helps.


问:
NPOI does not change cell´s font color
I am trying to change a cell's font color conditionally. This is my last try:

```<code>IWorkbook wb = null;

using (FileStream _fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
    wb = WorkbookFactory.Create(_fileStream);
    _fileStream.Close();
}

ISheet sheet = wb.GetSheet(sheetName);
IFont font = wb.CreateFont();
...
...

// within a loop
ICell cell = sheet.GetRow(r).GetCell(col);
if (integrity < 1)
{
    ICellStyle redStyle = cell.CellStyle;
    font.Color = IndexedColors.Red.Index;
    redStyle.SetFont(font);
    cell.CellStyle = redStyle;
}
else
{
    ICellStyle normalStyle = cell.CellStyle;
    font.Color = XSSFFont.DEFAULT_FONT_COLOR;
    normalStyle.SetFont(font);
    cell.CellStyle = normalStyle;
}
</code>```

However, the font does not change when the condition is met. It seems like the style is applied for all cells instead of the cell I am getting within the loop. I have read some questions related to this problem but I can not make it work.

This new try is formatting all cells. No matter whether it meets the condition or not

```<code>ICellStyle redStyle = cell.CellStyle;
font.Color = IndexedColors.Red.Index;
redStyle.SetFont(font);

//This is how I am trying to change cells format
if (integrity < 1)
{
    cell.CellStyle.SetFont(font);
}
</code>```

Joao response would format all cells with a "normalStyle"

答:
So I end up defining a style beforehand which I set to the cells that meet the condition.

```<code>IFont redfont = wb.CreateFont();
redfont.Color = IndexedColors.Red.Index;
redfont.FontHeight = 8;
ICellStyle style = wb.CreateCellStyle();

...
if (integrity < 1)
{
    style.CloneStyleFrom(cell.CellStyle);
    style.SetFont(redfont);
    cell.CellStyle = style;
}
</code>```

Thanks for the help!

Title: NPOI does not change cell´s font color

Body:
I am trying to change a cell's font color conditionally. This is my last try:

IWorkbook wb = null;

using (FileStream _fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
    wb = WorkbookFactory.Create(_fileStream);
    _fileStream.Close();
}

ISheet sheet = wb.GetSheet(sheetName);
IFont font = wb.CreateFont();
...
...

// within a loop
ICell cell = sheet.GetRow(r).GetCell(col);
if (integrity < 1)
{
    ICellStyle redStyle = cell.CellStyle;
    font.Color = IndexedColors.Red.Index;
    redStyle.SetFont(font);
    cell.CellStyle = redStyle;
}
else
{
    ICellStyle normalStyle = cell.CellStyle;
    font.Color = XSSFFont.DEFAULT_FONT_COLOR;
    normalStyle.SetFont(font);
    cell.CellStyle = normalStyle;
}

However, the font does not change when the condition is met. It seems like the style is applied for all cells instead of the cell I am getting within the loop. I have read some questions related to this problem but I can not make it work.

This new try is formatting all cells. No matter whether it meets the condition or not

ICellStyle redStyle = cell.CellStyle;
font.Color = IndexedColors.Red.Index;
redStyle.SetFont(font);

//This is how I am trying to change cells format
if (integrity < 1)
{
    cell.CellStyle.SetFont(font);
}

Joao response would format all cells with a "normalStyle"

Body:
So I end up defining a style beforehand which I set to the cells that meet the condition.

IFont redfont = wb.CreateFont();
redfont.Color = IndexedColors.Red.Index;
redfont.FontHeight = 8;
ICellStyle style = wb.CreateCellStyle();

...
if (integrity < 1)
{
    style.CloneStyleFrom(cell.CellStyle);
    style.SetFont(redfont);
    cell.CellStyle = style;
}

Thanks for the help!


问:
Margin below <TextView/> in <ConstraintLayout/> not working
There is a simple layout with TextView and RecyclerView inside a ConstraintLayout.

```<code>    <android.support.constraint.ConstraintLayout
        android:id="@+id/clSelectedPatient"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tvSelectPatient"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Lifcare"
            android:textSize="18sp"
            android:textStyle="bold"
            android:layout_marginBottom="100dp"
            app:layout_constraintBottom_toTopOf="@+id/rvPatients"
            app:layout_constraintTop_toTopOf="parent" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rvPatients"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            app:layout_constraintTop_toBottomOf="@+id/tvSelectPatient"/>

    </android.support.constraint.ConstraintLayout>
</code>```

android:layout_marginBottom="100dp" below TextView is not working.

答:
Add

app:layout_constraintBottom_toBottomOf="parent"

to your RecyclerView

Body:
There is a simple layout with TextView and RecyclerView inside a ConstraintLayout.

    <android.support.constraint.ConstraintLayout
        android:id="@+id/clSelectedPatient"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tvSelectPatient"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Lifcare"
            android:textSize="18sp"
            android:textStyle="bold"
            android:layout_marginBottom="100dp"
            app:layout_constraintBottom_toTopOf="@+id/rvPatients"
            app:layout_constraintTop_toTopOf="parent" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rvPatients"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            app:layout_constraintTop_toBottomOf="@+id/tvSelectPatient"/>

    </android.support.constraint.ConstraintLayout>

android:layout_marginBottom="100dp" below TextView is not working.


问:
How to test if a class reference implements an interface?
How can I test if a class reference implements an interface?

Note that the is and instanceof operators do not work with Class references.

Example:

```<code>    public function set someClassref(value:Class):void
    {
        if(value is IMyInterface)
        {
            _someClassref = value;
        }
        else
        {
            //
        }
    }
</code>```

答: AS3 - Can I know if a class implements an interface (or is a subclass of another class)? has what appear to be the two most common solutions.</p>

Body:
How can I test if a class reference implements an interface?

Note that the is and instanceof operators do not work with Class references.

Example:

    public function set someClassref(value:Class):void
    {
        if(value is IMyInterface)
        {
            _someClassref = value;
        }
        else
        {
            //
        }
    }


问:
Looks for patterns across different lines
I have a file like this (test.txt):

```<code>abc
12
34
def
56
abc
ghi
78
def
90
</code>```

And I would like to search the 78 which is enclosed by "abc\nghi" and "def". Currently, I know I can do this by:

```<code>cat test.txt | awk '/abc/,/def/' | awk '/ghi/,'/def/'
</code>```

Is there any better way?

答:
grep alternative

```<code>$ grep -Pazo '(?s)(?<=abc\nghi)(.*)(?=def)' file
</code>```

but I think awk will be better

Body:
I have a file like this (test.txt):

abc
12
34
def
56
abc
ghi
78
def
90

And I would like to search the 78 which is enclosed by "abc\nghi" and "def". Currently, I know I can do this by:

cat test.txt | awk '/abc/,/def/' | awk '/ghi/,'/def/'

Is there any better way?

Body:
grep alternative

$ grep -Pazo '(?s)(?<=abc\nghi)(.*)(?=def)' file

but I think awk will be better


问:
Two different color in background and Inside center box is container in html
In this picture  - sample outline

```<code><nav class="navbar navbar-inverse navbar-fixed-top">
  <div class="container">
  </div>
</nav>
</code>```

答:
This question could be clarified but if I'm right you want the two to have different colors
You need to see the class before them and in css edit the class like </p>

```<code> .container{
background-color: red !important;
}
</code>```

<p>Of this for each element especially when using bootstrap remember to put !important
Behind anything that would override the normal  setup </p>

Body: In this picture  - sample outline

Body:
This question could be clarified but if I'm right you want the two to have different colors
You need to see the class before them and in css edit the class like

 .container{
background-color: red !important;
}

Of this for each element especially when using bootstrap remember to put !important
Behind anything that would override the normal  setup


问:
grepl for dplyr sql table?
is there a workaround to use something like

```<code>filter(df, grepl("A|B|C",location))
</code>```

for a dplyr SQL table? In SQL it is probalby a LIKE. Of cource I could convert the SQL table to a R data table, but it is very large. (http://cran.r-project.org/web/packages/dplyr/vignettes/databases.html) At the moment I get

```<code>Error in sqliteSendQuery(conn, statement) :
  error in statement: no such function: GREPL
</code>```

thx
Christof

答:
Using sql to translate the expression directly into sql is one option.

```<code>sql_table %>% filter( sql("location LIKE 'A%'
                           OR location LIKE 'B%'
                           OR location LIKE 'C%'")
</code>```

Which will inject the following into the WHERE statement of your query:

```<code><SQL> location LIKE 'A%' OR location LIKE 'B%' OR location LIKE 'C%'
</code>```

Title: grepl for dplyr sql table?

Body:
is there a workaround to use something like

filter(df, grepl("A|B|C",location))

for a dplyr SQL table? In SQL it is probalby a LIKE. Of cource I could convert the SQL table to a R data table, but it is very large. (http://cran.r-project.org/web/packages/dplyr/vignettes/databases.html) At the moment I get

Error in sqliteSendQuery(conn, statement) :
  error in statement: no such function: GREPL

thx
Christof

Body:
Using sql to translate the expression directly into sql is one option.

sql_table %>% filter( sql("location LIKE 'A%'
                           OR location LIKE 'B%'
                           OR location LIKE 'C%'")

Which will inject the following into the WHERE statement of your query:

<SQL> location LIKE 'A%' OR location LIKE 'B%' OR location LIKE 'C%'


问:
How to access Instagram feed of any user with new Graph API?
Facebook recently introduced Instagram Graph API, which allows to fetch data from Instagram page that is connected to your Facebook company page, instagram.com/developers states:

The Instagram Graph API is Now Available to All Developers.

  For Non-Business Instagram Accounts please continue to use the existing Instagram API.

So, for example, if my company has account instagram.com/my_first_company, I can only retrieve its feed and no one else.

Using old Instagram API to retrieve public_content permission (access to any feed) is no longer an option too, from old API documetation:

public_content - to read any public profile info and media on a user’s
  behalf (applications no longer accepted)

What will happen to existing tools that have public_content permission? (for example, there are tons of plugins for various CMS that allow to display recent Instagram photos)

Is there any valid way to access public_content (access to any feed) right now (besides fetching HTML pages of Instagram website)?

Are there any plans to enable Graph API for non-business customers, of so when?

UPD. There seem to be ?__a=1 endpoint that allows to get access to recent photos of any public feed without any tokens. But it's not official and no one knows when/if Instagram will close it. If you do - please let me know.

UPD 2. Instagram removed ?__a=1 endpoint, not sure for how long, probably forever. Currently the only way to access instagram feed is to scrap instagram.com website, which is a horror.

答:
Prerequisite: You first need the business Instagram account to be linked with FB Page. https://help.instagram.com/356902681064399 - That one can do from the profile page of Instagram account.

Get the Instagram business account id:
graph.facebook.com/v2.8/<fbPageId>?fields=instagram_business_account. (the fbPageId is the page id of the facebook page the account is linked)

To fetch instagram media feed: graph.facebook.com/v2.8/<igBusinessId>/media to fetch the media feed of the Instagram account. (the igBusinessId is the id returned in above linked instagram_business_account) - This is still owned media as per the page access_token. Not any other user's feed.

All other endpoints (such as comments moderation, detailed insights API) mentioned here works on the business media list returned on above call.

Please note:
This still does not allow to fetch un-authenticated user's Instagram feed. That is not possible via API now. There is no valid way via API to get to public_content scope. There can be few Instagram Marketing partners for which this is enabled. But, in general the scope is deprecated now!

Currently, for FB graph API to work we need linked business page to Instagram account. As above apis uses page tokens.


问:
Hibernate ID generator - Option for both set the id myself, or hibernate generate it
Is there some Hibernate's primary key generator (as "assigned" or "identity" for example) that I can both set the id myself, or hibernate generate it?</p>

答:
You can use Guids, or take a look at Hi Low algorithm. This allows each client to maintain a block of id's to use.

Guids are probably the best bet for generating yourself as they are globally unique.

Keep your mapping as "assigned" and set the Guid on the entity before persisting.


问:
How to start parallel releases in VSTS?
We have 10 projects to release. It would be a time saver to start or create those releases in parallel. Right now we have to click and approve 10 pipelines. It takes around half an hour and 30 clicks.

Facts about Architecture

every microservice has its own pipeline

every pipeline has 3 artifacts

答:
Enable the Continuous Delivery trigger on each release definition.

Don't require approvals for lower environments within your deployment pipeline. Set the deployment condition for your lower environment to "After release is created".

That will immediately start deploying to the chosen environments after artifacts are published.

Then promote each service to the next stage in your pipeline as it's ready to go.

Since you stated they're microservices, they should be able to be deployed independently of one another with no degredation of service. Breaking changes should be extremely rare. If you find that you have to deploy many services in lock-step, you probably have an architecture problem, because the entire point of microservices is that they are independent of each other. At that point, you're no longer working with microservices, you're working with small, tightly coupled services.

Title: How to start parallel releases in VSTS?


问:
Count milliseconds between two times
I need an algorithm that counts milliseconds between these times

```<code>HH:MM:SS,MS  --> HH:MM:SS,MS

00:08:50,800 --> 00:08:55,250
</code>```

I write a java code for 4 times but I think I did not understand the idea, I searched for it but all solutions used a libraries and I do not want to use a library.

Here is the java code I wrote, but it does not give me correct offset

```<code>private int findOffset(Time t1, Time t2) {
        int offset = 0;
        int diffHH = (t2.getHH() - t1.getHH());
        int diffMM = (t2.getMM() - t1.getMM());
        int diffSS = (t2.getSS() - t1.getSS());
        int diffMS = (t2.getMS() - t1.getMS());
        if (diffHH != 0) {
            if (diffHH < 0) {
                diffHH = 24 - t1.getHH() + t2.getHH();
            }
            offset += (3600000 * diffHH);
        }

        if (diffMM != 0) {
            if (diffMM < 0) {
                diffMM = 60 - t1.getMM() + t2.getMM();
            }
            offset += (60000 * diffMM);
        }
        if (diffSS != 0) {
            if (diffSS < 0) {
                diffSS = 60 - t1.getSS() + t2.getSS();
            }
            offset += (1000 * diffSS);
        }

        if (diffMS != 0) {

            if (diffMS < 0) {
                diffMS =  t1.getMS() + t2.getMS();
            }

            offset -= diffMS;
        }

        return offset;
    }
</code>```

here is another code

```<code>private int findOffset2(Time t1, Time t2) {
        int offset = 0;
        int hh1 = t1.getHH(), hh2 = t2.getHH();
        int mm1 = t1.getMM(), mm2 = t2.getMM();
        int ss1 = t1.getSS(), ss2 = t2.getSS();
        int ms1 = t1.getMS(), ms2 = t2.getMS();

        while (hh1 != hh2 || mm1 != mm2
                || ss1 != ss2 || ms1 != ms2) {
            offset++;

            ms1++;
            while (ms1 >= 1000) {
                ss1++;

                while (ss1 >= 60) {
                    ss1 -= 60;
                    mm1++;
                }

                while (mm1 >= 60) {
                    mm1 -= 60;
                    hh1++;
                }

                ms1 -= 1000;
            }

            if(hh1 == hh2 && mm1 == mm2
                && ss1 == ss2 && ms1 == ms2){
                  System.out.println("test");
                }

        }

        return offset;
    }
</code>```

答:
The idea is to convert Time to ms and just return the diff :

```<code>private int timeToMs(Time t) {
    return t.getHH() * 60 * 60 * 1000 + t.getMM() * 60 * 1000 + t.getSS() * 1000 + t.getMS();
}

private int findOffset(Time begin, Time end) {
    return timeToMs(end) - timeToMs(begin);
}
</code>```

EDIT : This answer assumes that the given Times are in the same day.

Title: Count milliseconds between two times

Body:
I need an algorithm that counts milliseconds between these times

HH:MM:SS,MS  --> HH:MM:SS,MS

00:08:50,800 --> 00:08:55,250

I write a java code for 4 times but I think I did not understand the idea, I searched for it but all solutions used a libraries and I do not want to use a library.

Here is the java code I wrote, but it does not give me correct offset

private int findOffset(Time t1, Time t2) {
        int offset = 0;
        int diffHH = (t2.getHH() - t1.getHH());
        int diffMM = (t2.getMM() - t1.getMM());
        int diffSS = (t2.getSS() - t1.getSS());
        int diffMS = (t2.getMS() - t1.getMS());
        if (diffHH != 0) {
            if (diffHH < 0) {
                diffHH = 24 - t1.getHH() + t2.getHH();
            }
            offset += (3600000 * diffHH);
        }

        if (diffMM != 0) {
            if (diffMM < 0) {
                diffMM = 60 - t1.getMM() + t2.getMM();
            }
            offset += (60000 * diffMM);
        }
        if (diffSS != 0) {
            if (diffSS < 0) {
                diffSS = 60 - t1.getSS() + t2.getSS();
            }
            offset += (1000 * diffSS);
        }

        if (diffMS != 0) {

            if (diffMS < 0) {
                diffMS =  t1.getMS() + t2.getMS();
            }

            offset -= diffMS;
        }

        return offset;
    }

here is another code

private int findOffset2(Time t1, Time t2) {
        int offset = 0;
        int hh1 = t1.getHH(), hh2 = t2.getHH();
        int mm1 = t1.getMM(), mm2 = t2.getMM();
        int ss1 = t1.getSS(), ss2 = t2.getSS();
        int ms1 = t1.getMS(), ms2 = t2.getMS();

        while (hh1 != hh2 || mm1 != mm2
                || ss1 != ss2 || ms1 != ms2) {
            offset++;

            ms1++;
            while (ms1 >= 1000) {
                ss1++;

                while (ss1 >= 60) {
                    ss1 -= 60;
                    mm1++;
                }

                while (mm1 >= 60) {
                    mm1 -= 60;
                    hh1++;
                }

                ms1 -= 1000;
            }

            if(hh1 == hh2 && mm1 == mm2
                && ss1 == ss2 && ms1 == ms2){
                  System.out.println("test");
                }

        }

        return offset;
    }

Body:
The idea is to convert Time to ms and just return the diff :

private int timeToMs(Time t) {
    return t.getHH() * 60 * 60 * 1000 + t.getMM() * 60 * 1000 + t.getSS() * 1000 + t.getMS();
}

private int findOffset(Time begin, Time end) {
    return timeToMs(end) - timeToMs(begin);
}

EDIT : This answer assumes that the given Times are in the same day.


问:
Is it possible to use Include with a string value of the field name?

I want to load an SharePoint Project Server Project using CSOM

```<code>var proj = ctx.LoadQuery(ctx.Projects
        .Where(p => p.Id == projGuid)
        .Include(p => p.Id, p => p.Name));

ctx.ExecuteQuery();
</code>```

I needed the Include() to be dynamic so I did this:

```<code>Expression<Func<PublishedTask, object>>[] funcArray
            = new Expression<Func<PublishedTask, object>>[2];

    funcArray[0] = p => p.Name;
    funcArray[1] = p => p.Id;

var proj = ctx.LoadQuery(ctx.Projects
        .Where(p => p.Id == projGuid)
        .Include(funcArray));

ctx.ExecuteQuery();
</code>```

Now I am only get the information of which property has to be loaded from a String, so I tried something like this:

```<code>funcArray[0] = p => p.GetType().GetProperty("Name");
funcArray[1] = p => p.GetType().GetProperty("Id");
</code>```

That doesn't work and I am not quite sure If I am doing it right or if it is even possible to do it.

答:
Instead of passing an array of functions, you can pass a comma separated string and use some Linq to split them and include each one in query:

```<code>var includeFields = "Name,Id";

var proj = ctx.Projects.GetByGuid(projGuid);

foreach (var fieldName in includeFields.Split(','))
{
    ctx.Load(proj, includes => includes[fieldName]);
}

ctx.ExecuteQuery();
</code>```

You can also use the method "GetByGuid" instead of a Linq Where.

Body:
I want to load an SharePoint Project Server Project using CSOM

var proj = ctx.LoadQuery(ctx.Projects
        .Where(p => p.Id == projGuid)
        .Include(p => p.Id, p => p.Name));

ctx.ExecuteQuery();

I needed the Include() to be dynamic so I did this:

Expression<Func<PublishedTask, object>>[] funcArray
            = new Expression<Func<PublishedTask, object>>[2];

    funcArray[0] = p => p.Name;
    funcArray[1] = p => p.Id;

var proj = ctx.LoadQuery(ctx.Projects
        .Where(p => p.Id == projGuid)
        .Include(funcArray));

ctx.ExecuteQuery();

Now I am only get the information of which property has to be loaded from a String, so I tried something like this:

funcArray[0] = p => p.GetType().GetProperty("Name");
funcArray[1] = p => p.GetType().GetProperty("Id");

That doesn't work and I am not quite sure If I am doing it right or if it is even possible to do it.

Body:
Instead of passing an array of functions, you can pass a comma separated string and use some Linq to split them and include each one in query:

var includeFields = "Name,Id";

var proj = ctx.Projects.GetByGuid(projGuid);

foreach (var fieldName in includeFields.Split(','))
{
    ctx.Load(proj, includes => includes[fieldName]);
}

ctx.ExecuteQuery();

You can also use the method "GetByGuid" instead of a Linq Where.


问:
Invalid table name error, when execute alter stored procedure in oracle
```<code>-- Disable constaint, good
CREATE OR REPLACE PROCEDURE cpl_disable_constraint(table_name IN varchar2, constraint_name IN varchar2)
AS

BEGIN
   execute immediate 'ALTER TABLE :1 DISABLE CONSTRAINT :2' using table_name, constraint_name;
END;
/

-- Bug
declare
  table_name varchar2(100) := 'ADV_TEST_COURSE_CREDIT';
  column_name varchar2(100) := 'SEQUENCE_NUMBER';
begin
  cpl_disable_constraint(table_name, column_name);
end;
/
</code>```

I'm getting these errors:

ORA-00903: invalid table name

ORA-06512: at "SISD_OWNER.CPL_DISABLE_CONSTRAINT", line 5

ORA-06512: at line 5

00000 -  "invalid table name"

Any idea?

答:
As a_horse_with_no_name mentioned, you can't pass an identifier to execute immediate as a parameter. You have to put it in the SQL statement.

```<code>execute immediate 'ALTER TABLE ' || table_name || ' DISABLE CONSTRAINT :1' using constraint_name;
</code>```

Note that this will open you up to SQL Injection if you don't carefully validate the table_name variable. I usually do something like this before calling execute immediate, to make sure the table_name variable is the valid and correct table name for the constraint, and not some malicious string like null; DROP TABLE ADV_TEST_COURSE_CREDIT;:

```<code>select c.table_name into table_name from user_constraints c where c.constraint_name = constraint_name;
</code>```

(By the way, this is part of why people often choose a prefix for local PL/SQL variable names, like "v_table_name", to keep them separate from column names. You can see it's a little confusing in the query above.)

Also I'd like to point out that in your function definition, you're calling the second parameter "constraint_name", but in the anonymous block you're calling it "column_name".

Body:
-- Disable constaint, good
CREATE OR REPLACE PROCEDURE cpl_disable_constraint(table_name IN varchar2, constraint_name IN varchar2)
AS

BEGIN
   execute immediate 'ALTER TABLE :1 DISABLE CONSTRAINT :2' using table_name, constraint_name;
END;
/

-- Bug
declare
  table_name varchar2(100) := 'ADV_TEST_COURSE_CREDIT';
  column_name varchar2(100) := 'SEQUENCE_NUMBER';
begin
  cpl_disable_constraint(table_name, column_name);
end;
/

I'm getting these errors:

ORA-00903: invalid table name

ORA-06512: at "SISD_OWNER.CPL_DISABLE_CONSTRAINT", line 5

ORA-06512: at line 5

00000 -  "invalid table name"

Any idea?

Body:
As a_horse_with_no_name mentioned, you can't pass an identifier to execute immediate as a parameter. You have to put it in the SQL statement.

execute immediate 'ALTER TABLE ' || table_name || ' DISABLE CONSTRAINT :1' using constraint_name;

Note that this will open you up to SQL Injection if you don't carefully validate the table_name variable. I usually do something like this before calling execute immediate, to make sure the table_name variable is the valid and correct table name for the constraint, and not some malicious string like null; DROP TABLE ADV_TEST_COURSE_CREDIT;:

select c.table_name into table_name from user_constraints c where c.constraint_name = constraint_name;

(By the way, this is part of why people often choose a prefix for local PL/SQL variable names, like "v_table_name", to keep them separate from column names. You can see it's a little confusing in the query above.)

Also I'd like to point out that in your function definition, you're calling the second parameter "constraint_name", but in the anonymous block you're calling it "column_name".


问:
You seem to not be depending on "@angular/core". This is an error
I want to create an angular 2 App with angular cli

I have written in the cmd:

npm install angular-cli -g

then:

ng firstngapp

but it show me an error when I write npm start !

I don't understand the problem

答:
While running ng serve you should be in the app's/project's directory.

If you run the command in another directory you get the error:

You seem to not be depending on "@angular/core". This is an error.

ContentLicense: CC BY-SA 4.0


问:
PDFtk command not running from exec
I've moved my code form one WAMP computer to another and the code that runs pdftk stopped working. I've compared the permissions on pdftk.exe and they are the same on both machines. When I run the same command from a command prompt, it works. I add exec("whoami") to the script and the user is the same on both computers. When I run something like exec('dir 2>&1', $out) it executes so I know exec is working form within php.

I've created a trivial php file to test and it doesn't work.

```<code><?php
$String = 'pdftk.exe > "c:\temp\temp.txt"';
exec("$String");
exec("pdftk.exe > \"c:\temp\temp.txt\"");
?>
</code>```

Both exec command result in a 0 byte file being created.

if I run

```<code>pdftk.exe > "c:\temp\temp.txt"
</code>```

from a command line it puts the output of pdftk.exe into the temp.txt file as expected.

This seems like is must be some kind of permissions issue, but permissions on the executable seem to be the same. Losing my mind on this.

答:
In my opinion, first line should be:

```<code><?php
$String = 'pdftk.exe > "c:\temp\temp.txt"';
exec($String); //removed quotes
?>
</code>```

And for the second line, what if you try this?

```<code><?php
exec('pdftk.exe > "c:\temp\temp.txt\"', $outputAndErrors, $returnValue);
var_dump($outputAndErrors);
?>
</code>```

Or if you remove your first ">"?

```<code><?php
exec('pdftk.exe "c:\temp\temp.txt\" 2>&1', $outputAndErrors, $returnValue);
var_dump($outputAndErrors);
?>
</code>```

These are some tests that may help you, thought.

Title: PDFtk command not running from exec

Body:
I've moved my code form one WAMP computer to another and the code that runs pdftk stopped working. I've compared the permissions on pdftk.exe and they are the same on both machines. When I run the same command from a command prompt, it works. I add exec("whoami") to the script and the user is the same on both computers. When I run something like exec('dir 2>&1', $out) it executes so I know exec is working form within php.

I've created a trivial php file to test and it doesn't work.

<?php
$String = 'pdftk.exe > "c:\temp\temp.txt"';
exec("$String");
exec("pdftk.exe > \"c:\temp\temp.txt\"");
?>

Both exec command result in a 0 byte file being created.

if I run

pdftk.exe > "c:\temp\temp.txt"

from a command line it puts the output of pdftk.exe into the temp.txt file as expected.

This seems like is must be some kind of permissions issue, but permissions on the executable seem to be the same. Losing my mind on this.

Body:
In my opinion, first line should be:

<?php
$String = 'pdftk.exe > "c:\temp\temp.txt"';
exec($String); //removed quotes
?>

And for the second line, what if you try this?

<?php
exec('pdftk.exe > "c:\temp\temp.txt\"', $outputAndErrors, $returnValue);
var_dump($outputAndErrors);
?>

Or if you remove your first ">"?

<?php
exec('pdftk.exe "c:\temp\temp.txt\" 2>&1', $outputAndErrors, $returnValue);
var_dump($outputAndErrors);
?>

These are some tests that may help you, thought.


问:
Who knows how to connect the "Ulkit 3" (https://getuikit.com/) to "Vue.js 2
Who knows how to connect the "Ulkit 3" (https://getuikit.com/) to "Vue.js 2". I can't find some guides in the internet for this theme. I need exactly UIkit 3 version. I don't need the VUIKIT because it based on UIkit 2, not in UIkit 3. Thanks in advance.</p>

答:
In case the original asker is still looking, VUIKIT has a branch implementing UIKit 3:

https://github.com/vuikit/vuikit/tree/next

It is actively developed (as of 14/11/2017) and nearly feature complete.


问:
How can I get enum possible values in a MySQL database?
I want to populate my dropdowns with enum possible values from a DB automatically. Is this possible in MySQL?</p>

答:
To fetch the list of possible values has been well documented, but expanding on another answer that returned the values in parenthesis, I wanted to strip them out leaving me with a comma separated list that would then allow me to use an explode type function whenever I needed to get an array.

```<code>SELECT
    SUBSTRING(COLUMN_TYPE, 6, LENGTH(COLUMN_TYPE) - 6) AS val
FROM
    information_schema.COLUMNS
WHERE
    TABLE_NAME = 'articles'
AND
    COLUMN_NAME = 'status'
</code>```

The SUBSTRING now starts at the 6th character and uses a length which is 6 characters shorter than the total, removing the trailing parenthesis.

Body:
To fetch the list of possible values has been well documented, but expanding on another answer that returned the values in parenthesis, I wanted to strip them out leaving me with a comma separated list that would then allow me to use an explode type function whenever I needed to get an array.

SELECT
    SUBSTRING(COLUMN_TYPE, 6, LENGTH(COLUMN_TYPE) - 6) AS val
FROM
    information_schema.COLUMNS
WHERE
    TABLE_NAME = 'articles'
AND
    COLUMN_NAME = 'status'

The SUBSTRING now starts at the 6th character and uses a length which is 6 characters shorter than the total, removing the trailing parenthesis.


问:
WPF Window assigning event handlers
I was trying to assign event handlers for WPF window (window B) just like it was assigned in window A, but IDE says Cannot access non-static event PreviewKeyDown in static context. Perhaps anyone knows the reason why it's like that. I don't see any differences between two windows.

Window A:

```<code><Window x:Class="WindowA"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Title="PreviewDetailWindow"
    Height="512.929"
    Width="809.152"
    MinWidth="240"
    Name="FormWindow"
    WindowStartupLocation="CenterScreen"
    Background="Gray"
    UseLayoutRounding="True"
    SnapsToDevicePixels="True">
</code>```

Window B:

```<code><Window x:Class="WindowB"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:BasketMap"
    mc:Ignorable="d"
    Title="PlayerWindow"
    Height="300"
    Width="300"
    Background="Gray">
</code>```

Notice that using this.PreviewKeyDown works well on both, but I'm just curious about why former way doesn't work well on two windows.

答:
WindowB does not have a name assigned to it:</p>

```<code><Window x:Class="WindowB" ... x:Name="PlayerWindow" ...>
</code>```

Title: WPF Window assigning event handlers

Body:
I was trying to assign event handlers for WPF window (window B) just like it was assigned in window A, but IDE says Cannot access non-static event PreviewKeyDown in static context. Perhaps anyone knows the reason why it's like that. I don't see any differences between two windows.

Window A:

<Window x:Class="WindowA"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Title="PreviewDetailWindow"
    Height="512.929"
    Width="809.152"
    MinWidth="240"
    Name="FormWindow"
    WindowStartupLocation="CenterScreen"
    Background="Gray"
    UseLayoutRounding="True"
    SnapsToDevicePixels="True">

Window B:

<Window x:Class="WindowB"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:BasketMap"
    mc:Ignorable="d"
    Title="PlayerWindow"
    Height="300"
    Width="300"
    Background="Gray">

Notice that using this.PreviewKeyDown works well on both, but I'm just curious about why former way doesn't work well on two windows.

Body:
WindowB does not have a name assigned to it:

<Window x:Class="WindowB" ... x:Name="PlayerWindow" ...>


问:
node Object.assign(obj1,obj2,obj3) returning the json properties of obj3
I have some encapsulated mongoose queries to a mongodb.

```<code>collection1.findOne({ parm: value}, function(err, item){
    var a = item.a;
    var b = item.b;
    collection2.findOne({parm1: a}, function(err, item2){
        collection3.findOne({parm2: b}, function(err, item3){
            var records = Object.assign(item, item2, item3);
        });
    });
});
</code>```

If I print item, item2 and item3 before the assign all objects print different as well as some equal properties. When I print records after the var records line it only shows up item3 json properties.

Per the documentation it should

copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Which is not happening. Am I doing something wrong or is this the expected behavior?

I require async library. Is it possible that imports might be altering the behavior of object.assign?

答:
When I print records after the var records line it only shows up item3
  json properties.

As per spec

iii) if desc is not undefined and desc.[[Enumerable]] is true, then

a) Let propValue be Get(from, nextKey).

b) ReturnIfAbrupt(propValue).

c) Let status be Set(to, nextKey, propValue, true). //observe this line

d) ReturnIfAbrupt(status).

So, this is an expected behavior since assign works by

Assigning values from left source onwards to right.

And doesn't check if a property has already been set.

Demo

var a = {a:1, b:2};
var b = {b:3, c:4};
var c = Object.assign( {}, a,b );
console.log(c); ```

Observe that the output overrides b property

{   "a": 1,   "b": 3,   "c": 4 }

Body:
I have some encapsulated mongoose queries to a mongodb.

collection1.findOne({ parm: value}, function(err, item){
    var a = item.a;
    var b = item.b;
    collection2.findOne({parm1: a}, function(err, item2){
        collection3.findOne({parm2: b}, function(err, item3){
            var records = Object.assign(item, item2, item3);
        });
    });
});

If I print item, item2 and item3 before the assign all objects print different as well as some equal properties. When I print records after the var records line it only shows up item3 json properties.

Per the documentation it should

copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Which is not happening. Am I doing something wrong or is this the expected behavior?

I require async library. Is it possible that imports might be altering the behavior of object.assign?

Body:
When I print records after the var records line it only shows up item3
  json properties.

As per spec

iii) if desc is not undefined and desc.[[Enumerable]] is true, then

a) Let propValue be Get(from, nextKey).

b) ReturnIfAbrupt(propValue).

c) Let status be Set(to, nextKey, propValue, true). //observe this line

d) ReturnIfAbrupt(status).

So, this is an expected behavior since assign works by

Assigning values from left source onwards to right.

And doesn't check if a property has already been set.

Demo

var a = {a:1, b:2};
var b = {b:3, c:4};
var c = Object.assign( {}, a,b );
console.log(c);

Observe that the output overrides b property

{   "a": 1,   "b": 3,   "c": 4 }


问:
Excel Browsing a folder and Automating Data Entry into a default template
I been reading up codes available on the net from various sources and have debug with self-taught programming to make it work but I'm having difficulty proceeding on.

As you can see, it comes from a source. Browsing a folder & reading the files works fine with the code, I need to copy values from this folder & paste it into the default template as assigned in the code & save the file with with a default format and alongside values from a cell(O1) & (O11) assign in the code.

As you can see, is not saved as xlsx and neither is it saving with the values from cell specified.

Next, automating data entry to assigned field. Only first 3 files are able to copy exactly what I want. The rest inputs wrong data, as shown in the image below. Additionally, I also need to copy values from cell N15:O83 read from files in  folder, into template Column AA & AB starting from row 6 respectively.

Thanks in advance for any assistance provided.

Sample Source File

Correct Automation

Wrong Automation

Macro Code

```<code>Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and             perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim InstID As String
Dim InstDate As Date
Dim InstBR As String

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

With FldrPicker
  .Title = "Select A Target Folder"
  .AllowMultiSelect = False
    If .Show <> -1 Then GoTo NextCode
    myPath = .SelectedItems(1) & "\"
End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

    'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

  'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
  Do While myFile <> ""
'Set variable equal to opened workbook
  Set wb = Workbooks.Open(Filename:=myPath & myFile)

'Ensure Workbook has opened before moving on to next line of code
  DoEvents

'Input Code Here

  InstID = Range("O1")
  InstDate = Range("O11")
  InstBR = "Base Reading"

  wb.Worksheets(1).Range("B15:E83").Copy
  Workbooks.Add template:="C:\Users\PC1\Desktop\Daily data file\Inc\TestTemplate.xlsx"
  Sheets(ActiveSheet.Index + 1).Activate
  If Err.Number <> 0 Then Sheets(1).Activate
  Range("M6").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

    Range("E6:F76") = InstID
    Range("K6:K76") = InstDate
    Range("J6") = InstBR

ChDir ("C:\Users\PC\Desktop\Daily data file\Inc\INC22001 - Copy\Test Save") ' Directory you need to save the file as xlsm
Filename = ("Test_Data_ ") & Range("O1").Value & ";" &     Range("O11").Value
ActiveWorkbook.SaveAs Filename:=Filename, FileFormat:=xlOpenXMLWorkbook

'Save and Close Workbook
  wb.Close SaveChanges:=True

'Ensure Workbook has closed before moving on to next line of code
  DoEvents

'Get next file name
  myFile = Dir
  Loop

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True

End Sub
</code>```

答:
As per the previous answer, you will need to give your file an extension. But also, you are referencing your Ranges O1 and O11 softly (meaning your not specifying a sheet). If these values need to come from the file you are opening, I would reference them explicitly with wb.Worksheets(1).Range("O1").Value. By the looks of it, you are inadvertently getting these values from the target sheet (see cell O11 in screenshot 2 and your fourth file down in screenshot 1).

I would also be very cautious about putting a raw date in a filename. You would be better with a datestamp: Filename = "Test_Data_ " & InstID & ";" & Format(InstDate,"YYYYMMDD") & ".xlsx"

Body:
I been reading up codes available on the net from various sources and have debug with self-taught programming to make it work but I'm having difficulty proceeding on.

As you can see, it comes from a source. Browsing a folder & reading the files works fine with the code, I need to copy values from this folder & paste it into the default template as assigned in the code & save the file with with a default format and alongside values from a cell(O1) & (O11) assign in the code.

As you can see, is not saved as xlsx and neither is it saving with the values from cell specified.

Next, automating data entry to assigned field. Only first 3 files are able to copy exactly what I want. The rest inputs wrong data, as shown in the image below. Additionally, I also need to copy values from cell N15:O83 read from files in  folder, into template Column AA & AB starting from row 6 respectively.

Thanks in advance for any assistance provided.

Sample Source File

Correct Automation

Wrong Automation

Macro Code

Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and             perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim InstID As String
Dim InstDate As Date
Dim InstBR As String

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

With FldrPicker
  .Title = "Select A Target Folder"
  .AllowMultiSelect = False
    If .Show <> -1 Then GoTo NextCode
    myPath = .SelectedItems(1) & "\"
End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

    'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

  'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
  Do While myFile <> ""
'Set variable equal to opened workbook
  Set wb = Workbooks.Open(Filename:=myPath & myFile)

'Ensure Workbook has opened before moving on to next line of code
  DoEvents

'Input Code Here

  InstID = Range("O1")
  InstDate = Range("O11")
  InstBR = "Base Reading"

  wb.Worksheets(1).Range("B15:E83").Copy
  Workbooks.Add template:="C:\Users\PC1\Desktop\Daily data file\Inc\TestTemplate.xlsx"
  Sheets(ActiveSheet.Index + 1).Activate
  If Err.Number <> 0 Then Sheets(1).Activate
  Range("M6").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

    Range("E6:F76") = InstID
    Range("K6:K76") = InstDate
    Range("J6") = InstBR

ChDir ("C:\Users\PC\Desktop\Daily data file\Inc\INC22001 - Copy\Test Save") ' Directory you need to save the file as xlsm
Filename = ("Test_Data_ ") & Range("O1").Value & ";" &     Range("O11").Value
ActiveWorkbook.SaveAs Filename:=Filename, FileFormat:=xlOpenXMLWorkbook

'Save and Close Workbook
  wb.Close SaveChanges:=True

'Ensure Workbook has closed before moving on to next line of code
  DoEvents

'Get next file name
  myFile = Dir
  Loop

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True

End Sub


问:
Different app versions on iOS and Android - React Native (CRNA) with Expo
Is it possible to have two different app versions (one for iOS and one for Android) within the same codebase in a React Native (CRNA) app using Expo?

There is obviously only 1 app.json as follows:

```<code>{
  "expo": {
    "name": "MyApp",
    "icon": "./assets/images/appstore-icon.png",
    "description": "This is a sample",
    "slug": "test",
    "privacy": "unlisted",
    "sdkVersion": "19.0.0",
    "version": "1.0.10",
    ......... etc
  }
}
</code>```

Is there a way to add platform-specific versioning?

答:
sdkVersion is SDK version of Expo not your apps. version is your app version, use whatever versioning scheme that you like

If you want to versioning separately for Android/iOS app set right inside app.json like:

```<code>{
   "expo": {
    "name": "Your App Name",
    "icon": "./path/to/your/app-icon.png",
    "slug": "your-app-slug",
    "version": "1.2.0",
    "sdkVersion": "21.0.0",
    "ios": {
      "bundleIdentifier": "com.yourcompany.yourappname",
      "buildNumber": "3.2.1"
    },
    "android": {
      "package": "com.yourcompany.yourappname",
      "versionCode": "1.2.3"
    }
  }
}
</code>```

To keep track of versioning, you can update the binary’s versionCode and buildNumber. It is a good idea to glance through the app.json documentation to get an idea of all the properties you can change, e.g. the icons, deep linking url scheme, handset/tablet support, and a lot more.

See: https://docs.expo.io/versions/latest/guides/building-standalone-apps.html#7-update-your-app

Body:
Is it possible to have two different app versions (one for iOS and one for Android) within the same codebase in a React Native (CRNA) app using Expo?

There is obviously only 1 app.json as follows:

{
  "expo": {
    "name": "MyApp",
    "icon": "./assets/images/appstore-icon.png",
    "description": "This is a sample",
    "slug": "test",
    "privacy": "unlisted",
    "sdkVersion": "19.0.0",
    "version": "1.0.10",
    ......... etc
  }
}

Is there a way to add platform-specific versioning?

Body:
sdkVersion is SDK version of Expo not your apps. version is your app version, use whatever versioning scheme that you like

If you want to versioning separately for Android/iOS app set right inside app.json like:

{
   "expo": {
    "name": "Your App Name",
    "icon": "./path/to/your/app-icon.png",
    "slug": "your-app-slug",
    "version": "1.2.0",
    "sdkVersion": "21.0.0",
    "ios": {
      "bundleIdentifier": "com.yourcompany.yourappname",
      "buildNumber": "3.2.1"
    },
    "android": {
      "package": "com.yourcompany.yourappname",
      "versionCode": "1.2.3"
    }
  }
}

To keep track of versioning, you can update the binary’s versionCode and buildNumber. It is a good idea to glance through the app.json documentation to get an idea of all the properties you can change, e.g. the icons, deep linking url scheme, handset/tablet support, and a lot more.

See: https://docs.expo.io/versions/latest/guides/building-standalone-apps.html#7-update-your-app


问:
C# MVC save View as png
i have problem with png HTML renderer,
i am trying to send png of View to email, but on email i get 0B .png
PS: Ticket.pdf is ok</p>

```<code> using (MemoryStream ms = new MemoryStream())
        {

            var pdf = PdfGenerator.GeneratePdf(RenderRazorViewToString("TicketTemplateBig", model), PdfSharp.PageSize.A4);
            pdf.Save(ms, false);

            /////////////////
            //Bitmap bitmap = new Bitmap(Convert.ToInt32(1024), Convert.ToInt32(1024), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            using (MemoryStream ms2 = new MemoryStream())
            {
                //Image image = TheArtOfDev.HtmlRenderer.WinForms.HtmlRender.RenderToImage(RenderRazorViewToString("TicketTemplateBig", model));

                Bitmap bitmap = (Bitmap)Image.FromFile(@"C:\logo.png");
                bitmap.Save(ms2, ImageFormat.Png);

                /////////////////
                await ms.FlushAsync();
                await ms2.FlushAsync();
                mm.Attachments.Add(new Attachment(ms, string.Format("Ticket.pdf"), "application/pdf"));
                streams.Add(ms);
                mm.Attachments.Add(new Attachment(ms2, string.Format("logo.png"), "application/png"));
                streams.Add(ms2);
                await client.SendMailAsync(mm);
            }
        }
</code>```

答:
You are trying to send the mail before having effectively written to ms2.

you need to do flush the ms2 stream buffer before adding it to mm . (as you did for ms, that's why the pdf part was handled correctly)

(Also, minor typo :  "application/png" instead of "application/Png", probably not an issue)

Title: C# MVC save View as png

Body:
i have problem with png HTML renderer,
i am trying to send png of View to email, but on email i get 0B .png
PS: Ticket.pdf is ok

 using (MemoryStream ms = new MemoryStream())
        {

            var pdf = PdfGenerator.GeneratePdf(RenderRazorViewToString("TicketTemplateBig", model), PdfSharp.PageSize.A4);
            pdf.Save(ms, false);

            /////////////////
            //Bitmap bitmap = new Bitmap(Convert.ToInt32(1024), Convert.ToInt32(1024), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            using (MemoryStream ms2 = new MemoryStream())
            {
                //Image image = TheArtOfDev.HtmlRenderer.WinForms.HtmlRender.RenderToImage(RenderRazorViewToString("TicketTemplateBig", model));

                Bitmap bitmap = (Bitmap)Image.FromFile(@"C:\logo.png");
                bitmap.Save(ms2, ImageFormat.Png);

                /////////////////
                await ms.FlushAsync();
                await ms2.FlushAsync();
                mm.Attachments.Add(new Attachment(ms, string.Format("Ticket.pdf"), "application/pdf"));
                streams.Add(ms);
                mm.Attachments.Add(new Attachment(ms2, string.Format("logo.png"), "application/png"));
                streams.Add(ms2);
                await client.SendMailAsync(mm);
            }
        }