问:
json files downloaded by aws s3 sync / aws s3 cp are incomplete
I downloaded .json file from amazon s3, but its content is just a value of the first key/value pair.

original json file is like this:

```<code>{
    "_1": [
        {
            "Name": "name",
            "Type": "type"
        }
    ]
}
</code>```

but downloaded json file is not even json file, it only has list inside.

```<code>[
  {
    "Name": "name",
    "Type": "type"
  }
]
</code>```

I tried aws s3 sync / aws s3 copy / aws s3api get-object and all of its result is same.

I only want to download original file from the s3 bucket.

is there any solution?

Updates

I just copied the original content on the s3 select from preview and saved it as a file.

I found out its md5 checksum and file size is totally different with the object overview.

It seems the original file on the s3 bucket is corrupted, but I'm not sure how its preview is still same as the original content.

答:
I found out aws s3api select-object-content can give me same result as the S3 select from preview but without indents.

For indents, I decided to reindent after I receive the uncorrupted results.

I used below command to retrieve my json files.

```<code>aws s3api select-object-content \
  --bucket $BUCKET \
  --key $KEY --expression "select * from s3object" \
  --expression-type 'SQL' \
  --input-serialization '{"JSON": {"Type": "LINES"}, "CompressionType": "NONE"}' \
  --output-serialization '{"JSON": {}}' \
  /dev/stdout | python -mjson.tool > $KEY
</code>```

Body:
I downloaded .json file from amazon s3, but its content is just a value of the first key/value pair.

original json file is like this:

{
    "_1": [
        {
            "Name": "name",
            "Type": "type"
        }
    ]
}

but downloaded json file is not even json file, it only has list inside.

[
  {
    "Name": "name",
    "Type": "type"
  }
]

I tried aws s3 sync / aws s3 copy / aws s3api get-object and all of its result is same.

I only want to download original file from the s3 bucket.

is there any solution?

Updates

I just copied the original content on the s3 select from preview and saved it as a file.

I found out its md5 checksum and file size is totally different with the object overview.

It seems the original file on the s3 bucket is corrupted, but I'm not sure how its preview is still same as the original content.

Body:
I found out aws s3api select-object-content can give me same result as the S3 select from preview but without indents.

For indents, I decided to reindent after I receive the uncorrupted results.

I used below command to retrieve my json files.

aws s3api select-object-content \
  --bucket $BUCKET \
  --key $KEY --expression "select * from s3object" \
  --expression-type 'SQL' \
  --input-serialization '{"JSON": {"Type": "LINES"}, "CompressionType": "NONE"}' \
  --output-serialization '{"JSON": {}}' \
  /dev/stdout | python -mjson.tool > $KEY


来源: stackexchange

问:
What does & after a return type mean in C++ OOP
so I have a method of a class given below that multiplies two complex numbers using operator overloading :

Complex operator*(Complex &c2) {
    Complex temp;

    temp.realPart = realPart * c2.realPart - (imaginaryPart * c2.imaginaryPart);
    temp.imaginaryPart = (realPart * c2.imaginaryPart) + (imaginaryPart * c2.realPart);

    return temp;
}
```

<p>This seems to work fine. However, my program does not run when I change the member function header to:</p>

<pre class="lang-cpp prettyprint-override"><code>Complex& operator * (Complex &c2) {  // Adding & after the class name.
</code>```

The program does not crash but it can't compute the answer/ ends after the cursor on the program blinks for a while. What does & after the class name mean? And I have seen it being used when returning a this pointer.

答:
What does & after a return type mean in C++

It means the same thing as & after any type. It means that the type is a reference. So, if it is after a return type, then it means that the function returns a reference.

Your function returns an automatic variable. Returning a reference to an automatic variable is useless, because the automatic object is destroyed upon returning, so the reference becomes invalid immediately.

If you attempt to access the non-existing object through the returned invalid reference, then the behaviour of the program will be undefined.

ContentLicense: CC BY-SA 4.0

Body:
so I have a method of a class given below that multiplies two complex numbers using operator overloading :

Complex operator*(Complex &c2) {
    Complex temp;

    temp.realPart = realPart * c2.realPart - (imaginaryPart * c2.imaginaryPart);
    temp.imaginaryPart = (realPart * c2.imaginaryPart) + (imaginaryPart * c2.realPart);

    return temp;
}

This seems to work fine. However, my program does not run when I change the member function header to:

Complex& operator * (Complex &c2) {  // Adding & after the class name.

The program does not crash but it can't compute the answer/ ends after the cursor on the program blinks for a while. What does & after the class name mean? And I have seen it being used when returning a this pointer.


问:
Visual Studio 2008 Test Sets
Is it possible to group tests together so I can run a subset of all tests available?</p>

答:
IN VS 2008 pro and Team lets you create a Test list where you can specify what tests to run.

you can also arrange your tests using Namespaces to specify groups of tests and then run the tests in that specified context.

OwnerDisplayName: blu

ContentLicense: CC BY-SA 2.5

Title: Visual Studio 2008 Test Sets

OwnerDisplayName: Bob The Janitor


问:
Configuring .ASP pages in IIS 7.5 in Windows server 2003
I am trying to add a virtual directory in IIS 7.5 version of Windows server 2003. But i could not browse my default.asp page. How can i troubleshoot this issue ?</p>

答: I believe you installed IIS Express7.5... correct? If that is the case, take a look at failed request trace log files located in "%userprofile%\My Documents\IISExpress\TraceLogFiles\" and also see if there are any interesting events in event viewer.</p>

ContentLicense: CC BY-SA 3.0


问:
How to implement Redis streams with C# Rx
Because I could not find any implementation where we don't use a loop to get the stream content I start to implement one but I'm facing several problems that may some of you can point me to the right place.

The implementation uses a combination of Pub/Sub and the stream:
* log -> stream channel
* log:notification -> pub/sub
* log:lastReadMessage -> contains the last read key from the stream

Publisher

```<code>        static async Task Main(string[] args)
        {
            var connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync("localhost");
            var redisDb =  connectionMultiplexer.GetDatabase(1);

            while(true)
            {
                var value =  new NameValueEntry[]
                {
                    new NameValueEntry("id", Guid.NewGuid().ToString()),
                    new NameValueEntry("timestamp", DateTime.UtcNow.ToString())
                };

                redisDb.StreamAdd("log", value);
                var publisher = connectionMultiplexer.GetSubscriber();
                publisher.Publish("log:notify", string.Empty, CommandFlags.None);
                await Task.Delay(TimeSpan.FromSeconds(1));
            }
        }
</code>```

Subscriber

```<code>        static async Task Main(string[] args)
        {
            var connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync("localhost");
            var redisDb =  connectionMultiplexer.GetDatabase(1);

            var observableStream =  CreateTaskFromStream(connectionMultiplexer, redisDb, "log")
                .Subscribe(x => {
                  Console.WriteLine(x);
                });

            Console.ReadLine();
        }
</code>```

```<code>        private static SemaphoreSlim taskFromStreamBlocker = new SemaphoreSlim(1);

        private static IObservable<string> CreateTaskFromStream(ConnectionMultiplexer connection, IDatabase redisDb, string channel)
        {
            var lastReadMessage = "0-0";

            var lastReadMessageData = redisDb.StringGet($"{channel}:lastReadMessage", CommandFlags.None);
            if (string.IsNullOrEmpty(lastReadMessageData))
            {
                redisDb.StringGetSet($"{channel}:lastReadMessage", lastReadMessage);
            }
            else
            {
                lastReadMessage = lastReadMessageData;
            }

            return Observable.Create<string>(obs =>
            {
                var subscriber = connection.GetSubscriber();
                subscriber.Subscribe($"{channel}:notify", async (ch, msg) =>
                {
                    var locker = await taskFromStreamBlocker
                        .WaitAsync(0)
                        .ConfigureAwait(false);

                    if (!locker)
                    {
                        return;
                    }

                    var messages = await redisDb.StreamReadAsync(channel, lastReadMessage);

                    foreach(var message in messages)
                    {
                        obs.OnNext($"{message.Id} -> {message.Values[0].Name}: {message.Values[0].Value} / {message.Values[1].Name}: {message.Values[1].Value}");
                        lastReadMessage = message.Id;
                    }

                    redisDb.KeyDelete($"{channel}:lastReadMessage");
                    redisDb.StringGetSet($"{channel}:lastReadMessage", lastReadMessage);

                    taskFromStreamBlocker.Release();
                });

                return Disposable.Create(() => subscriber.Unsubscribe(channel));
            });
        }
</code>```

Why the semaphore?

Because I could have lots of messages add to the stream and I don't want o to have the same message processed twice.

THE PROBLEMS

If we have unprocessed messages in the stream, how can we process without having an event from the Pub/Sub
When we start we can verify if it is unprocessed messages and processes it. If during this time a new message is added to the stream, and we aren't subscribing yet the Pub/sub, the subscriber will not process the message until we receive a notification through the Pub/Sub.

The semaphore is important to not process the same message twice but at the same time it's a curse. During the process of a message, another can be added to the stream. When that happens the subscriber will not process right away but only the next time it's notified (at this point will process two messages).

How you would implement this?
Is there an implementation of the Redis streams using Rx only?
The solution should not use some kind of loop and be memory efficient. Is this possible?

Best wishes

Paulo Aboim Pinto

答:
I use a tight loop just do an XRange and save a position - KISS.. but if there is no work it backs off so its pretty fast when there is a lot going on its a tight loop.

If you need higher performance eg reading while processing however i would caution against this for most cases.

It creates a lot of complexity and this needs to be rock solid.

Redis is normally fast enough

" I don't want o to have the same message processed twice."  almost every system has at least once delivery eliminating this around crashes is mind mindbogglingly difficult / slow.  You can remove it partially by using a hashset of ids but its pretty trivial for consumers to deal with it and messages designed to be idempotent. This is probably the root cause message design issues.  If you partition each reader ( separate stream and 1 worker per stream) you can keep the hashset in memory avoiding scaling / distributed issues. Note a Redis stream can preserve order use this to make simpler idempotent messages.

Exceptions, you don't want to stop processing a stream because a consumer has a logic exception on 1 message eg get a call at night the whole system has stopped, locks make this worse.   Event data cant be changed its happened so its  best effort. However infra / redis exceptions do need to throw and be retried. Managing this outside a loop is very painful.

Simple back pressure. If you cant process the work fast enough the loop slows down instead of creating a lot of tasks and blowing up all your memory.

I dont use distributed locks / semaphores anymore.

If your dealing with Commands eg dosomething instead of xyz has happened these can fail. Again the consumer should deal with the case it has already happened not the redis / stream reading part.

Some libs with magic call backs dont solve these issues the call backs will have retry when time out run on any node etc. The complexity / issues are still there they just move somewhere else.

You may have an observable on top for consumers but this is basically cosmetic it does not solve the problem and if you look under many implementations somewhere you will see the same loop.  I would not use this instead get the consumer to register an action.

eg

```<code>    public interface IStreamSubscriber
    {
        void RegisterEventCallBack(Func<object, IReadOnlyDictionary<string, string>, Task> callback);
        void RegisterBatchEventCallBack(Func<IEnumerable<(object msg, IReadOnlyDictionary<string, string> metaData)>, Task> batchCallback);
        void Start();
    }
</code>```

In your case the call back could have the observable and not use the loop but there is a low level loop underneath which can also do message to object conversion for the consumer.

Body:
Because I could not find any implementation where we don't use a loop to get the stream content I start to implement one but I'm facing several problems that may some of you can point me to the right place.

The implementation uses a combination of Pub/Sub and the stream:
* log -> stream channel
* log:notification -> pub/sub
* log:lastReadMessage -> contains the last read key from the stream

Publisher

        static async Task Main(string[] args)
        {
            var connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync("localhost");
            var redisDb =  connectionMultiplexer.GetDatabase(1);

            while(true)
            {
                var value =  new NameValueEntry[]
                {
                    new NameValueEntry("id", Guid.NewGuid().ToString()),
                    new NameValueEntry("timestamp", DateTime.UtcNow.ToString())
                };

                redisDb.StreamAdd("log", value);
                var publisher = connectionMultiplexer.GetSubscriber();
                publisher.Publish("log:notify", string.Empty, CommandFlags.None);
                await Task.Delay(TimeSpan.FromSeconds(1));
            }
        }

Subscriber

        static async Task Main(string[] args)
        {
            var connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync("localhost");
            var redisDb =  connectionMultiplexer.GetDatabase(1);

            var observableStream =  CreateTaskFromStream(connectionMultiplexer, redisDb, "log")
                .Subscribe(x => {
                  Console.WriteLine(x);
                });

            Console.ReadLine();
        }

        private static SemaphoreSlim taskFromStreamBlocker = new SemaphoreSlim(1);

        private static IObservable<string> CreateTaskFromStream(ConnectionMultiplexer connection, IDatabase redisDb, string channel)
        {
            var lastReadMessage = "0-0";

            var lastReadMessageData = redisDb.StringGet($"{channel}:lastReadMessage", CommandFlags.None);
            if (string.IsNullOrEmpty(lastReadMessageData))
            {
                redisDb.StringGetSet($"{channel}:lastReadMessage", lastReadMessage);
            }
            else
            {
                lastReadMessage = lastReadMessageData;
            }

            return Observable.Create<string>(obs =>
            {
                var subscriber = connection.GetSubscriber();
                subscriber.Subscribe($"{channel}:notify", async (ch, msg) =>
                {
                    var locker = await taskFromStreamBlocker
                        .WaitAsync(0)
                        .ConfigureAwait(false);

                    if (!locker)
                    {
                        return;
                    }

                    var messages = await redisDb.StreamReadAsync(channel, lastReadMessage);

                    foreach(var message in messages)
                    {
                        obs.OnNext($"{message.Id} -> {message.Values[0].Name}: {message.Values[0].Value} / {message.Values[1].Name}: {message.Values[1].Value}");
                        lastReadMessage = message.Id;
                    }

                    redisDb.KeyDelete($"{channel}:lastReadMessage");
                    redisDb.StringGetSet($"{channel}:lastReadMessage", lastReadMessage);

                    taskFromStreamBlocker.Release();
                });

                return Disposable.Create(() => subscriber.Unsubscribe(channel));
            });
        }

Why the semaphore?

Because I could have lots of messages add to the stream and I don't want o to have the same message processed twice.

THE PROBLEMS

If we have unprocessed messages in the stream, how can we process without having an event from the Pub/Sub
When we start we can verify if it is unprocessed messages and processes it. If during this time a new message is added to the stream, and we aren't subscribing yet the Pub/sub, the subscriber will not process the message until we receive a notification through the Pub/Sub.

The semaphore is important to not process the same message twice but at the same time it's a curse. During the process of a message, another can be added to the stream. When that happens the subscriber will not process right away but only the next time it's notified (at this point will process two messages).

How you would implement this?
Is there an implementation of the Redis streams using Rx only?
The solution should not use some kind of loop and be memory efficient. Is this possible?

Best wishes

Paulo Aboim Pinto

Body:
I use a tight loop just do an XRange and save a position - KISS.. but if there is no work it backs off so its pretty fast when there is a lot going on its a tight loop.

If you need higher performance eg reading while processing however i would caution against this for most cases.

It creates a lot of complexity and this needs to be rock solid.

Redis is normally fast enough

" I don't want o to have the same message processed twice."  almost every system has at least once delivery eliminating this around crashes is mind mindbogglingly difficult / slow.  You can remove it partially by using a hashset of ids but its pretty trivial for consumers to deal with it and messages designed to be idempotent. This is probably the root cause message design issues.  If you partition each reader ( separate stream and 1 worker per stream) you can keep the hashset in memory avoiding scaling / distributed issues. Note a Redis stream can preserve order use this to make simpler idempotent messages.

Exceptions, you don't want to stop processing a stream because a consumer has a logic exception on 1 message eg get a call at night the whole system has stopped, locks make this worse.   Event data cant be changed its happened so its  best effort. However infra / redis exceptions do need to throw and be retried. Managing this outside a loop is very painful.

Simple back pressure. If you cant process the work fast enough the loop slows down instead of creating a lot of tasks and blowing up all your memory.

I dont use distributed locks / semaphores anymore.

If your dealing with Commands eg dosomething instead of xyz has happened these can fail. Again the consumer should deal with the case it has already happened not the redis / stream reading part.

Some libs with magic call backs dont solve these issues the call backs will have retry when time out run on any node etc. The complexity / issues are still there they just move somewhere else.

You may have an observable on top for consumers but this is basically cosmetic it does not solve the problem and if you look under many implementations somewhere you will see the same loop.  I would not use this instead get the consumer to register an action.

eg

    public interface IStreamSubscriber
    {
        void RegisterEventCallBack(Func<object, IReadOnlyDictionary<string, string>, Task> callback);
        void RegisterBatchEventCallBack(Func<IEnumerable<(object msg, IReadOnlyDictionary<string, string> metaData)>, Task> batchCallback);
        void Start();
    }

In your case the call back could have the observable and not use the loop but there is a low level loop underneath which can also do message to object conversion for the consumer.


问:
Node js , replacing occurrences in a nested data structure
Basically I want to replace # occurrences in a string from an object. As you can see it replace occurences in templateName , description , comments and Name but I can't replace sections header and sections questions , how will I improve my loop to apply replaceOccurrences in sections.header and sections questions array of objects? . sections headers are array of objects I also want to include that. Any idea? thank you.

Code

```<code>const replaceOccurrences = (originalString) => (typeof originalString === 'string' ? originalString.replace(/#/g, '#') : originalString);

const generateTemplate = async (data) => {

  for (const [k, v] of Object.entries(data)) { data[k] = replaceOccurrences(v); }

  return template(data);
};
</code>```

Data

```<code>data :  {
  Name: 'Rajesh',
  sections: [
    {
      questions: [Array]
    }
  ],
  templateName: 'TEMPLAT#E',
  description: 'Tes#t',
  comments: "adasdada'dfgdfgdfg 'gfddf#gdfgdf #num;## ##fsdfds gdfgdfgfd##"
}
</code>```

答:
You can stringify the object, make your replacements, then return it to object form:

let a = JSON.stringify(data).replace(/#/g, '#');
let b = JSON.parse(a);

Name: "Rajesh"
comments: "adasdada'dfgdfgdfg 'gfddf#gdfgdf #num;## ##fsdfds gdfgdfgfd##"
description: "Tes#t"
sections: Array(1)
0: {header: "Testing sec#tion", questions: Array(1)}
length: 1
__proto__: Array(0)
templateName: "TECHNICAL TEMPLAT#E"
```

Body:
Basically I want to replace # occurrences in a string from an object. As you can see it replace occurences in templateName , description , comments and Name but I can't replace sections header and sections questions , how will I improve my loop to apply replaceOccurrences in sections.header and sections questions array of objects? . sections headers are array of objects I also want to include that. Any idea? thank you.

Code

const replaceOccurrences = (originalString) => (typeof originalString === 'string' ? originalString.replace(/#/g, '#') : originalString);

const generateTemplate = async (data) => {

  for (const [k, v] of Object.entries(data)) { data[k] = replaceOccurrences(v); }

  return template(data);
};

Data

data :  {
  Name: 'Rajesh',
  sections: [
    {
      questions: [Array]
    }
  ],
  templateName: 'TEMPLAT#E',
  description: 'Tes#t',
  comments: "adasdada'dfgdfgdfg 'gfddf#gdfgdf #num;## ##fsdfds gdfgdfgfd##"
}

Body:
You can stringify the object, make your replacements, then return it to object form:

let a = JSON.stringify(data).replace(/#/g, '&num;');
let b = JSON.parse(a);

Name: "Rajesh"
comments: "adasdada'dfgdfgdfg 'gfddf&num;gdfgdf &num;num;&num;&num; &num;&num;fsdfds gdfgdfgfd&num;&num;"
description: "Tes&num;t"
sections: Array(1)
0: {header: "Testing sec&num;tion", questions: Array(1)}
length: 1
__proto__: Array(0)
templateName: "TECHNICAL TEMPLAT&num;E"


问:
Piping output of youtube-dl to a script using ffmpeg looks ok using echo but returns an error when executing
I am trying to use youtube-dl to get the urls of some videos and then pipe the resulting urls into the input of my script. So in my terminal I do

```<code>youtube-dl --ignore-config -iga ~/Desktop/youtube/videolist.txt | myscript.sh
</code>```

In my script I define things as

```<code>command='ffmpeg'
inputArgs='-i'
outputArgs='-c:v libx264 -preset ultrafast -qp 0'
directory="${HOME}/Desktop/Videos/"
output="video${count}"
extension='mp4'
</code>```

I test it with echo to make sure everything appears in the correct order.

```<code>echo "${command}" "${inputArgs}" "${input}" "${outputArgs}" \
"${directory}""${output}${count}"."${extension}"
</code>```

And the output from that looks correct. But when I try to run the same thing without the preceding echo command, i.e.,

```<code>"${command}" "${inputArgs}" "${input}" "${outputArgs}" \
"${directory}""${output}${count}"."${extension}"
</code>```

I get an error message that says

At least one output file must be specified.

So it seems pretty obvious to me that I'm doing something wrong  when attempting to execute it.

I have tried:

quoting the entire line as a whole

quoting different sections together

using the exec command in front of everything

No matter what I do, an error occurs at some point in the process. I know it's something simple I'm doing wrong. Would someone please enlighten me as to what that might be?

I feel very strongly that the . shouldn't just be in the middle of everything like that, but I really don't know.

Again, everything looks as it should when I run echo before the string of shell parameters.

If more of the script I'm using is needed to understand what I'm talking about, that is not a problem.

答:
You tried to rely on a string to convey multiple arguments. You probably would want to use an array in all cases like this. An array is easy to use and more versatile (works with any arbitrary strings) and you don't have to walk on that many eggshells in order to avoid quirks and security holes, unlike when leaving quotes off.

```<code>command='ffmpeg'
inputArgs=(-i)
outputArgs=(-c:v libx264 -preset ultrafast -qp 0
  -metadata 'title=another * string'
  -metadata 'artist=; echo "Just a string'
  -metadata "comment=Processed by my ${command} script.")
directory="${HOME}/Desktop/Videos/"
output="video${count}"
extension='mp4'
outputArgs+=(-metadata "track=${count}")
</code>```

When expanding an array, the reference must have the {} around it. When used in the form: "${name[@]}", it behaves as if you had typed the contents on the line directly.

printf '%q\n' is a more useful way of examining a command compared to echo, as it can clearly tell you what belongs to which separate argument.
You can also expand an array into another array:

```<code>whole_thing=("${command}" "${inputArgs[@]}" "${input}"
  "${outputArgs[@]}"
  "${directory}/${output}"."${extension}")

#This will output lines you can paste
# into bash to recreate the array:
printf 'whole_thing=()\n'
printf 'whole_thing+=(%q)\n' "${whole_thing[@]}"

#This will run the command:
"${whole_thing[@]}"
</code>```

Body:
I am trying to use youtube-dl to get the urls of some videos and then pipe the resulting urls into the input of my script. So in my terminal I do

youtube-dl --ignore-config -iga ~/Desktop/youtube/videolist.txt | myscript.sh

In my script I define things as

command='ffmpeg'
inputArgs='-i'
outputArgs='-c:v libx264 -preset ultrafast -qp 0'
directory="${HOME}/Desktop/Videos/"
output="video${count}"
extension='mp4'

I test it with echo to make sure everything appears in the correct order.

echo "${command}" "${inputArgs}" "${input}" "${outputArgs}" \
"${directory}""${output}${count}"."${extension}"

And the output from that looks correct. But when I try to run the same thing without the preceding echo command, i.e.,

"${command}" "${inputArgs}" "${input}" "${outputArgs}" \
"${directory}""${output}${count}"."${extension}"

I get an error message that says

At least one output file must be specified.

So it seems pretty obvious to me that I'm doing something wrong  when attempting to execute it.

I have tried:

quoting the entire line as a whole

quoting different sections together

using the exec command in front of everything

No matter what I do, an error occurs at some point in the process. I know it's something simple I'm doing wrong. Would someone please enlighten me as to what that might be?

I feel very strongly that the . shouldn't just be in the middle of everything like that, but I really don't know.

Again, everything looks as it should when I run echo before the string of shell parameters.

If more of the script I'm using is needed to understand what I'm talking about, that is not a problem.

Body:
You tried to rely on a string to convey multiple arguments. You probably would want to use an array in all cases like this. An array is easy to use and more versatile (works with any arbitrary strings) and you don't have to walk on that many eggshells in order to avoid quirks and security holes, unlike when leaving quotes off.

command='ffmpeg'
inputArgs=(-i)
outputArgs=(-c:v libx264 -preset ultrafast -qp 0
  -metadata 'title=another * string'
  -metadata 'artist=; echo "Just a string'
  -metadata "comment=Processed by my ${command} script.")
directory="${HOME}/Desktop/Videos/"
output="video${count}"
extension='mp4'
outputArgs+=(-metadata "track=${count}")

When expanding an array, the reference must have the {} around it. When used in the form: "${name[@]}", it behaves as if you had typed the contents on the line directly.

printf '%q\n' is a more useful way of examining a command compared to echo, as it can clearly tell you what belongs to which separate argument.
You can also expand an array into another array:

whole_thing=("${command}" "${inputArgs[@]}" "${input}"
  "${outputArgs[@]}"
  "${directory}/${output}"."${extension}")

#This will output lines you can paste
# into bash to recreate the array:
printf 'whole_thing=()\n'
printf 'whole_thing+=(%q)\n' "${whole_thing[@]}"

#This will run the command:
"${whole_thing[@]}"


问:
Why does Select2 not override the normal select boxes in Electron?
Here is my code below:

<!DOCTYPE html>

 <select id="test">
  <option value="" selected=hidden>Select Product</option>
  <option></option>
 </select>

```

I have installed both jquery and select2 as node modules. Jquery seems to work just fine. Here are photos of the electron output:

Two dropdowns appear
Both can be interacted

Am I missing something simple?
Thanks in advance.

答:
You can install select2 manually insead of using NPM. This way you can use select2 offline.

Download the latest release of select2 (.zip) from: https://github.com/select2/select2/tags

Unzip the downloaded .zip and copy the necessary files from /dist.

Include these files in your .html file like:

```<code><link href="path/to/select2.min.css" rel="stylesheet" />
<script src="path/to/select2.min.js"></script>
</code>```

All done! Now select2 will work offline.

More details

Body:
Here is my code below:

<!DOCTYPE html>

 <select id="test">
  <option value="" selected=hidden>Select Product</option>
  <option></option>
 </select>

I have installed both jquery and select2 as node modules. Jquery seems to work just fine. Here are photos of the electron output:

Two dropdowns appear
Both can be interacted

Am I missing something simple?
Thanks in advance.

Body:
You can install select2 manually insead of using NPM. This way you can use select2 offline.

Download the latest release of select2 (.zip) from: https://github.com/select2/select2/tags

Unzip the downloaded .zip and copy the necessary files from /dist.

Include these files in your .html file like:

<link href="path/to/select2.min.css" rel="stylesheet" />
<script src="path/to/select2.min.js"></script>

All done! Now select2 will work offline.

More details


问:
How to add the tick labels after set the boundary?
I tried to add tick labels after using .set_boundary(), but failed.How to achieve it？

```<code>ax1.set_extent([-180, 180, -90, -60], ccrs.PlateCarree())
ax1.add_feature(cfeature.LAND)
ax1.add_feature(cfeature.OCEAN)
ax1.gridlines()

ax2.gridlines()
ax2.add_feature(cfeature.LAND)
ax2.add_feature(cfeature.OCEAN)
theta = np.linspace(0, 2*np.pi, 100)
center, radius = [0.5, 0.5], 0.5
verts = np.vstack([np.sin(theta), np.cos(theta)]).T
circle = mpath.Path(verts * radius + center)
ax2.set_boundary(circle, transform=ax2.transAxes)

ax1.gridlines(draw_labels=True)
ax2.gridlines(draw_labels=True)

</code>```

答:
There is missing code in your example so I can't be sure it will solve your problem, but Cartopy allows longitude and latitude labeling to all projections starting only with version 0.18 (whats new and PR). Before that only PlateCarree and Mercator were allowed and any other projection would fail with error:

TypeError: Cannot label gridlines on a SouthPolarStereo plot. Only PlateCarree and Mercator plots are currently supported.

With v0.18 the code (that I got from the PR linked above) makes the lonlat labels just fine:

```<code>import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature

projection = ccrs.SouthPolarStereo()
extent = [-180, 180, -90, -60]

fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(1, 1, 1, projection=projection)
ax.set_extent(extent, crs=ccrs.PlateCarree())
ax.coastlines(resolution='50m', color='k')
ax.gridlines(color='lightgrey', linestyle='-', draw_labels=True)
</code>```

Body:
I tried to add tick labels after using .set_boundary(), but failed.How to achieve it？

ax1.set_extent([-180, 180, -90, -60], ccrs.PlateCarree())
ax1.add_feature(cfeature.LAND)
ax1.add_feature(cfeature.OCEAN)
ax1.gridlines()

ax2.gridlines()
ax2.add_feature(cfeature.LAND)
ax2.add_feature(cfeature.OCEAN)
theta = np.linspace(0, 2*np.pi, 100)
center, radius = [0.5, 0.5], 0.5
verts = np.vstack([np.sin(theta), np.cos(theta)]).T
circle = mpath.Path(verts * radius + center)
ax2.set_boundary(circle, transform=ax2.transAxes)

ax1.gridlines(draw_labels=True)
ax2.gridlines(draw_labels=True)

Body:
There is missing code in your example so I can't be sure it will solve your problem, but Cartopy allows longitude and latitude labeling to all projections starting only with version 0.18 (whats new and PR). Before that only PlateCarree and Mercator were allowed and any other projection would fail with error:

TypeError: Cannot label gridlines on a SouthPolarStereo plot. Only PlateCarree and Mercator plots are currently supported.

With v0.18 the code (that I got from the PR linked above) makes the lonlat labels just fine:

import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature

projection = ccrs.SouthPolarStereo()
extent = [-180, 180, -90, -60]

fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(1, 1, 1, projection=projection)
ax.set_extent(extent, crs=ccrs.PlateCarree())
ax.coastlines(resolution='50m', color='k')
ax.gridlines(color='lightgrey', linestyle='-', draw_labels=True)


问:
Prevent ID autogeneration on copy-paste in Visual Studio 2008 ASP.NET Web Form
If I have the following in an ASP.NET Web Form:

```<code><asp:TextBox runat="server" ID="tbxUser"/>
</code>```

and I copy and paste that line in the same page, I usually get the following:

```<code><asp:TextBox runat="server" ID="TextBox1"/>
</code>```

Obviously, nobody is going to name their controls in that way (if you don't want to name a textbox, simply don't asign an ID to it), and it's not nice having to change the ids of pasted controls. The same happens if I copy a control without an explicit ID, VS simply generates one for me.

Is there any way of preventing VS from autogenerating IDs when I copy-paste ASP.NET code?

答:
I have a workaround ...
copy part of tag .
for example:

and then add the close tag ">" manually.

Best Regards'

Body:
If I have the following in an ASP.NET Web Form:

<asp:TextBox runat="server" ID="tbxUser"/>

and I copy and paste that line in the same page, I usually get the following:

<asp:TextBox runat="server" ID="TextBox1"/>

Obviously, nobody is going to name their controls in that way (if you don't want to name a textbox, simply don't asign an ID to it), and it's not nice having to change the ids of pasted controls. The same happens if I copy a control without an explicit ID, VS simply generates one for me.

Is there any way of preventing VS from autogenerating IDs when I copy-paste ASP.NET code?


问:
'git pull' command faied:Permission denied
Error Message:

```<code>error: unable to write file .git/objects/pack/pack-92ef...e9d2.pack: Permission denied
fatal: cannot store pack file
fatal: index-pack failed
</code>```

I tried to delete all the files in the pack folder, but it failed. Still can't submit。

it makes me cannot pull and push.

How to solve it?
help!

答:
If you deleted all the files in your .git/objects/pack folder, you've very likely lost data.  Those files are used to store a compressed version of your Git data, and by deleting them, you've lost any data in that folder that isn't in another repository either on your computer or on a remote server.  If you have backups, you should use them now.

As for the reason you're getting this error, the message means that you don't have the proper permissions on that directory.  If you're on Linux, macOS, or another Unix system, you should make sure that you have read, write, and execute permissions on all of these directories: .git, .git/objects, and .git/objects/pack.  You should use chmod to change the permissions if need be.  If you're on Windows, you need to adjust the permissions appropriately for that operating system; its ACLs are much more complicated and there is not space to discuss it all here.

Body:
Error Message:

error: unable to write file .git/objects/pack/pack-92ef...e9d2.pack: Permission denied
fatal: cannot store pack file
fatal: index-pack failed

I tried to delete all the files in the pack folder, but it failed. Still can't submit。

it makes me cannot pull and push.

How to solve it?
help!


答:
As a starter: if you are running MySQL 8.0, you can do this easily with window functions:

```<code>select
    date,
    ant,
    sum(num_habit) as hab,
    sum(sum(num_habit)) over(order by date) cumulative_hab,
    sum(sum(num_habit)) over(order by date desc) reverse_cumulative_hab
from mytable
where date between current_date - interval 5 day and current_date
group by date, ant
order by date
</code>```

In earlier versions, it is more complicated. I would suggest joining two queries:

```<code>select t.*, r.reverse_cumulative_hab
from (
    select t.*, @csum := @csum + hab cumulative_hab
    from (
        select date, ant, sum(num_habit) as hab
        from mytable
        where date between current_date - interval 5 day and current_date
        group by date, ant
        order by date
    ) t
    cross join (select @csum := 0) x
) t
inner join (
    select t.*, @rcsum := @rcsum + hab reverse_cumulative_hab
    from (
        select date, ant, sum(num_habit) as hab
        from mytable
        where date between current_date - interval 5 day and current_date
        group by date, ant
        order by date desc
    ) t
    cross join (select @rcsum := 0) x
) r on r.date = t.date
order by t.date
</code>```

This assumes no duplicate ant per date.

It might also be possible to simplify the logic and compute the reverse sum by taking the difference between the cumulative sum and the overall sum:

```<code>select t.*, z.total_hab - t.cumulative_hab reverse_cumulative_hab
from (
    select t.*, @csum := @csum + hab cumulative_hab
    from (
        select date, ant, sum(num_habit) as hab
        from mytable
        where date between current_date - interval 5 day and current_date
        group by date, ant
        order by date
    ) t
    cross join (select @csum := 0) x
) t
cross join (
    select sum(num_habit) as total_hab
    from mytable
    where date between current_date - interval 5 day and current_date
) z
order by date
</code>```

Note that these queries are safer than your original code in regard of ordering of the rows: records are ordered in a subquery before the cumulative sum is computed.

Title: How to calculate reverse running sum in MySQL

Body:
I have this query where I calculated cumulative sum. Now, I need to calculate reverse cumulative sum for the same variable

SELECT t1.date, t1.ant, t1.hab,
(@csum:= @csum + t1.hab) as cumulative_hab
from(
SELECT date,
        ant,
        sum(num_habit) as hab
        from xxxxxxxxxx
        WHERE date BETWEEN CURDATE() - INTERVAL 5 DAY AND CURDATE()
        group by ant) AS t1
,(select @csum := 0) vars
order by t1.ant

My table look like this

date       ant   hab    cumulative_hab
24-05-2020  0   382,000   382,000
24-05-2020  1   28,000    410,000
24-05-2020  2   26,000    436,000
24-05-2020  3   11,000    447,000
24-05-2020  4   29,000    476,000
24-05-2020  6   6,000     482,000
24-05-2020  7   12,000    494,000
28-05-2020  8   50,000    544,000
24-05-2020  12  5,000     549,000
24-05-2020  13  6,000     555,000

I would like another column with reverse running sum (reverse cumulative sum), the first value is calculated 555 - 382

 date      ant   hab    cumulative_hab   reverse_cum_hab
24-05-2020  0   382,000   382,000             555,000
24-05-2020  1   28,000    410,000             173,000,
24-05-2020  2   26,000    436,000             145,000
24-05-2020  3   11,000    447,000             119,000
24-05-2020  4   29,000    476,000             108,000
24-05-2020  6   6,000     482,000              79,000
24-05-2020  7   12,000    494,000              73,000
28-05-2020  8   50,000    544,000              61,000
24-05-2020  12  5,000     549,000              11,000
24-05-2020  13  6,000     555,000               6,000

Body:
As a starter: if you are running MySQL 8.0, you can do this easily with window functions:

select
    date,
    ant,
    sum(num_habit) as hab,
    sum(sum(num_habit)) over(order by date) cumulative_hab,
    sum(sum(num_habit)) over(order by date desc) reverse_cumulative_hab
from mytable
where date between current_date - interval 5 day and current_date
group by date, ant
order by date

In earlier versions, it is more complicated. I would suggest joining two queries:

select t.*, r.reverse_cumulative_hab
from (
    select t.*, @csum := @csum + hab cumulative_hab
    from (
        select date, ant, sum(num_habit) as hab
        from mytable
        where date between current_date - interval 5 day and current_date
        group by date, ant
        order by date
    ) t
    cross join (select @csum := 0) x
) t
inner join (
    select t.*, @rcsum := @rcsum + hab reverse_cumulative_hab
    from (
        select date, ant, sum(num_habit) as hab
        from mytable
        where date between current_date - interval 5 day and current_date
        group by date, ant
        order by date desc
    ) t
    cross join (select @rcsum := 0) x
) r on r.date = t.date
order by t.date

This assumes no duplicate ant per date.

It might also be possible to simplify the logic and compute the reverse sum by taking the difference between the cumulative sum and the overall sum:

select t.*, z.total_hab - t.cumulative_hab reverse_cumulative_hab
from (
    select t.*, @csum := @csum + hab cumulative_hab
    from (
        select date, ant, sum(num_habit) as hab
        from mytable
        where date between current_date - interval 5 day and current_date
        group by date, ant
        order by date
    ) t
    cross join (select @csum := 0) x
) t
cross join (
    select sum(num_habit) as total_hab
    from mytable
    where date between current_date - interval 5 day and current_date
) z
order by date

Note that these queries are safer than your original code in regard of ordering of the rows: records are ordered in a subquery before the cumulative sum is computed.


问:
How to assign url parameter value and load in iframe using radio buttons
Using select/option tag works fine but no success when I use radio buttons.

function xxx(){
 var base_url = 'https://example.com/?test=';
 var select_value = document.getElementById('myid').value;
 var target_url = base_url + select_value;
 var ifr = document.getElementById('myiframe');
 ifr.src = target_url;
 return false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <form>
      <select id="myid" onchange="xxx();">
        <option value="VALUE1">Featured</option>
        <option value="VALUE2">Hey</option>
        <option value="VALUE3">Wish</option>
      </select>
    </form>
<iframe src="" id="myiframe" width="460" height="300"></iframe></code>```

I want to use below format but the result is "undefined"...

```<code><form id="myid" onchange="xxx();">
  <input type="radio" name="name1" value="VALUE1"> featured<br>
  <input type="radio" name="name1" value="VALUE2"> hey<br>
  <input type="radio" name="name1" value="VALUE3"> wish
</form>
</code>```

I'm getting this

https://example.com/?test=UNDEFINED

instead of

https://example.com/?test=VALUE1 or VALUE2 or VALUE3

答:
I am not a PRO in JavaScript but I think it is working

function xxx(){
 var base_url = 'https://example.com/?test=';
 var select_value = document.getElementById('myid').value;
 var target_url = base_url + select_value;
 var ifr = document.getElementById('myiframe');
 ifr.src = target_url;
 return false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
      <select id="myid" onchange="xxx();">
        <option value="VALUE1">Featured</option>
        <option value="VALUE2">Hey</option>
        <option value="VALUE3">Wish</option>
      </select>

    </form>

    <form>
    <input type="radio" id="myid" onchange="xxx();" name="value" value="value1">
<label for="value1">Featured</label><br>
<input type="radio" id="myid" onchange="xxx();" name="value" value="value2">
<label for="value2">Hey</label><br>
<input type="radio" id="myid" onchange="xxx();" name="value" value="value3">
<label for="value3">Wish</label></form>

<iframe src="" id="myiframe" width="460" height="300"></iframe></code>```

Body:
Using select/option tag works fine but no success when I use radio buttons.

function xxx(){
 var base_url = 'https://example.com/?test=';
 var select_value = document.getElementById('myid').value;
 var target_url = base_url + select_value;
 var ifr = document.getElementById('myiframe');
 ifr.src = target_url;
 return false;
}

    <form>
      <select id="myid" onchange="xxx();">
        <option value="VALUE1">Featured</option>
        <option value="VALUE2">Hey</option>
        <option value="VALUE3">Wish</option>
      </select>
    </form>

I want to use below format but the result is "undefined"...

<form id="myid" onchange="xxx();">
  <input type="radio" name="name1" value="VALUE1"> featured

  <input type="radio" name="name1" value="VALUE2"> hey

  <input type="radio" name="name1" value="VALUE3"> wish
</form>

I'm getting this

https://example.com/?test=UNDEFINED

instead of

https://example.com/?test=VALUE1 or VALUE2 or VALUE3

Body:
I am not a PRO in JavaScript but I think it is working

function xxx(){
 var base_url = 'https://example.com/?test=';
 var select_value = document.getElementById('myid').value;
 var target_url = base_url + select_value;
 var ifr = document.getElementById('myiframe');
 ifr.src = target_url;
 return false;
}

<form>
      <select id="myid" onchange="xxx();">
        <option value="VALUE1">Featured</option>
        <option value="VALUE2">Hey</option>
        <option value="VALUE3">Wish</option>
      </select>

    </form>

    <form>
    <input type="radio" id="myid" onchange="xxx();" name="value" value="value1">
<label for="value1">Featured</label><br>
<input type="radio" id="myid" onchange="xxx();" name="value" value="value2">
<label for="value2">Hey</label><br>
<input type="radio" id="myid" onchange="xxx();" name="value" value="value3">
<label for="value3">Wish</label></form>

<iframe src="" id="myiframe" width="460" height="300"></iframe>


问:
Executing a command when a list is equal to one line of a matrix in python
If all 3 of the values in the list below are equal to any of the 3 values in one line of the matrix, I want it to print 'hello'. </p>

```<code>#if x is equal to the 1st line of the matrix I want it to print hello. If x is equal to the 2nd part and not the 1st I still want it to print the same string.

x = [1, 2, 3]
y = [
    [1, 2, 3],
    [4, 5, 6],
    [3, 4, 5],
    [7, 8, 9]
]
if x == (y):
    print('hello')
</code>```

<p>As shown above, the x list value is equal to one of the lines in the matrix but it won't print hello. How would I get the program to do that. </p>

答:
There is a built-in function for this kind of testing, called any, that checks if any of a sequence of values is True. We don't have the true or false values we want yet, so we need to create them. The strategy is to transform from the value that's in the y list, into a true value that indicates whether that value is equal to x. We can do this elegantly with a generator expression:

```<code>any(row == x for row in y)
</code>```

It means exactly what it sounds like: if any of the row values is == x, considered for the row values that are in y.

Body:
If all 3 of the values in the list below are equal to any of the 3 values in one line of the matrix, I want it to print 'hello'.

#if x is equal to the 1st line of the matrix I want it to print hello. If x is equal to the 2nd part and not the 1st I still want it to print the same string.

x = [1, 2, 3]
y = [
    [1, 2, 3],
    [4, 5, 6],
    [3, 4, 5],
    [7, 8, 9]
]
if x == (y):
    print('hello')

As shown above, the x list value is equal to one of the lines in the matrix but it won't print hello. How would I get the program to do that.

Body:
There is a built-in function for this kind of testing, called any, that checks if any of a sequence of values is True. We don't have the true or false values we want yet, so we need to create them. The strategy is to transform from the value that's in the y list, into a true value that indicates whether that value is equal to x. We can do this elegantly with a generator expression:

any(row == x for row in y)

It means exactly what it sounds like: if any of the row values is == x, considered for the row values that are in y.


问:
Any way to cache git source files?
There is this great Cache task in Build pipelines.  It works great to cache nuget and npm packages (among others), but I don't see a corollary for the git sources.

Is there any way to do this, short of disabling the built in get sources and running our own git checkout as a task?  We have a relatively large repo that takes about 3 minutes to sync.  I'd like to reduce that if possible.  I've already tried using shallow fetch set to a depth of 1, and it hasn't appreciably changed the checkout time.

答:
Azure devops doesnot have this feature of Caching git source currently.

However, if you use self-hosted agent, the git source will be cached on your self-hosted agent machine by default(in the pipeline source code directory. eg. C:\agent\_work\1\s ). Next time when you run your pipeline, it will only checkout the changed files to your local machine.

So you can create a self-hosted agent to run your pipeline. Check here for detailed steps to create self-hosted agent.

(If you want to clean the source code folder each time you run the pipeline. You can set the clean to true for checkout step.  clean option of checkout step will not work for Microsoft-hosted agent. Because Each time you run a pipeline, you get a fresh virtual machine. The virtual machine is discarded after one use.)

You can also click here to submit a feature request(Click Suggest a feature and select Azure Devops.
) to Microsoft development team. Hopefully they will consider adding this feature in the future.

Title: Any way to cache git source files?


问:
“Microsoft.VisualBasic.FileIO does not exist”. How to include this library in my project?
So I am trying to parse a .csv file with columns that may include their own comma characters.

Answers here and here say that the best way to easily handle this without writing my own line-by-line parser would be to use the Microsoft.VisualBasic.FileIO library.

Unfortunately, when i try to include this in my project I get the common error:

```<code>'File.IO' does not exist in the namespace "Microsoft.VisualBasic" (are you missing an assembly reference?)
</code>```

Fixes for this issue here and here all say that I need to use the Reference Manager to add Microsoft.VisualBasic to my project, but my reference manager does not have the Assemblies, with Framework and Extensions subgroups tabs that the official help documents say to use to add the package to my project. I have attached a screenshot of my Reference Manager window here. The Projects tab just shows a list of all the projects in my solution and the Shared Projects tab is blank.

I have also checked to see if I should include a NuGet package instead, but that did not solve the problem at all.

答:
I find the solution for solving the problem.

First, please change your platform from .net core2.1 to .net core3.0 or.net core 3.1.

Second, you can refer to the following code to convert csv file to datatable by using

Microsoft.VisualBasic.FileIO.

```<code>static void Main(string[] args)
        {
            DataTable table = GetDataTabletFromCSVFile("D:\\Test.csv");
        }

        private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
        {
            DataTable csvData = new DataTable();
            try
            {
                using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
                {
                    csvReader.SetDelimiters(new string[] { "," });
                    csvReader.HasFieldsEnclosedInQuotes = true;
                    string[] colFields = csvReader.ReadFields();
                    foreach (string column in colFields)
                    {
                        if (column == "Name" || column == "Age" || column == "Id")
                        {
                            DataColumn datecolumn = new DataColumn(column);
                            datecolumn.AllowDBNull = true;
                            csvData.Columns.Add(datecolumn);
                        }
                    }
                    while (!csvReader.EndOfData)
                    {
                        string[] fieldData = csvReader.ReadFields();
                        for (int i = 0; i < fieldData.Length; i++)
                        {
                            if (fieldData[i] == "")
                            {
                                fieldData[i] = null;
                            }
                        }
                        csvData.Rows.Add(fieldData);
                    }
                }

            }
            catch (Exception)
            {
                throw;
            }
            return csvData;
        }
</code>```

Result:

Body:
So I am trying to parse a .csv file with columns that may include their own comma characters.

Answers here and here say that the best way to easily handle this without writing my own line-by-line parser would be to use the Microsoft.VisualBasic.FileIO library.

Unfortunately, when i try to include this in my project I get the common error:

'File.IO' does not exist in the namespace "Microsoft.VisualBasic" (are you missing an assembly reference?)

Fixes for this issue here and here all say that I need to use the Reference Manager to add Microsoft.VisualBasic to my project, but my reference manager does not have the Assemblies, with Framework and Extensions subgroups tabs that the official help documents say to use to add the package to my project. I have attached a screenshot of my Reference Manager window here. The Projects tab just shows a list of all the projects in my solution and the Shared Projects tab is blank.

I have also checked to see if I should include a NuGet package instead, but that did not solve the problem at all.

Body:
I find the solution for solving the problem.

First, please change your platform from .net core2.1 to .net core3.0 or.net core 3.1.

Second, you can refer to the following code to convert csv file to datatable by using

Microsoft.VisualBasic.FileIO.

static void Main(string[] args)
        {
            DataTable table = GetDataTabletFromCSVFile("D:\\Test.csv");
        }

        private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
        {
            DataTable csvData = new DataTable();
            try
            {
                using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
                {
                    csvReader.SetDelimiters(new string[] { "," });
                    csvReader.HasFieldsEnclosedInQuotes = true;
                    string[] colFields = csvReader.ReadFields();
                    foreach (string column in colFields)
                    {
                        if (column == "Name" || column == "Age" || column == "Id")
                        {
                            DataColumn datecolumn = new DataColumn(column);
                            datecolumn.AllowDBNull = true;
                            csvData.Columns.Add(datecolumn);
                        }
                    }
                    while (!csvReader.EndOfData)
                    {
                        string[] fieldData = csvReader.ReadFields();
                        for (int i = 0; i < fieldData.Length; i++)
                        {
                            if (fieldData[i] == "")
                            {
                                fieldData[i] = null;
                            }
                        }
                        csvData.Rows.Add(fieldData);
                    }
                }

            }
            catch (Exception)
            {
                throw;
            }
            return csvData;
        }

Result:


问:
Getting infinite loop overflow ONLY on linux - C
i've been stuck fro 6 hours at least to find ot what's wrong with my menu driven program.

Basically i made an excercise for an exam and to pass it i have to validate 2 test cases where at a specific input.txt file correspond an output.txt file

Now comes the fun part. SAME program, on Liux, with one test case it works flawessly, on the other the SAME menu code is causing never-ending menu operations like if the choice variable has always something in it. Of course on windows everything work as intended.

Anyone can help me with this? i'm getting crazy....

Edit: i run the program like this "./main < input0.txt"

It is about a library, at first you have to insert all the books and save them into a list, secondly a menu is shown asking you to search, rent or bring back a book, print the catalogue or exit if choice equals 5.

Actually the problem starts after inserting all the books into the program, the menu doesn't wait for user input and just starts to perform random actions in an infinite loop.

This is the code:

```<code>void menu(ptr head) {
    //Array di funzioni per gestire le prime 4 scelte: la scelta di uscita dal programma e' gestita direttamente dal ciclo
    void (*chose[4])(ptr*) = { print_catalogue, search_book, rent, bring_back };
    int scelta = 0;
    // for infinito per poter validare meglio l'input
    for (;;) {
        printf("Scegli un opzione:\n1) Stampa catalogo.\n2) Cerca.\n3) Prestito.\n4) Restituzione.\n5) Esci.\nScelta: ");
        if (scanf("%d", &scelta) != 1 || scelta < 1 || scelta > 5) {
            printf("Errore. Scelta non valida.\n");
            // clean the buffer
            scanf("%*[^\n]%*1[\n]");
        }
        else if (scelta == 5) { // devo uscire dell'intero programma
            break;
        }
        else { // ho inserito un numero valido, posso procedere
            // clean the buffer
            scanf("%*[^\n]%*1[\n]");
            (*chose[scelta - 1])(&head);
        }
    }

    // programma terminato libero la memoria
    freeList(&head);
    puts("Bye");
}
</code>```

i'm pretty sure with debugging that the problem is the menu...

答:
At least these problems:

Not clearing the buffer

The following fails to consume all the text up to the '\n' when the first character is a '\n'.

```<code>// clean the buffer
scanf("%*[^\n]%*1[\n]");  // weak
// scanf() stop on first specifier when input is `\n`
</code>```

Instead, use 2 calls

```<code>scanf("%*[^\n]");
scanf("%*1[\n]");
</code>```

Missing end-of-file detection

When scanf("%d", &scelta) returns EOF due to end-of-file, OP's code will loop forever.  @TonyB

```<code> // if (scanf("%d", &scelta) != 1 || scelta < 1 || scelta > 5) {
 int cnt = scanf("%d", &scelta);
 if (cnt == EOF) break;
 if (cnt != 1 || scelta < 1 || scelta > 5) {
</code>```

Insure output is flushed

After the print, flush - espsaily with line buffered stdout and print does not end with '\n'.

```<code>    printf("Scegli un opzione:\n1) Stampa catalogo.\n2) Cerca.\n3) Prestito.\n4) Restituzione.\n5) Esci.\nScelta: ");
    fflush(stdout); //Add
</code>```

Suspicion

Problems exist in unposted print_catalogue, search_book, rent, bring_back.

Perhaps other troubles too?

Tip: Save time.  Do not use scanf().  Usge fgets() to read a line of input into a string and then parse with sscanf(), strtol() etc.  Much easier to handle errant input.

Body:
i've been stuck fro 6 hours at least to find ot what's wrong with my menu driven program.

Basically i made an excercise for an exam and to pass it i have to validate 2 test cases where at a specific input.txt file correspond an output.txt file

Now comes the fun part. SAME program, on Liux, with one test case it works flawessly, on the other the SAME menu code is causing never-ending menu operations like if the choice variable has always something in it. Of course on windows everything work as intended.

Anyone can help me with this? i'm getting crazy....

Edit: i run the program like this "./main < input0.txt"

It is about a library, at first you have to insert all the books and save them into a list, secondly a menu is shown asking you to search, rent or bring back a book, print the catalogue or exit if choice equals 5.

Actually the problem starts after inserting all the books into the program, the menu doesn't wait for user input and just starts to perform random actions in an infinite loop.

This is the code:

void menu(ptr head) {
    //Array di funzioni per gestire le prime 4 scelte: la scelta di uscita dal programma e' gestita direttamente dal ciclo
    void (*chose[4])(ptr*) = { print_catalogue, search_book, rent, bring_back };
    int scelta = 0;
    // for infinito per poter validare meglio l'input
    for (;;) {
        printf("Scegli un opzione:\n1) Stampa catalogo.\n2) Cerca.\n3) Prestito.\n4) Restituzione.\n5) Esci.\nScelta: ");
        if (scanf("%d", &scelta) != 1 || scelta < 1 || scelta > 5) {
            printf("Errore. Scelta non valida.\n");
            // clean the buffer
            scanf("%*[^\n]%*1[\n]");
        }
        else if (scelta == 5) { // devo uscire dell'intero programma
            break;
        }
        else { // ho inserito un numero valido, posso procedere
            // clean the buffer
            scanf("%*[^\n]%*1[\n]");
            (*chose[scelta - 1])(&head);
        }
    }

    // programma terminato libero la memoria
    freeList(&head);
    puts("Bye");
}

i'm pretty sure with debugging that the problem is the menu...

Body:
At least these problems:

Not clearing the buffer

The following fails to consume all the text up to the '\n' when the first character is a '\n'.

// clean the buffer
scanf("%*[^\n]%*1[\n]");  // weak
// scanf() stop on first specifier when input is `\n`

Instead, use 2 calls

scanf("%*[^\n]");
scanf("%*1[\n]");

Missing end-of-file detection

When scanf("%d", &scelta) returns EOF due to end-of-file, OP's code will loop forever.  @TonyB

 // if (scanf("%d", &scelta) != 1 || scelta < 1 || scelta > 5) {
 int cnt = scanf("%d", &scelta);
 if (cnt == EOF) break;
 if (cnt != 1 || scelta < 1 || scelta > 5) {

Insure output is flushed

After the print, flush - espsaily with line buffered stdout and print does not end with '\n'.

    printf("Scegli un opzione:\n1) Stampa catalogo.\n2) Cerca.\n3) Prestito.\n4) Restituzione.\n5) Esci.\nScelta: ");
    fflush(stdout); //Add

Suspicion

Problems exist in unposted print_catalogue, search_book, rent, bring_back.

Perhaps other troubles too?

Tip: Save time.  Do not use scanf().  Usge fgets() to read a line of input into a string and then parse with sscanf(), strtol() etc.  Much easier to handle errant input.


问:
Euro currency symbol creeping into parsed excel output
I'm using Spreadsheet::BasicRead to extract data from a spreadsheet generated by a Quickbooks online report. Some cells have what look to be a currency format with a leading dollar sign. However, after extracting the data, data from those cells look like this: '20.00  €'.

I could just strip out the symbol, but would like to know why this is happening. I inspected the xml inside the xlsx file and see the euro symbol in there (even though in the spreadsheet it is displayed as a dollar sign):

```<code>styles.xml:<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><numFmts count="2"><numFmt numFmtId="165" formatCode="#,##0.00\ _€"/><numFmt numFmtId="166" formatCode=""$"* #,##0.00\ _€"/></numFmts>
</code>```

Is there a solution? Maybe I just need a better spreadsheet parser?

答:
As best as I can tell, the _€ add padding to the left hand side of the cell. I have confirmed this by adding several _€ characters at the end of the custom format in an Excel spreadsheet program. According to MS documentation, the underscore adds in a space equal to the width of the character that follows it.

I'm not sure why Quickbooks chose the euro symbol.

At any rate, this format specifier should get stripped out.

Body:
I'm using Spreadsheet::BasicRead to extract data from a spreadsheet generated by a Quickbooks online report. Some cells have what look to be a currency format with a leading dollar sign. However, after extracting the data, data from those cells look like this: '20.00  €'.

I could just strip out the symbol, but would like to know why this is happening. I inspected the xml inside the xlsx file and see the euro symbol in there (even though in the spreadsheet it is displayed as a dollar sign):

styles.xml:


问:
Dagger2 dependency Cycle by Using @Binds and @Inject fields
I am getting a dependency cycle whenever I try to use a subcomponent with binding objects. I have an app scope and an activity scope.  At the app scope I create my web service then when the activity opens I want to create a storage object, controller, and navigator (all custom classes not androidx classes) and inject them into my androidx ViewModel class.  But when I do so I get a dependency cycle.

My top level component looks like

```<code>@AppScope
@Component(modules = [AppModule::class])
interface AppComponent {

  val activityComponentBuilder: ActivityComponent.Builder
}

@Module(subcomponents = [ActivityComponent::class])
interface AppModule {

  @Binds
  fun mockWebService(mockWebService: MockWebService): MockWebService
}
</code>```

Next my subcomponent looks like

```<code>@ActivityComponent
@Subcomponent(modules = [ActivityModule::class])
interface ActivityComponent {

  fun inject(sharedViewModel: SharedViewModel)

  @Subcomponent.Builder
  interface Builder {
    @BindsInstance
    fun storage(storage: Storage): Builder

    fun build(): ActivityComponent
  }
}
</code>```

In my activity module I bind two objects

```<code>  @Binds
  abstract fun controller(controller: Controller): Controller

  @Binds
  abstract fun navigator(navigator: Navigator): Navigator
</code>```

Each object has an @Inject constructor

```<code>class Navigator @Inject constructor(private val storage: Storage)

class Controller @Inject constructor(
  private val webService: MockWebService,
  private val navigator: Navigator,
  private val storage: Storage
) {
</code>```

Inside my shared view model I try to build my component and inject the fields

```<code>  @Inject
  lateinit var navigator: Navigator
  @Inject
  lateinit var controller: Controller

  init {
      MainApplication.component.activityComponentBuilder
        .storage(InMemoryStorage.from(UUID.randomUUID().toString()))
        .build()
        .inject(this)

  }
</code>```

But dagger won't build.  I get an error

```<code>[Dagger/DependencyCycle] Found a dependency cycle: public abstract interface AppComponent {

MockWebService is injected at di.AppModule.mockWebService(mockWebService)
MockWebService is injected at ActivityModule.Controller(webService, …)
Controller is injected at SharedViewModel.controller
SharedViewModel is injected at
</code>```

But the error message cuts off there. Am I missing something in how to use a subcomponent to put objects on the graph and then inject them into an object?  Is this not possible with Dagger?

答:
@Binds is used to let dagger know the different implementations of an interface. You don't need @Binds here since Navigator and Controller are simple classes that do not implement any interface. I'd assume that's the case with MockWebService too. Also, those classes have @Inject constructor, which means dagger can instantiate them and we don't need to write extra @Provides functions for those classes.

@Binds isn't doing any scoping. Its only job is to tell dagger about different implementations. You can add @XScope with @Binds to make some object scoped. Or, you could just add the scope annotation to the class declaration. Here's an example of how you can add scope to class declaration.

As for the dependency cycle, I think it's because you're telling ActivityComponent to use ActivityModule and telling ActivityModule to install ActivityComponent. Doing just either one should be the case (I think).

Body:
I am getting a dependency cycle whenever I try to use a subcomponent with binding objects. I have an app scope and an activity scope.  At the app scope I create my web service then when the activity opens I want to create a storage object, controller, and navigator (all custom classes not androidx classes) and inject them into my androidx ViewModel class.  But when I do so I get a dependency cycle.

My top level component looks like

@AppScope
@Component(modules = [AppModule::class])
interface AppComponent {

  val activityComponentBuilder: ActivityComponent.Builder
}

@Module(subcomponents = [ActivityComponent::class])
interface AppModule {

  @Binds
  fun mockWebService(mockWebService: MockWebService): MockWebService
}

Next my subcomponent looks like

@ActivityComponent
@Subcomponent(modules = [ActivityModule::class])
interface ActivityComponent {

  fun inject(sharedViewModel: SharedViewModel)

  @Subcomponent.Builder
  interface Builder {
    @BindsInstance
    fun storage(storage: Storage): Builder

    fun build(): ActivityComponent
  }
}

In my activity module I bind two objects

  @Binds
  abstract fun controller(controller: Controller): Controller

  @Binds
  abstract fun navigator(navigator: Navigator): Navigator

Each object has an @Inject constructor

class Navigator @Inject constructor(private val storage: Storage)

class Controller @Inject constructor(
  private val webService: MockWebService,
  private val navigator: Navigator,
  private val storage: Storage
) {

Inside my shared view model I try to build my component and inject the fields

  @Inject
  lateinit var navigator: Navigator
  @Inject
  lateinit var controller: Controller

  init {
      MainApplication.component.activityComponentBuilder
        .storage(InMemoryStorage.from(UUID.randomUUID().toString()))
        .build()
        .inject(this)

  }

But dagger won't build.  I get an error

[Dagger/DependencyCycle] Found a dependency cycle: public abstract interface AppComponent {

MockWebService is injected at di.AppModule.mockWebService(mockWebService)
MockWebService is injected at ActivityModule.Controller(webService, …)
Controller is injected at SharedViewModel.controller
SharedViewModel is injected at

But the error message cuts off there. Am I missing something in how to use a subcomponent to put objects on the graph and then inject them into an object?  Is this not possible with Dagger?


问:
ios swift How to programmattically change background color of view on screen rotation?
This is part of a much bigger issue I  am having. I have simplified it for you. I want to programmatically change the background color of view on device orientation ?

The following code prints "landcape" and "portrait" in the debugging console every-tome I  rotate the device in the simulator :-

```<code>  import UIKit
  class OrientationViewController: UIViewController {
  override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    if UIDevice.current.orientation.isLandscape {
        print("landscape")
    } else {
        print("portrait")
    }
  }
}
</code>```

Though the following code does nothing :-

```<code>   import UIKit
   class AskitViewController: UIViewController {
    override func viewDidLoad() {
    let landscapesmallview = UIView()
    landscapesmallview.backgroundColor = .orange
   let portraitsmallview = UIView()
    portraitsmallview.backgroundColor = .purple
    view.addSubview(landscapesmallview)
    view.addSubview(portraitsmallview)

 func viewWillTransition(to size: CGSize, with coordinator:      UIViewControllerTransitionCoordinator) {
     if UIDevice.current.orientation.isLandscape {
        print("landscape")
    landscapesmallview.translatesAutoresizingMaskIntoConstraints = false
     portraitsmallview.translatesAutoresizingMaskIntoConstraints = true
    } else {
        print("potrait")
  portraitsmallview.translatesAutoresizingMaskIntoConstraints = false
  landscapesmallview.translatesAutoresizingMaskIntoConstraints = true
        }
       }
      }
     }
</code>```

I am using swift 4.2 and or 5, xcode 10.2
   So, how to programmatically change the background color of view every-time I rotate  the device ?

Please, any of you experts help me ?

edit 1:

I had told you'll in the beginning that it is a part of a bigger issue -

I have buttons inside a view which in potrait mode I want like this -

which is achieved by the following code -

//original potrait mode/////

```<code>    import UIKit
    class PotraitViewController: UIViewController {
    override func viewDidLoad() {
    let buttonred = UIButton()
    buttonred.backgroundColor = UIColor.red
    let buttonblue = UIButton()
    buttonblue.backgroundColor = UIColor.blue
    let landscapesmallview = UIView()
    view.addSubview(landscapesmallview)
    landscapesmallview.addSubview(buttonred)
    landscapesmallview.addSubview(buttonblue)
    buttonred.translatesAutoresizingMaskIntoConstraints = false
    buttonblue.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([

        buttonred.topAnchor.constraint(equalTo: view.topAnchor,constant: 200),
        buttonred.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        buttonred.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant:-20),
        buttonred.widthAnchor.constraint(equalToConstant: 50),
        //-------
        buttonblue.topAnchor.constraint(equalTo: buttonred.bottomAnchor,constant: 40),
        buttonblue.leadingAnchor.constraint(equalTo: buttonred.leadingAnchor),
        buttonblue.trailingAnchor.constraint(equalTo:buttonred.trailingAnchor),
        buttonblue.widthAnchor.constraint(equalTo: buttonred.widthAnchor)

        ])
    }

 }
</code>```

and in landscape mode  I want like this -

which is achieved by the following code -

// original lanscape mode/////

```<code>  import UIKit
  class LandscapeViewController: UIViewController {
   override func viewDidLoad() {
    let buttonred = UIButton()
    buttonred.backgroundColor = UIColor.red
    let buttonblue = UIButton()
    buttonblue.backgroundColor = UIColor.blue
    view.addSubview(buttonred)
    view.addSubview(buttonblue)
    buttonred.translatesAutoresizingMaskIntoConstraints = false
    buttonblue.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([

        buttonred.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        buttonred.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant:40),
        buttonred.trailingAnchor.constraint(equalTo: view.centerXAnchor,constant:-20),
        buttonred.widthAnchor.constraint(equalToConstant: 50),

        //-------
        buttonblue.centerYAnchor.constraint(equalTo: buttonred.centerYAnchor),
        buttonblue.leadingAnchor.constraint(equalTo: view.centerXAnchor,constant:40),
        buttonblue.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant:-20),
        buttonblue.widthAnchor.constraint(equalTo:buttonred.widthAnchor)

        ])
     }

  }
</code>```

So, I tried the following code to achieve by screen rotation i.e. two different  layouts in potrait and landscape views programmatically with the help of the following code:-

```<code>    import UIKit

    class NewViewController: UIViewController {
    override func viewDidLoad() {
    let buttonredlandscape = UIButton()
    buttonredlandscape.backgroundColor = UIColor.red
    let buttonbluelandscape = UIButton()
    buttonbluelandscape.backgroundColor = UIColor.blue
    let buttonredportrait = UIButton()
    buttonredportrait.backgroundColor = UIColor.red
    let buttonblueportrait = UIButton()
    buttonblueportrait.backgroundColor = UIColor.blue

    let landscapesmallview = UIView()
    let portraitsmallview = UIView()
    landscapesmallview.backgroundColor = UIColor.gray
    portraitsmallview.backgroundColor = UIColor.purple
    landscapesmallview.frame = view.frame
    portraitsmallview.frame = view.frame
    view.addSubview(landscapesmallview)
    view.addSubview(portraitsmallview)

    landscapesmallview.addSubview(buttonredlandscape)
    landscapesmallview.addSubview(buttonbluelandscape)
    portraitsmallview.addSubview(buttonredportrait)
    portraitsmallview.addSubview(buttonblueportrait)
    buttonredlandscape.translatesAutoresizingMaskIntoConstraints = false
    buttonbluelandscape.translatesAutoresizingMaskIntoConstraints = false
    buttonredportrait.translatesAutoresizingMaskIntoConstraints = false
    buttonblueportrait.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activate([

    buttonredlandscape.centerYAnchor.constraint(equalTo:landscapesmallview.centerYAnchor),
        buttonredlandscape.topAnchor.constraint(equalTo:landscapesmallview.topAnchor,constant:40),
        buttonredlandscape.trailingAnchor.constraint(equalTo: landscapesmallview.centerXAnchor,constant:-20),
        buttonredlandscape.heightAnchor.constraint(equalTo: landscapesmallview.heightAnchor,constant:50),

        buttonbluelandscape.centerYAnchor.constraint(equalTo:buttonredlandscape.centerYAnchor),
        buttonbluelandscape.leadingAnchor.constraint(equalTo: landscapesmallview.centerXAnchor,constant:40),
        buttonbluelandscape.trailingAnchor.constraint(equalTo: landscapesmallview.trailingAnchor,constant:-20),
        buttonbluelandscape.heightAnchor.constraint(equalTo: buttonredlandscape.heightAnchor),

        buttonredportrait.topAnchor.constraint(equalTo: portraitsmallview.topAnchor,constant: 200),
        buttonredportrait.centerXAnchor.constraint(equalTo: portraitsmallview.centerXAnchor),
        buttonredportrait.trailingAnchor.constraint(equalTo: portraitsmallview.trailingAnchor,constant:-20),
        buttonredportrait.widthAnchor.constraint(equalTo: buttonredportrait.widthAnchor),

        buttonblueportrait.topAnchor.constraint(equalTo: buttonredportrait.bottomAnchor,constant: 40),
        buttonblueportrait.leadingAnchor.constraint(equalTo: buttonredportrait.leadingAnchor),
        buttonblueportrait.trailingAnchor.constraint(equalTo:buttonredportrait.trailingAnchor),
        buttonblueportrait.widthAnchor.constraint(equalTo: buttonredportrait.widthAnchor)

        ])

    //-------

    func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        if UIDevice.current.orientation.isLandscape {
            landscapesmallview.translatesAutoresizingMaskIntoConstraints = false
            portraitsmallview.translatesAutoresizingMaskIntoConstraints = true
        } else if UIDevice.current.orientation.isPortrait {
            portraitsmallview.translatesAutoresizingMaskIntoConstraints = false
            landscapesmallview.translatesAutoresizingMaskIntoConstraints = true

         }
      }

    }

  }
</code>```

which in potrait mode shows -

and which in landscape mode shows -

How to achieve what I want programmatically (see after edit 1) i.e. topmost 2  buttons to rearrange themselves programmatically every-time  the user rotates the device. Its not just the buttons. It can be labels, images, collectionview etc. or just anything. The upshot is that I want to achieve two layouts  in landscape and portrait modes programmatically.

Points to be noted :-

i) I want to use "NSLayoutConstraint.activate" because apple recommends it.

ii) If possible, I do not want to use stackview or containerview,  because there can be many more types of labels, buttons etc, but if there is no other way, then I will use it.

iii) Is my code DRY principle compliant ?

Also, guys, please, I do not deserve negative marks because,  as far as I know, this has not been asked before. I request you to remove negative marks and encourage me.

答:
i had make to view one for portraitsmallview and one for landscapesmallview
import UIKit

```<code>class ViewController: UIViewController {
    var landscapesmallview = UIView()
    var portraitsmallview = UIView()

    override func viewDidLoad() {

    landscapesmallview.frame = CGRect.init(x: 0, y: 0, width: 300, height: 500)
    landscapesmallview.backgroundColor = UIColor.yellow     //give color to the view
    landscapesmallview.center = self.view.center
    self.view.addSubview(landscapesmallview)

    portraitsmallview.frame = CGRect.init(x: 0, y: 0, width: 200, height: 300)
    portraitsmallview.backgroundColor = UIColor.blue     //give color to the view
    portraitsmallview.center = self.view.center
    self.view.addSubview(portraitsmallview)

    landscapesmallview.isHidden = true
    portraitsmallview.isHidden = true
        }
    override func viewWillLayoutSubviews() {
        if UIDevice.current.orientation.isPortrait {
            landscapesmallview.isHidden = true
            portraitsmallview.isHidden = false
        } else {
            landscapesmallview.isHidden = false
            portraitsmallview.isHidden = true

        }
    }
}
</code>```

and if you need change the backgrandcolor landscapesmallview.backgroundColor and portraitsmallview.backgroundColor

```<code>//
//  ViewController.swift
//  test
//
//  Created by Younouss EL OUATI on 5/29/20.
//  Copyright © 2020 Younouss EL OUATI. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    var landscapesmallview = UIView()
    var portraitsmallview = UIView()

    override func viewDidLoad() {

    landscapesmallview.frame = CGRect.init(x: 0, y: 0, width: 300, height: 500)
    landscapesmallview.backgroundColor = UIColor.yellow     //give color to the view
    landscapesmallview.center = self.view.center
    self.view.addSubview(landscapesmallview)

    portraitsmallview.frame = CGRect.init(x: 0, y: 0, width: 200, height: 300)
    portraitsmallview.backgroundColor = UIColor.blue     //give color to the view
    portraitsmallview.center = self.view.center
    self.view.addSubview(portraitsmallview)

    landscapesmallview.isHidden = true
    portraitsmallview.isHidden = true
        }
    override func viewWillLayoutSubviews() {
        if UIDevice.current.orientation.isPortrait {
            landscapesmallview.backgroundColor = UIColor.green
            landscapesmallview.isHidden = true
            portraitsmallview.isHidden = false
        } else {
            portraitsmallview.backgroundColor = UIColor.gray
            landscapesmallview.isHidden = false
            portraitsmallview.isHidden = true

        }
    }
}
</code>```

Body:
This is part of a much bigger issue I  am having. I have simplified it for you. I want to programmatically change the background color of view on device orientation ?

The following code prints "landcape" and "portrait" in the debugging console every-tome I  rotate the device in the simulator :-

  import UIKit
  class OrientationViewController: UIViewController {
  override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    if UIDevice.current.orientation.isLandscape {
        print("landscape")
    } else {
        print("portrait")
    }
  }
}

Though the following code does nothing :-

   import UIKit
   class AskitViewController: UIViewController {
    override func viewDidLoad() {
    let landscapesmallview = UIView()
    landscapesmallview.backgroundColor = .orange
   let portraitsmallview = UIView()
    portraitsmallview.backgroundColor = .purple
    view.addSubview(landscapesmallview)
    view.addSubview(portraitsmallview)

 func viewWillTransition(to size: CGSize, with coordinator:      UIViewControllerTransitionCoordinator) {
     if UIDevice.current.orientation.isLandscape {
        print("landscape")
    landscapesmallview.translatesAutoresizingMaskIntoConstraints = false
     portraitsmallview.translatesAutoresizingMaskIntoConstraints = true
    } else {
        print("potrait")
  portraitsmallview.translatesAutoresizingMaskIntoConstraints = false
  landscapesmallview.translatesAutoresizingMaskIntoConstraints = true
        }
       }
      }
     }

I am using swift 4.2 and or 5, xcode 10.2
   So, how to programmatically change the background color of view every-time I rotate  the device ?

Please, any of you experts help me ?

edit 1:

I had told you'll in the beginning that it is a part of a bigger issue -

I have buttons inside a view which in potrait mode I want like this -

which is achieved by the following code -

//original potrait mode/////

    import UIKit
    class PotraitViewController: UIViewController {
    override func viewDidLoad() {
    let buttonred = UIButton()
    buttonred.backgroundColor = UIColor.red
    let buttonblue = UIButton()
    buttonblue.backgroundColor = UIColor.blue
    let landscapesmallview = UIView()
    view.addSubview(landscapesmallview)
    landscapesmallview.addSubview(buttonred)
    landscapesmallview.addSubview(buttonblue)
    buttonred.translatesAutoresizingMaskIntoConstraints = false
    buttonblue.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([

        buttonred.topAnchor.constraint(equalTo: view.topAnchor,constant: 200),
        buttonred.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        buttonred.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant:-20),
        buttonred.widthAnchor.constraint(equalToConstant: 50),
        //-------
        buttonblue.topAnchor.constraint(equalTo: buttonred.bottomAnchor,constant: 40),
        buttonblue.leadingAnchor.constraint(equalTo: buttonred.leadingAnchor),
        buttonblue.trailingAnchor.constraint(equalTo:buttonred.trailingAnchor),
        buttonblue.widthAnchor.constraint(equalTo: buttonred.widthAnchor)

        ])
    }

 }

and in landscape mode  I want like this -

which is achieved by the following code -

// original lanscape mode/////

  import UIKit
  class LandscapeViewController: UIViewController {
   override func viewDidLoad() {
    let buttonred = UIButton()
    buttonred.backgroundColor = UIColor.red
    let buttonblue = UIButton()
    buttonblue.backgroundColor = UIColor.blue
    view.addSubview(buttonred)
    view.addSubview(buttonblue)
    buttonred.translatesAutoresizingMaskIntoConstraints = false
    buttonblue.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([

        buttonred.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        buttonred.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant:40),
        buttonred.trailingAnchor.constraint(equalTo: view.centerXAnchor,constant:-20),
        buttonred.widthAnchor.constraint(equalToConstant: 50),

        //-------
        buttonblue.centerYAnchor.constraint(equalTo: buttonred.centerYAnchor),
        buttonblue.leadingAnchor.constraint(equalTo: view.centerXAnchor,constant:40),
        buttonblue.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant:-20),
        buttonblue.widthAnchor.constraint(equalTo:buttonred.widthAnchor)

        ])
     }

  }

So, I tried the following code to achieve by screen rotation i.e. two different  layouts in potrait and landscape views programmatically with the help of the following code:-

    import UIKit

    class NewViewController: UIViewController {
    override func viewDidLoad() {
    let buttonredlandscape = UIButton()
    buttonredlandscape.backgroundColor = UIColor.red
    let buttonbluelandscape = UIButton()
    buttonbluelandscape.backgroundColor = UIColor.blue
    let buttonredportrait = UIButton()
    buttonredportrait.backgroundColor = UIColor.red
    let buttonblueportrait = UIButton()
    buttonblueportrait.backgroundColor = UIColor.blue

    let landscapesmallview = UIView()
    let portraitsmallview = UIView()
    landscapesmallview.backgroundColor = UIColor.gray
    portraitsmallview.backgroundColor = UIColor.purple
    landscapesmallview.frame = view.frame
    portraitsmallview.frame = view.frame
    view.addSubview(landscapesmallview)
    view.addSubview(portraitsmallview)

    landscapesmallview.addSubview(buttonredlandscape)
    landscapesmallview.addSubview(buttonbluelandscape)
    portraitsmallview.addSubview(buttonredportrait)
    portraitsmallview.addSubview(buttonblueportrait)
    buttonredlandscape.translatesAutoresizingMaskIntoConstraints = false
    buttonbluelandscape.translatesAutoresizingMaskIntoConstraints = false
    buttonredportrait.translatesAutoresizingMaskIntoConstraints = false
    buttonblueportrait.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activate([

    buttonredlandscape.centerYAnchor.constraint(equalTo:landscapesmallview.centerYAnchor),
        buttonredlandscape.topAnchor.constraint(equalTo:landscapesmallview.topAnchor,constant:40),
        buttonredlandscape.trailingAnchor.constraint(equalTo: landscapesmallview.centerXAnchor,constant:-20),
        buttonredlandscape.heightAnchor.constraint(equalTo: landscapesmallview.heightAnchor,constant:50),

        buttonbluelandscape.centerYAnchor.constraint(equalTo:buttonredlandscape.centerYAnchor),
        buttonbluelandscape.leadingAnchor.constraint(equalTo: landscapesmallview.centerXAnchor,constant:40),
        buttonbluelandscape.trailingAnchor.constraint(equalTo: landscapesmallview.trailingAnchor,constant:-20),
        buttonbluelandscape.heightAnchor.constraint(equalTo: buttonredlandscape.heightAnchor),

        buttonredportrait.topAnchor.constraint(equalTo: portraitsmallview.topAnchor,constant: 200),
        buttonredportrait.centerXAnchor.constraint(equalTo: portraitsmallview.centerXAnchor),
        buttonredportrait.trailingAnchor.constraint(equalTo: portraitsmallview.trailingAnchor,constant:-20),
        buttonredportrait.widthAnchor.constraint(equalTo: buttonredportrait.widthAnchor),

        buttonblueportrait.topAnchor.constraint(equalTo: buttonredportrait.bottomAnchor,constant: 40),
        buttonblueportrait.leadingAnchor.constraint(equalTo: buttonredportrait.leadingAnchor),
        buttonblueportrait.trailingAnchor.constraint(equalTo:buttonredportrait.trailingAnchor),
        buttonblueportrait.widthAnchor.constraint(equalTo: buttonredportrait.widthAnchor)

        ])

    //-------

    func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        if UIDevice.current.orientation.isLandscape {
            landscapesmallview.translatesAutoresizingMaskIntoConstraints = false
            portraitsmallview.translatesAutoresizingMaskIntoConstraints = true
        } else if UIDevice.current.orientation.isPortrait {
            portraitsmallview.translatesAutoresizingMaskIntoConstraints = false
            landscapesmallview.translatesAutoresizingMaskIntoConstraints = true

         }
      }

    }

  }

which in potrait mode shows -

and which in landscape mode shows -

How to achieve what I want programmatically (see after edit 1) i.e. topmost 2  buttons to rearrange themselves programmatically every-time  the user rotates the device. Its not just the buttons. It can be labels, images, collectionview etc. or just anything. The upshot is that I want to achieve two layouts  in landscape and portrait modes programmatically.

Points to be noted :-

i) I want to use "NSLayoutConstraint.activate" because apple recommends it.

ii) If possible, I do not want to use stackview or containerview,  because there can be many more types of labels, buttons etc, but if there is no other way, then I will use it.

iii) Is my code DRY principle compliant ?

Also, guys, please, I do not deserve negative marks because,  as far as I know, this has not been asked before. I request you to remove negative marks and encourage me.

Body:
i had make to view one for portraitsmallview and one for landscapesmallview
import UIKit

class ViewController: UIViewController {
    var landscapesmallview = UIView()
    var portraitsmallview = UIView()

    override func viewDidLoad() {

    landscapesmallview.frame = CGRect.init(x: 0, y: 0, width: 300, height: 500)
    landscapesmallview.backgroundColor = UIColor.yellow     //give color to the view
    landscapesmallview.center = self.view.center
    self.view.addSubview(landscapesmallview)

    portraitsmallview.frame = CGRect.init(x: 0, y: 0, width: 200, height: 300)
    portraitsmallview.backgroundColor = UIColor.blue     //give color to the view
    portraitsmallview.center = self.view.center
    self.view.addSubview(portraitsmallview)

    landscapesmallview.isHidden = true
    portraitsmallview.isHidden = true
        }
    override func viewWillLayoutSubviews() {
        if UIDevice.current.orientation.isPortrait {
            landscapesmallview.isHidden = true
            portraitsmallview.isHidden = false
        } else {
            landscapesmallview.isHidden = false
            portraitsmallview.isHidden = true

        }
    }
}

and if you need change the backgrandcolor landscapesmallview.backgroundColor and portraitsmallview.backgroundColor

//
//  ViewController.swift
//  test
//
//  Created by Younouss EL OUATI on 5/29/20.
//  Copyright © 2020 Younouss EL OUATI. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    var landscapesmallview = UIView()
    var portraitsmallview = UIView()

    override func viewDidLoad() {

    landscapesmallview.frame = CGRect.init(x: 0, y: 0, width: 300, height: 500)
    landscapesmallview.backgroundColor = UIColor.yellow     //give color to the view
    landscapesmallview.center = self.view.center
    self.view.addSubview(landscapesmallview)

    portraitsmallview.frame = CGRect.init(x: 0, y: 0, width: 200, height: 300)
    portraitsmallview.backgroundColor = UIColor.blue     //give color to the view
    portraitsmallview.center = self.view.center
    self.view.addSubview(portraitsmallview)

    landscapesmallview.isHidden = true
    portraitsmallview.isHidden = true
        }
    override func viewWillLayoutSubviews() {
        if UIDevice.current.orientation.isPortrait {
            landscapesmallview.backgroundColor = UIColor.green
            landscapesmallview.isHidden = true
            portraitsmallview.isHidden = false
        } else {
            portraitsmallview.backgroundColor = UIColor.gray
            landscapesmallview.isHidden = false
            portraitsmallview.isHidden = true

        }
    }
}


问:
PHP / Axios - correctly formatting email object to pass to PHP mailer
On the PHP side, what is the correct syntax to get all the key=>value pairs from an axios object being posted to a simple PHP mailer?

My ojbect:

```<code>let post = {
  message: this.message, // string
  email: this.email, // string
  links: this.links // array of objects { name: item.name, id: item.id }
};
axios.post('/mail.php', JSON.stringify(post)).then(() => { ... });
</code>```

In my mailer I'm doing this:

```<code>$_POST = json_decode(array_keys($_POST)[0], true);

if (isset($_POST['message'])) {
    $body = $_POST['message'];
}
if (isset($_POST['email'])) {
    $email = $_POST['email'];
}
if (isset($_POST['links'])) {
    $links = $_POST['links'];
}

</code>```

But this doesn't get everything... I'm assuming because of the [0] but if I remove the [0] json_decode complains. (I'm not super excellent at PHP yet).

What I would love is for vars to be assigned like this:

```<code>$message = json_decode(array_keys($_POST)[0], true);
$email = json_decode(array_keys($_POST)[1], true);
$links = json_decode(array_keys($_POST)[2], true);
</code>```

But that doesn't work either.

答:
I removed the stringify from the axios post and then in the PHP mailer I used:</p>

```<code>if (isset($_POST)) {
  $data = json_decode(file_get_contents('php://input'), true);
}

if (isset($data['email'])) {
  $to = $data['email'];
}

if (isset($data['message'])) {
  $body = $data['message'];
}

if (isset($data['links'])) {
  $to = $data['links'];
}

</code>```

Body:
On the PHP side, what is the correct syntax to get all the key=>value pairs from an axios object being posted to a simple PHP mailer?

My ojbect:

let post = {
  message: this.message, // string
  email: this.email, // string
  links: this.links // array of objects { name: item.name, id: item.id }
};
axios.post('/mail.php', JSON.stringify(post)).then(() => { ... });

In my mailer I'm doing this:

$_POST = json_decode(array_keys($_POST)[0], true);

if (isset($_POST['message'])) {
    $body = $_POST['message'];
}
if (isset($_POST['email'])) {
    $email = $_POST['email'];
}
if (isset($_POST['links'])) {
    $links = $_POST['links'];
}

But this doesn't get everything... I'm assuming because of the [0] but if I remove the [0] json_decode complains. (I'm not super excellent at PHP yet).

What I would love is for vars to be assigned like this:

$message = json_decode(array_keys($_POST)[0], true);
$email = json_decode(array_keys($_POST)[1], true);
$links = json_decode(array_keys($_POST)[2], true);

But that doesn't work either.

Body:
I removed the stringify from the axios post and then in the PHP mailer I used:

if (isset($_POST)) {
  $data = json_decode(file_get_contents('php://input'), true);
}

if (isset($data['email'])) {
  $to = $data['email'];
}

if (isset($data['message'])) {
  $body = $data['message'];
}

if (isset($data['links'])) {
  $to = $data['links'];
}