问:
How to deserialize a x-www-form-urlencoded encoded string in .NET Core 3.1 or .NET Standard?
How to deserialize a x-www-form-urlencoded encoded string in .NET Core 3.1 or in .NET Standard (C#)?

I'm aware of this question - answer.  However, FormDataCollection does not appear to be available in .NET Core 3.1.  See here.

EDIT: I am being passed this encoded data back by another external system. I am not writing a ASP.NET Core Website/API.

答:
So I never found a neat answer to this question. So I banged out my own rough serializer. Posting here in case anyone gets any use from it. I still welcome a better answer! :-)

using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;

public static class FormUrlEncodedSerializer
{
    public static async Task<string> SerializeAsync(object obj)
    {
        if (obj == null)
            throw new ArgumentNullException(nameof(obj));

        var keyValues = obj.GetPropertiesAsDictionary();

        var formUrlEncodedContent = new FormUrlEncodedContent(keyValues);

        return await formUrlEncodedContent.ReadAsStringAsync();
    }

    public static T Deserialize<T>(string formUrlEncodedText) where T : new()
    {
        if (string.IsNullOrEmpty(formUrlEncodedText))
            throw new ArgumentException("Form URL Encoded text was null or empty.", nameof(formUrlEncodedText));

        var pairs = formUrlEncodedText.Split('&');

        var obj = new T();

        foreach (var pair in pairs)
        {
            var nameValue = pair.Split('=');

            if (HasValue(nameValue))
            {
                obj.SetProperty(nameValue[0], nameValue[1]);
            }
        }

        return obj;
    }

    private static bool HasValue(string[] nameValue)
    {
        return nameValue.Length == 2 && nameValue[1] != string.Empty;
    }
}

public static class ObjectExtensions
{
    public static void SetProperty(this object source, string propertyName, object propertyValue)
    {
        var pi = source.GetProperty(propertyName);

        if (pi != null && pi.CanWrite)
        {
            pi.SetValue(source, propertyValue, null);
        }
    }

    public static PropertyInfo GetProperty(this object source, string propertyName)
    {
        BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance;

        return source.GetType().GetProperty(propertyName, bindingFlags);
    }

    public static IDictionary<string, string> GetPropertiesAsDictionary(this object source)
    {
        var dict = new Dictionary<string, string>();

        if (source == null)
            return dict;

        var properties = source.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);

        foreach (var property in properties)
        {
            var value = property.GetValue(source);

            if (value == null)
                continue;

            dict.Add(property.Name, value.ToString());
        }

        return dict;
    }
}
```

EDIT: Replaced ToKeyValues with GetPropertiesAsDictionary.

Body:
So I never found a neat answer to this question. So I banged out my own rough serializer. Posting here in case anyone gets any use from it. I still welcome a better answer! :-)

using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;

public static class FormUrlEncodedSerializer
{
    public static async Task<string> SerializeAsync(object obj)
    {
        if (obj == null)
            throw new ArgumentNullException(nameof(obj));

        var keyValues = obj.GetPropertiesAsDictionary();

        var formUrlEncodedContent = new FormUrlEncodedContent(keyValues);

        return await formUrlEncodedContent.ReadAsStringAsync();
    }

    public static T Deserialize<T>(string formUrlEncodedText) where T : new()
    {
        if (string.IsNullOrEmpty(formUrlEncodedText))
            throw new ArgumentException("Form URL Encoded text was null or empty.", nameof(formUrlEncodedText));

        var pairs = formUrlEncodedText.Split('&');

        var obj = new T();

        foreach (var pair in pairs)
        {
            var nameValue = pair.Split('=');

            if (HasValue(nameValue))
            {
                obj.SetProperty(nameValue[0], nameValue[1]);
            }
        }

        return obj;
    }

    private static bool HasValue(string[] nameValue)
    {
        return nameValue.Length == 2 && nameValue[1] != string.Empty;
    }
}

public static class ObjectExtensions
{
    public static void SetProperty(this object source, string propertyName, object propertyValue)
    {
        var pi = source.GetProperty(propertyName);

        if (pi != null && pi.CanWrite)
        {
            pi.SetValue(source, propertyValue, null);
        }
    }

    public static PropertyInfo GetProperty(this object source, string propertyName)
    {
        BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance;

        return source.GetType().GetProperty(propertyName, bindingFlags);
    }

    public static IDictionary<string, string> GetPropertiesAsDictionary(this object source)
    {
        var dict = new Dictionary<string, string>();

        if (source == null)
            return dict;

        var properties = source.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);

        foreach (var property in properties)
        {
            var value = property.GetValue(source);

            if (value == null)
                continue;

            dict.Add(property.Name, value.ToString());
        }

        return dict;
    }
}

EDIT: Replaced ToKeyValues with GetPropertiesAsDictionary.


来源: stackexchange

问:
Is there any way to chunk message while sending message into service bus topic in logic app?
I have a logic app and sedning messages to service bus using service bus connector

when a message is more than 1mb i'm getting below error -

```<code>{
  "status": 400,
  "message": "A request has exceeded the maximum message size for 'demo.servicebus.windows.net' Service Bus namespace and 'demo' entity. Validate the content size before retrying.",
  "error": {
    "message": "A request has exceeded the maximum message size for 'demo.servicebus.windows.net' Service Bus namespace and 'demo' entity. Validate the content size before retrying."
  }
}
</code>```

Is there any way to handle such scenarios ?

答:
Suppose you already got the result from the doc I shared:Service Bus Premium and Standard messaging tiers.

These two tiers of Service Bus Messaging are designed to serve different use cases, however, both of them have a limit about the message size.

Premium: Message size up to 1 MB

Standard: Message size up to 256 KB

ContentLicense: CC BY-SA 4.0

Body:
I have a logic app and sedning messages to service bus using service bus connector

when a message is more than 1mb i'm getting below error -

{
  "status": 400,
  "message": "A request has exceeded the maximum message size for 'demo.servicebus.windows.net' Service Bus namespace and 'demo' entity. Validate the content size before retrying.",
  "error": {
    "message": "A request has exceeded the maximum message size for 'demo.servicebus.windows.net' Service Bus namespace and 'demo' entity. Validate the content size before retrying."
  }
}

Is there any way to handle such scenarios ?


问:
Function for converting numeric value into word
Is there any function in progress for converting a numeric value into word or there is another way of doing it?
For ex- 1234 -> one thousand two hundred thirty four.</p>

答:
This will (not too much tests done) up to 9999. After that you will have to expand it to work.</p>

```<code>DEFINE VARIABLE cNum2Words     AS CHARACTER NO-UNDO EXTENT 20 INITIAL ["zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eigteen","nineteen"].
DEFINE VARIABLE cTens          AS CHARACTER NO-UNDO EXTENT 10 INITIAL ["","twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety"].
DEFINE VARIABLE cPostfix       AS CHARACTER NO-UNDO EXTENT 10 INITIAL ["","","hundred","thousand","hundredthousand","million"].

FUNCTION num2word RETURN CHARACTER (INPUT piNum AS INTEGER):

    RETURN cNum2Words[piNum + 1].

END.

FUNCTION num2words RETURNS CHARACTER (INPUT piNum AS INTEGER):

    DEFINE VARIABLE iStep   AS INTEGER NO-UNDO.
    DEFINE VARIABLE cReturn AS CHARACTER NO-UNDO.
    DEFINE VARIABLE iPos    AS INTEGER NO-UNDO.

    IF piNum >= 0 AND piNum <= 19 THEN
        RETURN num2Word(piNum).
    ELSE DO:

        DO iStep = LENGTH(STRING(piNum)) TO 1 BY -1:

            iPos = iPos + 1.

            IF iStep = 1 THEN DO:
                cReturn = cReturn + " " +  num2word(INTEGER(SUBSTRING(STRING(piNum), iPos, 1))).
            END.
            ELSE IF iStep = 2 THEN DO:
                cReturn =  cReturn + " " + cTens[INTEGER(SUBSTRING(STRING(piNum), iPos, 1))].
            END.
            ELSE IF iStep > 2 AND iStep <= 6 THEN DO:
                cReturn = cReturn + " " + num2word(INTEGER(SUBSTRING(STRING(piNum), iPos, 1))) + " " + cPostfix[iStep].
            END.

        END.
    END.
    RETURN creturn.

END.

MESSAGE  num2words(9999) VIEW-AS ALERT-BOX .
</code>```

Body:
This will (not too much tests done) up to 9999. After that you will have to expand it to work.

DEFINE VARIABLE cNum2Words     AS CHARACTER NO-UNDO EXTENT 20 INITIAL ["zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eigteen","nineteen"].
DEFINE VARIABLE cTens          AS CHARACTER NO-UNDO EXTENT 10 INITIAL ["","twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety"].
DEFINE VARIABLE cPostfix       AS CHARACTER NO-UNDO EXTENT 10 INITIAL ["","","hundred","thousand","hundredthousand","million"].

FUNCTION num2word RETURN CHARACTER (INPUT piNum AS INTEGER):

    RETURN cNum2Words[piNum + 1].

END.

FUNCTION num2words RETURNS CHARACTER (INPUT piNum AS INTEGER):

    DEFINE VARIABLE iStep   AS INTEGER NO-UNDO.
    DEFINE VARIABLE cReturn AS CHARACTER NO-UNDO.
    DEFINE VARIABLE iPos    AS INTEGER NO-UNDO.

    IF piNum >= 0 AND piNum <= 19 THEN
        RETURN num2Word(piNum).
    ELSE DO:

        DO iStep = LENGTH(STRING(piNum)) TO 1 BY -1:

            iPos = iPos + 1.

            IF iStep = 1 THEN DO:
                cReturn = cReturn + " " +  num2word(INTEGER(SUBSTRING(STRING(piNum), iPos, 1))).
            END.
            ELSE IF iStep = 2 THEN DO:
                cReturn =  cReturn + " " + cTens[INTEGER(SUBSTRING(STRING(piNum), iPos, 1))].
            END.
            ELSE IF iStep > 2 AND iStep <= 6 THEN DO:
                cReturn = cReturn + " " + num2word(INTEGER(SUBSTRING(STRING(piNum), iPos, 1))) + " " + cPostfix[iStep].
            END.

        END.
    END.
    RETURN creturn.

END.

MESSAGE  num2words(9999) VIEW-AS ALERT-BOX .


问:
running cygwin commands in a windows bat file
am trying to run the cygwin command in a windows batch file,
however, the cygwin command only reaches to the cygwin interactive promt.

my code is as follows in the windows bat file

```<code>@echo off

C:
chdir C:\cygwin\bin

bash --login -i
split -l 1 test.txt
logoff
exit
</code>```

it only reaches to the command interface for cygwin/linux
command prompt reached

答:
When you use bash --login -i, you enter in an interactive bash shell.

What you need is :

```<code>bash -c "cd /path/to/your-test-txt; split -l 1 test.txt"
</code>```

Body:
am trying to run the cygwin command in a windows batch file,
however, the cygwin command only reaches to the cygwin interactive promt.

my code is as follows in the windows bat file

@echo off

C:
chdir C:\cygwin\bin

bash --login -i
split -l 1 test.txt
logoff
exit

it only reaches to the command interface for cygwin/linux
command prompt reached

Body:
When you use bash --login -i, you enter in an interactive bash shell.

What you need is :

bash -c "cd /path/to/your-test-txt; split -l 1 test.txt"


问:
sortn starting at row x
I am using the sortn formula (see below), which works like a charm. However, I want the thirty results showing to start on a predefined row (it is predefined to start on row 1). Is this possible? Basically [n] starting on row x.

```<code>=SORTN(A1:AB9691, 30 , 5, true)
</code>```

Or is there a better way of doing this?

答:
I understand that you want SORTN to return 30 values skipping the n first rows. If my comprehension is correct, then you can use QUERY to reach your goal. Using the OFFSET clause you can skip the firsts n rows, you only have to increase your SORTN results by n.

```<code>=QUERY({YOUR SORTN HERE},"SELECT * OFFSET n")
</code>```

Don't hesitate to ask me further questions if you have doubts.

Title: sortn starting at row x

Body:
I am using the sortn formula (see below), which works like a charm. However, I want the thirty results showing to start on a predefined row (it is predefined to start on row 1). Is this possible? Basically [n] starting on row x.

=SORTN(A1:AB9691, 30 , 5, true)

Or is there a better way of doing this?

Body:
I understand that you want SORTN to return 30 values skipping the n first rows. If my comprehension is correct, then you can use QUERY to reach your goal. Using the OFFSET clause you can skip the firsts n rows, you only have to increase your SORTN results by n.

=QUERY({YOUR SORTN HERE},"SELECT * OFFSET n")

Don't hesitate to ask me further questions if you have doubts.


问:
How to create a UITextField like MFMailComposer has?
I want to create a MFMailComposer like UITextField like when we type an email address it converted into blue round button like shape. I do not want to use Three20's MailComposer. I want to create my own.Any idea how to achieve this? or if there is already a UITextField or whatever control is out there please let me know.

EDIT: I've checked three20's TTCatalog demo. And It has all the things I want except a few like when I type an email address manually it's not converted into the blue button.Also I want to send mail using my own methods because I'm doing encryption of message. And I want to get all the email addresses entered in the To field and I want a Cc/Bcc field like MFMailComposer has.

答: Check out TITokenFieldView - you may be able to use/adapt for your needs</p>

ContentLicense: CC BY-SA 3.0


问:
How to delete one blank row and the following row only if it is not empty
I have a two column file with a structure

```<code>1 2
10 1

10 1
10 3
102 40

102 40
25 5
53 4

53 4
35 6
64 5
456 4

456 4
243 535
435 6
</code>```

So number above and below the blank row are same. But the blank row are not uniform (they are single, double or triple). I want to delete the number just after the each blank row and the blank row just above this number.

My expected output should be like this

```<code>1 2
10 1
10 3
102 40

25 5
53 4
35 6
64 5
456 4

243 535
435 6
</code>```

I have tried to do this:

```<code>sed -e '/pattern/,+1d' input_file
</code>```

You see my pattern is varying and I failed to solve the issue.

答:
This might work for you (GNU sed):

```<code>sed 'N;/^\n\S/d;P;D' file
</code>```

Open a two line window throughout the length of the file.

If the first line of the window is empty and the second is not, delete both lines.

Otherwise, print/delete the first line and repeat.

Body:
I have a two column file with a structure

1 2
10 1

10 1
10 3
102 40

102 40
25 5
53 4

53 4
35 6
64 5
456 4

456 4
243 535
435 6

So number above and below the blank row are same. But the blank row are not uniform (they are single, double or triple). I want to delete the number just after the each blank row and the blank row just above this number.

My expected output should be like this

1 2
10 1
10 3
102 40

25 5
53 4
35 6
64 5
456 4

243 535
435 6

I have tried to do this:

sed -e '/pattern/,+1d' input_file

You see my pattern is varying and I failed to solve the issue.

Body:
This might work for you (GNU sed):

sed 'N;/^\n\S/d;P;D' file

Open a two line window throughout the length of the file.

If the first line of the window is empty and the second is not, delete both lines.

Otherwise, print/delete the first line and repeat.


问:
std::async with non static member functions
I am trying to evaluate a part of my code asynchronously

```<code>#include <stdio.h>
#include <string>
#include <memory>
#include <future>
#include <map>

namespace IG
{
    typedef std::map<uint, std::string> CadDef;

    class FooFoo
    {
        CadDef foo()
        {
            CadDef cdef{};
            cdef[1] = "aa";
            return cdef;
        }
    };
}

int main()
{
    auto ptr = std::make_unique<IG::FooFoo>();
    std::future<IG::CadDef> resFut = std::async(ptr->foo);
    auto res = resFut.get();
    return 0;
}
</code>```

But the code doesn't compile -
(On gcc)

```<code>error: invalid use of non-static member function ‘IG::CadDef IG::FooFoo::foo()’
</code>```

(on msvc -- my main program, from where I abstracted the minimal example)

```<code>error C3867: 'IG::FooFoo::foo': non-standard syntax; use '&' to create a pointer to member
error C2672: 'std::async': no matching overloaded function found
error C2780: 'std::future<_Invoke_traits<void,decay<_Ty>::type,decay<_ArgTypes>::type...>::type> std::async(std::launch,_Fty &&,_ArgTypes &&...)': expects 3 arguments - 1 provided
</code>```

Seems like MSVC is complaining that I have not used ptr->foo() but I am not sure.

What am I doing wrong?

答:
Async takes a function address as an argument, but it the function is a class-member function you have to bind it to the object which can invoke this function.

All functions (including methods) are moved to the code segment of the binary file.
That's why the sizeof(T) equals to sum of sizeof of all class data-members (including a virtual table pointer (vptr) if exists).

class A {void method() }; can be represented as void method(A* a) {}

Knowing all this information you should bind the method with the object

```<code>int main()
{
    auto ptr = std::make_unique<IG::FooFoo>();
    std::future<IG::CadDef> resFut = std::async(&IG::FooFoo::foo, ptr.get());
    auto res = resFut.get();
    return 0;
}
</code>```

Body:
I am trying to evaluate a part of my code asynchronously

#include <stdio.h>
#include <string>
#include <memory>
#include <future>
#include <map>

namespace IG
{
    typedef std::map<uint, std::string> CadDef;

    class FooFoo
    {
        CadDef foo()
        {
            CadDef cdef{};
            cdef[1] = "aa";
            return cdef;
        }
    };
}

int main()
{
    auto ptr = std::make_unique<IG::FooFoo>();
    std::future<IG::CadDef> resFut = std::async(ptr->foo);
    auto res = resFut.get();
    return 0;
}

But the code doesn't compile -
(On gcc)

error: invalid use of non-static member function ‘IG::CadDef IG::FooFoo::foo()’

(on msvc -- my main program, from where I abstracted the minimal example)

error C3867: 'IG::FooFoo::foo': non-standard syntax; use '&' to create a pointer to member
error C2672: 'std::async': no matching overloaded function found
error C2780: 'std::future<_Invoke_traits<void,decay<_Ty>::type,decay<_ArgTypes>::type...>::type> std::async(std::launch,_Fty &&,_ArgTypes &&...)': expects 3 arguments - 1 provided

Seems like MSVC is complaining that I have not used ptr->foo() but I am not sure.

What am I doing wrong?

Body:
Async takes a function address as an argument, but it the function is a class-member function you have to bind it to the object which can invoke this function.

All functions (including methods) are moved to the code segment of the binary file.
That's why the sizeof(T) equals to sum of sizeof of all class data-members (including a virtual table pointer (vptr) if exists).

class A {void method() }; can be represented as void method(A* a) {}

Knowing all this information you should bind the method with the object

int main()
{
    auto ptr = std::make_unique<IG::FooFoo>();
    std::future<IG::CadDef> resFut = std::async(&IG::FooFoo::foo, ptr.get());
    auto res = resFut.get();
    return 0;
}


问:
Iterating through dataframes for creating and filling new data frames
I have the following large dataframes:

```<code>Jan_Feb2019
Mar_Apr2019
May_Jun2019
Jul_Aug2019
Sep_Oct2019
Nov_Dec2019
Jan_Feb2020
Mar_2020
</code>```

And i use the following code to generate other dataframes and fill the columns with the data i want.

```<code>#Jan_Feb2019
Jan_Feb2019_df <- as.data.frame(Jan_Feb2019$reactions$summary$total_count)
colnames(Jan_Feb2019_df)[1] <- "Reactions"
Jan_Feb2019_df$Shares <- Jan_Feb2019$shares$count
Jan_Feb2019_df$Comments <- Jan_Feb2019$comments$summary$total_count
Jan_Feb2019_df$Message <- Jan_Feb2019$message
Jan_Feb2019_df$Likes <- Jan_Feb2019$likes$summary$total_count
Jan_Feb2019_df$CreatedDate <- Jan_Feb2019$created_time
Jan_Feb2019_df$PostID <- Jan_Feb2019$id
Jan_Feb2019_df$Love <- Jan_Feb2019$reacts_love$summary$total_count
Jan_Feb2019_df$Angry <- Jan_Feb2019$reacts_angry$summary$total_count
Jan_Feb2019_df$Sad <- Jan_Feb2019$reacts_sad$summary$total_count
Jan_Feb2019_df$HAHA <- Jan_Feb2019$reacts_haha$summary$total_count
Jan_Feb2019_df$WOW <- Jan_Feb2019$reacts_wow$summary$total_count
Jan_Feb2019_df$CreatedDate <- anytime(Jan_Feb2019_df[,6])
Jan_Feb2019_df$insights.data <- Jan_Feb2019$insights$data

Jan_Feb2019_df <- Jan_Feb2019_df %>%
  unnest(insights.data) %>%
  unnest(values) %>%
  select(Message,Shares,Comments,Reactions,Likes,CreatedDate,PostID,Love,Angry,Sad,HAHA,WOW,name,value) %>%
  pivot_wider(names_from = name, values_from = value)
</code>```

Is there a way to iterate between all the above dataframes, so i won't have to repeat the process 8 times?
Thanks

答:
The code below is untested. I have tried to follow the code in the question, making it general. There are 2 functions.

fillNewDf takes the old object as only argument and creates and fills the new data frame.

makeNewDf takes the old object name as an argument and calls fillNewDf returning its value.

If the objects are in the global environment then makeNewDf argument envir default value is used.

```<code>fillNewDf <- function(X){
  vec <- X[['reactions']][['summary']][['total_count']]
  Y <- data.frame(Reactions = vec)
  Y[['Shares']] <- X[['shares']][['count']]
  Y[['Comments']] <- X[['comments']][['summary']][['total_count']]
  Y[['Message']] <- X[['message']]
  Y[['Likes']] <- X[['likes']][['summary']][['total_count']]
  Y[['CreatedDate']] <- X[['created_time']]
  Y[['PostID']] <- X[['id']]
  Y[['Love']] <- X[['reacts_love']][['summary']][['total_count']]
  Y[['Angry']] <- X[['reacts_angry']][['summary']][['total_count']]
  Y[['Sad']] <- X[['reacts_sad']][['summary']][['total_count']]
  Y[['HAHA']] <- X[['reacts_haha']][['summary']][['total_count']]
  Y[['WOW']] <- X[['reacts_wow']][['summary']][['total_count']]
  Y[['CreatedDate']] <- anytime(Y[, 6])
  Y[['insights.data']] <- X[['insights']][['data']]

  Y %>%
    unnest(insights.data) %>%
    unnest(values) %>%
    select(Message, Shares, Comments, Reactions, Likes, CreatedDate, PostID, Love, Angry, Sad, HAHA, WOW, name, value) %>%
    pivot_wider(names_from = name, values_from = value)
}
makeNewDf <- function(X, envir = .GlobalEnv){
  DF <- get(X, envir = envir)
  filNewDf(DF)
}
</code>```

Now get the names of the objects to be processed with ls() and create a list with the new data frames.

```<code>old_names <- ls(pattern = '\\d{4}$')
new_list <- lapply(old_list, makeNewDf)
names(new_list) <- paste(old_names, "df", sep = "_")
</code>```

If these new data frames are to become objects in the global environment, list2env(new_list) will create them with the same names as the names attribute of new_list.

Body:
I have the following large dataframes:

Jan_Feb2019
Mar_Apr2019
May_Jun2019
Jul_Aug2019
Sep_Oct2019
Nov_Dec2019
Jan_Feb2020
Mar_2020

And i use the following code to generate other dataframes and fill the columns with the data i want.

#Jan_Feb2019
Jan_Feb2019_df <- as.data.frame(Jan_Feb2019$reactions$summary$total_count)
colnames(Jan_Feb2019_df)[1] <- "Reactions"
Jan_Feb2019_df$Shares <- Jan_Feb2019$shares$count
Jan_Feb2019_df$Comments <- Jan_Feb2019$comments$summary$total_count
Jan_Feb2019_df$Message <- Jan_Feb2019$message
Jan_Feb2019_df$Likes <- Jan_Feb2019$likes$summary$total_count
Jan_Feb2019_df$CreatedDate <- Jan_Feb2019$created_time
Jan_Feb2019_df$PostID <- Jan_Feb2019$id
Jan_Feb2019_df$Love <- Jan_Feb2019$reacts_love$summary$total_count
Jan_Feb2019_df$Angry <- Jan_Feb2019$reacts_angry$summary$total_count
Jan_Feb2019_df$Sad <- Jan_Feb2019$reacts_sad$summary$total_count
Jan_Feb2019_df$HAHA <- Jan_Feb2019$reacts_haha$summary$total_count
Jan_Feb2019_df$WOW <- Jan_Feb2019$reacts_wow$summary$total_count
Jan_Feb2019_df$CreatedDate <- anytime(Jan_Feb2019_df[,6])
Jan_Feb2019_df$insights.data <- Jan_Feb2019$insights$data

Jan_Feb2019_df <- Jan_Feb2019_df %>%
  unnest(insights.data) %>%
  unnest(values) %>%
  select(Message,Shares,Comments,Reactions,Likes,CreatedDate,PostID,Love,Angry,Sad,HAHA,WOW,name,value) %>%
  pivot_wider(names_from = name, values_from = value)

Is there a way to iterate between all the above dataframes, so i won't have to repeat the process 8 times?
Thanks

Body:
The code below is untested. I have tried to follow the code in the question, making it general. There are 2 functions.

fillNewDf takes the old object as only argument and creates and fills the new data frame.

makeNewDf takes the old object name as an argument and calls fillNewDf returning its value.

If the objects are in the global environment then makeNewDf argument envir default value is used.

fillNewDf <- function(X){
  vec <- X[['reactions']][['summary']][['total_count']]
  Y <- data.frame(Reactions = vec)
  Y[['Shares']] <- X[['shares']][['count']]
  Y[['Comments']] <- X[['comments']][['summary']][['total_count']]
  Y[['Message']] <- X[['message']]
  Y[['Likes']] <- X[['likes']][['summary']][['total_count']]
  Y[['CreatedDate']] <- X[['created_time']]
  Y[['PostID']] <- X[['id']]
  Y[['Love']] <- X[['reacts_love']][['summary']][['total_count']]
  Y[['Angry']] <- X[['reacts_angry']][['summary']][['total_count']]
  Y[['Sad']] <- X[['reacts_sad']][['summary']][['total_count']]
  Y[['HAHA']] <- X[['reacts_haha']][['summary']][['total_count']]
  Y[['WOW']] <- X[['reacts_wow']][['summary']][['total_count']]
  Y[['CreatedDate']] <- anytime(Y[, 6])
  Y[['insights.data']] <- X[['insights']][['data']]

  Y %>%
    unnest(insights.data) %>%
    unnest(values) %>%
    select(Message, Shares, Comments, Reactions, Likes, CreatedDate, PostID, Love, Angry, Sad, HAHA, WOW, name, value) %>%
    pivot_wider(names_from = name, values_from = value)
}
makeNewDf <- function(X, envir = .GlobalEnv){
  DF <- get(X, envir = envir)
  filNewDf(DF)
}

Now get the names of the objects to be processed with ls() and create a list with the new data frames.

old_names <- ls(pattern = '\\d{4}$')
new_list <- lapply(old_list, makeNewDf)
names(new_list) <- paste(old_names, "df", sep = "_")

If these new data frames are to become objects in the global environment, list2env(new_list) will create them with the same names as the names attribute of new_list.


问:
How to use a custom helper via the "helper" method in Rails 3?
I'm trying to create a custom helper like this:

```<code># app/controllers/my_controller.rb
class MyController < ApplicationController
  helper :my
  def index
    puts foo
  end
end

# app/helpers/my_helper.rb
module MyHelper
  def foo
    "Hello"
  end
end
</code>```

But, I got the following error:

```<code>undefined local variable or method `foo' for #<MyController:0x20e01d0>
</code>```

What am I missing ?

答:
Helpers are accessed from the views, not the controllers. so if you try to put the following inside your index template it should work:

```<code>#my/index.html.erb
<%= foo %>
</code>```

If you do want to access something from the controller, then you should use the include syntax instead of helper, but do not name it like a helper module in that case.

Body:
I'm trying to create a custom helper like this:

# app/controllers/my_controller.rb
class MyController < ApplicationController
  helper :my
  def index
    puts foo
  end
end

# app/helpers/my_helper.rb
module MyHelper
  def foo
    "Hello"
  end
end

But, I got the following error:

undefined local variable or method `foo' for #<MyController:0x20e01d0>

What am I missing ?

Body:
Helpers are accessed from the views, not the controllers. so if you try to put the following inside your index template it should work:

#my/index.html.erb
<%= foo %>

If you do want to access something from the controller, then you should use the include syntax instead of helper, but do not name it like a helper module in that case.


问:
Azure Event Hub : Create Logger - 400 Invalid Hostname
I am trying to create a proof of concept with Azure APIM and am stuck at a 400 invalid hostname error.

I have tried following this example

https://learn.microsoft.com/en-gb/azure/api-management/api-management-howto-log-event-hubs

which leads me to this page

https://learn.microsoft.com/en-us/rest/api/apimanagement/2019-12-01/logger/createorupdate

I have in postman the put command with the following url, edited out the personal details

https://management.azure.com/subscriptions/xxxxx-yyyy-zzz-a4ed-b0b5ddddddd/resourceGroups/xx-Trial/providers/Microsoft.ApiManagement/service/xxx-API-Management-Services/loggers/loggerId?api-version=2019-12-01

This is being sent as a PUT command

This is the body that is also being sent

```<code>{
 "type": "AzureEventHub",
 "description": "xx Poc description",
 "credentials": {
   "name": "apim",
   "connectionString": "Endpoint=sb://xx-poc.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=yyyyyyK/ixxxxxxxxxxxxxxc="
 }
}
</code>```

The response that comes back is

```<code><h2>Bad Request - Invalid Hostname</h2>
<hr>
<p>HTTP Error 400. The request hostname is invalid.</p>
</code>```

I would be grateful if anyone can help me progress this forward as I cannot see what I have missed.

Thanks

答:
After hours of searching I finally stumbled across this url https://www.svenmalvik.com/azure-apim-with-eventhub/ which has resolve my issue. </p>

<p>I had done everything right in terms of setup, but this was the final step that was missing </p>

```<code>$apimCtx = New-AzApiManagementContext -ResourceGroupName "xx-Trial" -ServiceName "xx-API-Management-Services"
$ehConnection = (Get-AzEventHubKey -ResourceGroupName "xx-Trial" -NamespaceName "xx-yyy-zzz-eh-ns" -AuthorizationRuleName "xx-yyy-zzz-eh-auth-rule").PrimaryConnectionString
New-AzApiManagementLogger -Context $apimCtx -LoggerId "simon-logger" -Name "simon-logger" -ConnectionString "$ehConnection;EntityPath=xx-yyy-eh"
</code>```

Body:
I am trying to create a proof of concept with Azure APIM and am stuck at a 400 invalid hostname error.

I have tried following this example

https://learn.microsoft.com/en-gb/azure/api-management/api-management-howto-log-event-hubs

which leads me to this page

https://learn.microsoft.com/en-us/rest/api/apimanagement/2019-12-01/logger/createorupdate

I have in postman the put command with the following url, edited out the personal details

https://management.azure.com/subscriptions/xxxxx-yyyy-zzz-a4ed-b0b5ddddddd/resourceGroups/xx-Trial/providers/Microsoft.ApiManagement/service/xxx-API-Management-Services/loggers/loggerId?api-version=2019-12-01

This is being sent as a PUT command

This is the body that is also being sent

{
 "type": "AzureEventHub",
 "description": "xx Poc description",
 "credentials": {
   "name": "apim",
   "connectionString": "Endpoint=sb://xx-poc.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=yyyyyyK/ixxxxxxxxxxxxxxc="
 }
}

The response that comes back is

Bad Request - Invalid Hostname

HTTP Error 400. The request hostname is invalid.

I would be grateful if anyone can help me progress this forward as I cannot see what I have missed.

Thanks

Body:
After hours of searching I finally stumbled across this url https://www.svenmalvik.com/azure-apim-with-eventhub/ which has resolve my issue.

I had done everything right in terms of setup, but this was the final step that was missing

$apimCtx = New-AzApiManagementContext -ResourceGroupName "xx-Trial" -ServiceName "xx-API-Management-Services"
$ehConnection = (Get-AzEventHubKey -ResourceGroupName "xx-Trial" -NamespaceName "xx-yyy-zzz-eh-ns" -AuthorizationRuleName "xx-yyy-zzz-eh-auth-rule").PrimaryConnectionString
New-AzApiManagementLogger -Context $apimCtx -LoggerId "simon-logger" -Name "simon-logger" -ConnectionString "$ehConnection;EntityPath=xx-yyy-eh"


问:
Sort and merge a list of object
I'm trying to pull out the values from a list of objects and push it into an array and then sort it. The logic seems to be working, I can console log the output, but not return it.

const mergeKLists = function(lists) {
    let result = [];
    for (let i = 0; i < lists.length; i++) {
    for (let node = lists[i]; node; node = node.next) {
        result.push(node.val)
    }
    }
    console.log(result.sort()) // [ 1, 1, 2, 3, 4, 4, 5, 6 ]
    return result.sort() // [ undefined ]
};
```

<p><br /></p>

<p>This is what <code>lists</code> looks like</p>

<pre class="lang-js prettyprint-override"><code>[
  ListNode { val: 1, next: ListNode { val: 4, next: [ListNode] } },
  ListNode { val: 1, next: ListNode { val: 3, next: [ListNode] } },
  ListNode { val: 2, next: ListNode { val: 6, next: null } }
]
</code>```

答:
This works for me (I removed types to make it plain JS).

I've defined the sorting logic for the sort function, as the default could lead to unexpected behavior, given that it sorts them as strings:

```<code>[8, 4, 12].sort() // returns [12, 4, 8]
</code>```

You can see this type of behavior only when using integer numbers bigger than 9.

The way to solve this is to sort defining the specific logic for it:

```<code>[8, 4, 12].sort((x,y) => x - y) // returns [4, 8, 12]
</code>```

In this case, it compares the pair of items and if the result of the operation is < 0, the item is shifted left. Otherwise, if > 0, it's shifted right.

You can check sort() documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

const list = [
  { val: 1, next: { val: 4, next: { val: 15 } } },
  { val: 1, next: { val: 3, next: { val: 4 } } },
  { val: 2, next: { val: 6, next: null } }
];

const mergeKLists = function(lists) {
    let result = [];
    for (let i = 0; i < lists.length; i++) {
      for (let node = lists[i]; node; node = node.next) {
          result.push(node.val)
      }
    }
    return result.sort((a,b) => a - b) // if you use the default sort, 15 would appear before 2
};

const result = mergeKLists(list);

console.log(result);```

Title: Sort and merge a list of object

Body:
I'm trying to pull out the values from a list of objects and push it into an array and then sort it. The logic seems to be working, I can console log the output, but not return it.

const mergeKLists = function(lists) {
    let result = [];
    for (let i = 0; i < lists.length; i++) {
    for (let node = lists[i]; node; node = node.next) {
        result.push(node.val)
    }
    }
    console.log(result.sort()) // [ 1, 1, 2, 3, 4, 4, 5, 6 ]
    return result.sort() // [ undefined ]
};

This is what lists looks like

[
  ListNode { val: 1, next: ListNode { val: 4, next: [ListNode] } },
  ListNode { val: 1, next: ListNode { val: 3, next: [ListNode] } },
  ListNode { val: 2, next: ListNode { val: 6, next: null } }
]

Body:
This works for me (I removed types to make it plain JS).

I've defined the sorting logic for the sort function, as the default could lead to unexpected behavior, given that it sorts them as strings:

[8, 4, 12].sort() // returns [12, 4, 8]

You can see this type of behavior only when using integer numbers bigger than 9.

The way to solve this is to sort defining the specific logic for it:

[8, 4, 12].sort((x,y) => x - y) // returns [4, 8, 12]

In this case, it compares the pair of items and if the result of the operation is < 0, the item is shifted left. Otherwise, if > 0, it's shifted right.

You can check sort() documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

const list = [
  { val: 1, next: { val: 4, next: { val: 15 } } },
  { val: 1, next: { val: 3, next: { val: 4 } } },
  { val: 2, next: { val: 6, next: null } }
];

const mergeKLists = function(lists) {
    let result = [];
    for (let i = 0; i < lists.length; i++) {
      for (let node = lists[i]; node; node = node.next) {
          result.push(node.val)
      }
    }
    return result.sort((a,b) => a - b) // if you use the default sort, 15 would appear before 2
};

const result = mergeKLists(list);

console.log(result);


问:
Error deploying EKS node-group with terraform
I have a problem deploying with Terraform a node group in an EKS cluster. The error looks like one plugin is having problems but I do not know how to resolve it.

If I see the EC2 in the AWS console (web), I can see the instance of the cluster  but I have this error in the cluster.

The error was shown in  my pipeline:

Error: waiting for EKS Node Group (UNIR-API-REST-CLUSTER-DEV:node_sping_boot) creation: NodeCreationFailure: Instances failed to join the kubernetes cluster. Resource IDs: [i-05ed58f8101240dc8]

on EKS.tf line 17, in resource "aws_eks_node_group" "nodes":

17: resource "aws_eks_node_group" "nodes"

2020-06-01T00:03:50.576Z [DEBUG] plugin: plugin process exited: path=/home/ubuntu/.jenkins/workspace/shop_infraestucture_generator_pipline/shop-proyect-dev/.terraform/plugins/linux_amd64/terraform-provider-aws_v2.64.0_x4 pid=13475

2020-06-01T00:03:50.576Z [DEBUG] plugin: plugin exited

And the error is printed in AWS console:

Link

This is the code in  Terraform  I use to create my project:

EKS.tf for creating the cluster and de nodes

```<code>resource "aws_eks_cluster" "CLUSTER" {
  name     = "UNIR-API-REST-CLUSTER-${var.SUFFIX}"
  role_arn = "${aws_iam_role.eks_cluster_role.arn}"
  vpc_config {
    subnet_ids = [
      "${aws_subnet.unir_subnet_cluster_1.id}","${aws_subnet.unir_subnet_cluster_2.id}"
    ]
  }
  depends_on = [
    "aws_iam_role_policy_attachment.AmazonEKSWorkerNodePolicy",
    "aws_iam_role_policy_attachment.AmazonEKS_CNI_Policy",
    "aws_iam_role_policy_attachment.AmazonEC2ContainerRegistryReadOnly",
  ]
}

resource "aws_eks_node_group" "nodes" {
  cluster_name    = "${aws_eks_cluster.CLUSTER.name}"
  node_group_name = "node_sping_boot"
  node_role_arn   = "${aws_iam_role.eks_nodes_role.arn}"
  subnet_ids      = [
      "${aws_subnet.unir_subnet_cluster_1.id}","${aws_subnet.unir_subnet_cluster_2.id}"
  ]
  scaling_config {
    desired_size = 1
    max_size     = 5
    min_size     = 1
  }
# instance_types is mediumt3 by default
# Ensure that IAM Role permissions are created before and deleted after EKS Node Group handling.
# Otherwise, EKS will not be able to properly delete EC2 Instances and Elastic Network Interfaces.
  depends_on = [
    "aws_iam_role_policy_attachment.AmazonEKSWorkerNodePolicy",
    "aws_iam_role_policy_attachment.AmazonEKS_CNI_Policy",
    "aws_iam_role_policy_attachment.AmazonEC2ContainerRegistryReadOnly",
  ]
}

output "eks_cluster_endpoint" {
  value = "${aws_eks_cluster.CLUSTER.endpoint}"
}

output "eks_cluster_certificat_authority" {
    value = "${aws_eks_cluster.CLUSTER.certificate_authority}"
}
</code>```

securityAndGroups.tf

```<code>resource "aws_iam_role" "eks_cluster_role" {
  name = "eks-cluster-${var.SUFFIX}"

  assume_role_policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "eks.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
POLICY
}

resource "aws_iam_role" "eks_nodes_role" {
  name = "eks-node-${var.SUFFIX}"

  assume_role_policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
POLICY
}

resource "aws_iam_role_policy_attachment" "AmazonEKSClusterPolicy" {
  policy_arn = "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy"
  role       = "${aws_iam_role.eks_cluster_role.name}"
}

resource "aws_iam_role_policy_attachment" "AmazonEKSServicePolicy" {
  policy_arn = "arn:aws:iam::aws:policy/AmazonEKSServicePolicy"
  role       = "${aws_iam_role.eks_cluster_role.name}"
}

resource "aws_iam_role_policy_attachment" "AmazonEKSWorkerNodePolicy" {
  policy_arn = "arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy"
  role       = "${aws_iam_role.eks_nodes_role.name}"
}

resource "aws_iam_role_policy_attachment" "AmazonEKS_CNI_Policy" {
  policy_arn = "arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy"
  role       = "${aws_iam_role.eks_nodes_role.name}"
}

resource "aws_iam_role_policy_attachment" "AmazonEC2ContainerRegistryReadOnly" {
  policy_arn = "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly"
  role       = "${aws_iam_role.eks_nodes_role.name}"
}
</code>```

VPCAndRouting.tf to create my routing, VPC, and Subnets

```<code>resource "aws_vpc" "unir_shop_vpc_dev" {
  cidr_block = "${var.NET_CIDR_BLOCK}"
  enable_dns_hostnames = true
  enable_dns_support = true
  tags = {
    Name = "UNIR-VPC-SHOP-${var.SUFFIX}"
    Environment = "${var.SUFFIX}"
  }
}
resource "aws_route_table" "route" {
  vpc_id = "${aws_vpc.unir_shop_vpc_dev.id}"
  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = "${aws_internet_gateway.unir_gat_shop_dev.id}"
  }
  tags = {
    Name = "UNIR-RoutePublic-${var.SUFFIX}"
    Environment = "${var.SUFFIX}"
  }
}

data "aws_availability_zones" "available" {
  state = "available"
}
resource "aws_subnet" "unir_subnet_aplications" {
  vpc_id = "${aws_vpc.unir_shop_vpc_dev.id}"
  cidr_block = "${var.SUBNET_CIDR_APLICATIONS}"
  availability_zone = "${var.ZONE_SUB}"
  depends_on = ["aws_internet_gateway.unir_gat_shop_dev"]
  map_public_ip_on_launch = true
  tags = {
    Name = "UNIR-SUBNET-APLICATIONS-${var.SUFFIX}"
    Environment = "${var.SUFFIX}"
  }
}

resource "aws_subnet" "unir_subnet_cluster_1" {
  vpc_id = "${aws_vpc.unir_shop_vpc_dev.id}"
  cidr_block = "${var.SUBNET_CIDR_CLUSTER_1}"
  map_public_ip_on_launch = true
  availability_zone = "${var.ZONE_SUB_CLUSTER_2}"
  tags = {
    "kubernetes.io/cluster/UNIR-API-REST-CLUSTER-${var.SUFFIX}" = "shared"
  }
}

resource "aws_subnet" "unir_subnet_cluster_2" {
  vpc_id = "${aws_vpc.unir_shop_vpc_dev.id}"
  cidr_block = "${var.SUBNET_CIDR_CLUSTER_2}"
  availability_zone = "${var.ZONE_SUB_CLUSTER_1}"
  map_public_ip_on_launch = true
  tags = {
    "kubernetes.io/cluster/UNIR-API-REST-CLUSTER-${var.SUFFIX}" = "shared"
  }

}

resource "aws_internet_gateway" "unir_gat_shop_dev" {
  vpc_id = "${aws_vpc.unir_shop_vpc_dev.id}"
  tags = {
    Environment = "${var.SUFFIX}"
    Name = "UNIR-publicGateway-${var.SUFFIX}"
  }
}
</code>```

My variables:

```<code>SUFFIX="DEV"
ZONE="eu-west-1"
TERRAFORM_USER_ID=
TERRAFORM_USER_PASS=
ZONE_SUB="eu-west-1b"
ZONE_SUB_CLUSTER_1="eu-west-1a"
ZONE_SUB_CLUSTER_2="eu-west-1c"
NET_CIDR_BLOCK="172.15.0.0/24"
SUBNET_CIDR_APLICATIONS="172.15.0.0/27"
SUBNET_CIDR_CLUSTER_1="172.15.0.32/27"
SUBNET_CIDR_CLUSTER_2="172.15.0.64/27"
SUBNET_CIDR_CLUSTER_3="172.15.0.128/27"
SUBNET_CIDR_CLUSTER_4="172.15.0.160/27"
SUBNET_CIDR_CLUSTER_5="172.15.0.192/27"
SUBNET_CIDR_CLUSTER_6="172.15.0.224/27"
MONGO_SSH_KEY=
KIBANA_SSH_KEY=
CLUSTER_SSH_KEY=
</code>```

Will be more logs necesary?

答:
According to the AWS documentation:

If you receive the error "Instances failed to join the kubernetes
  cluster" in the AWS Management Console, ensure that either the
  cluster's private endpoint access is enabled, or that you have
  correctly configured CIDR blocks for public endpoint access. For more
  information, see Amazon EKS cluster endpoint access control.

I noticed that you are switching the availability zones for your subnets:

```<code>resource "aws_subnet" "unir_subnet_cluster_1" {
  vpc_id = "${aws_vpc.unir_shop_vpc_dev.id}"
  cidr_block = "${var.SUBNET_CIDR_CLUSTER_1}"
  map_public_ip_on_launch = true
  availability_zone = "${var.ZONE_SUB_CLUSTER_2}"
</code>```

You have assigned var.ZONE_SUB_CLUSTER_2 to unir_subnet_cluster_1 and var.ZONE_SUB_CLUSTER_1 to unir_subnet_cluster_2. Maybe this could be a cause for the misconfiguration.

Body:
I have a problem deploying with Terraform a node group in an EKS cluster. The error looks like one plugin is having problems but I do not know how to resolve it.

If I see the EC2 in the AWS console (web), I can see the instance of the cluster  but I have this error in the cluster.

The error was shown in  my pipeline:

Error: waiting for EKS Node Group (UNIR-API-REST-CLUSTER-DEV:node_sping_boot) creation: NodeCreationFailure: Instances failed to join the kubernetes cluster. Resource IDs: [i-05ed58f8101240dc8]

on EKS.tf line 17, in resource "aws_eks_node_group" "nodes":

17: resource "aws_eks_node_group" "nodes"

2020-06-01T00:03:50.576Z [DEBUG] plugin: plugin process exited: path=/home/ubuntu/.jenkins/workspace/shop_infraestucture_generator_pipline/shop-proyect-dev/.terraform/plugins/linux_amd64/terraform-provider-aws_v2.64.0_x4 pid=13475

2020-06-01T00:03:50.576Z [DEBUG] plugin: plugin exited

And the error is printed in AWS console:

Link

This is the code in  Terraform  I use to create my project:

EKS.tf for creating the cluster and de nodes

resource "aws_eks_cluster" "CLUSTER" {
  name     = "UNIR-API-REST-CLUSTER-${var.SUFFIX}"
  role_arn = "${aws_iam_role.eks_cluster_role.arn}"
  vpc_config {
    subnet_ids = [
      "${aws_subnet.unir_subnet_cluster_1.id}","${aws_subnet.unir_subnet_cluster_2.id}"
    ]
  }
  depends_on = [
    "aws_iam_role_policy_attachment.AmazonEKSWorkerNodePolicy",
    "aws_iam_role_policy_attachment.AmazonEKS_CNI_Policy",
    "aws_iam_role_policy_attachment.AmazonEC2ContainerRegistryReadOnly",
  ]
}

resource "aws_eks_node_group" "nodes" {
  cluster_name    = "${aws_eks_cluster.CLUSTER.name}"
  node_group_name = "node_sping_boot"
  node_role_arn   = "${aws_iam_role.eks_nodes_role.arn}"
  subnet_ids      = [
      "${aws_subnet.unir_subnet_cluster_1.id}","${aws_subnet.unir_subnet_cluster_2.id}"
  ]
  scaling_config {
    desired_size = 1
    max_size     = 5
    min_size     = 1
  }
# instance_types is mediumt3 by default
# Ensure that IAM Role permissions are created before and deleted after EKS Node Group handling.
# Otherwise, EKS will not be able to properly delete EC2 Instances and Elastic Network Interfaces.
  depends_on = [
    "aws_iam_role_policy_attachment.AmazonEKSWorkerNodePolicy",
    "aws_iam_role_policy_attachment.AmazonEKS_CNI_Policy",
    "aws_iam_role_policy_attachment.AmazonEC2ContainerRegistryReadOnly",
  ]
}

output "eks_cluster_endpoint" {
  value = "${aws_eks_cluster.CLUSTER.endpoint}"
}

output "eks_cluster_certificat_authority" {
    value = "${aws_eks_cluster.CLUSTER.certificate_authority}"
}

securityAndGroups.tf

resource "aws_iam_role" "eks_cluster_role" {
  name = "eks-cluster-${var.SUFFIX}"

  assume_role_policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "eks.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
POLICY
}

resource "aws_iam_role" "eks_nodes_role" {
  name = "eks-node-${var.SUFFIX}"

  assume_role_policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
POLICY
}

resource "aws_iam_role_policy_attachment" "AmazonEKSClusterPolicy" {
  policy_arn = "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy"
  role       = "${aws_iam_role.eks_cluster_role.name}"
}

resource "aws_iam_role_policy_attachment" "AmazonEKSServicePolicy" {
  policy_arn = "arn:aws:iam::aws:policy/AmazonEKSServicePolicy"
  role       = "${aws_iam_role.eks_cluster_role.name}"
}

resource "aws_iam_role_policy_attachment" "AmazonEKSWorkerNodePolicy" {
  policy_arn = "arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy"
  role       = "${aws_iam_role.eks_nodes_role.name}"
}

resource "aws_iam_role_policy_attachment" "AmazonEKS_CNI_Policy" {
  policy_arn = "arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy"
  role       = "${aws_iam_role.eks_nodes_role.name}"
}

resource "aws_iam_role_policy_attachment" "AmazonEC2ContainerRegistryReadOnly" {
  policy_arn = "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly"
  role       = "${aws_iam_role.eks_nodes_role.name}"
}

VPCAndRouting.tf to create my routing, VPC, and Subnets

resource "aws_vpc" "unir_shop_vpc_dev" {
  cidr_block = "${var.NET_CIDR_BLOCK}"
  enable_dns_hostnames = true
  enable_dns_support = true
  tags = {
    Name = "UNIR-VPC-SHOP-${var.SUFFIX}"
    Environment = "${var.SUFFIX}"
  }
}
resource "aws_route_table" "route" {
  vpc_id = "${aws_vpc.unir_shop_vpc_dev.id}"
  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = "${aws_internet_gateway.unir_gat_shop_dev.id}"
  }
  tags = {
    Name = "UNIR-RoutePublic-${var.SUFFIX}"
    Environment = "${var.SUFFIX}"
  }
}

data "aws_availability_zones" "available" {
  state = "available"
}
resource "aws_subnet" "unir_subnet_aplications" {
  vpc_id = "${aws_vpc.unir_shop_vpc_dev.id}"
  cidr_block = "${var.SUBNET_CIDR_APLICATIONS}"
  availability_zone = "${var.ZONE_SUB}"
  depends_on = ["aws_internet_gateway.unir_gat_shop_dev"]
  map_public_ip_on_launch = true
  tags = {
    Name = "UNIR-SUBNET-APLICATIONS-${var.SUFFIX}"
    Environment = "${var.SUFFIX}"
  }
}

resource "aws_subnet" "unir_subnet_cluster_1" {
  vpc_id = "${aws_vpc.unir_shop_vpc_dev.id}"
  cidr_block = "${var.SUBNET_CIDR_CLUSTER_1}"
  map_public_ip_on_launch = true
  availability_zone = "${var.ZONE_SUB_CLUSTER_2}"
  tags = {
    "kubernetes.io/cluster/UNIR-API-REST-CLUSTER-${var.SUFFIX}" = "shared"
  }
}

resource "aws_subnet" "unir_subnet_cluster_2" {
  vpc_id = "${aws_vpc.unir_shop_vpc_dev.id}"
  cidr_block = "${var.SUBNET_CIDR_CLUSTER_2}"
  availability_zone = "${var.ZONE_SUB_CLUSTER_1}"
  map_public_ip_on_launch = true
  tags = {
    "kubernetes.io/cluster/UNIR-API-REST-CLUSTER-${var.SUFFIX}" = "shared"
  }

}

resource "aws_internet_gateway" "unir_gat_shop_dev" {
  vpc_id = "${aws_vpc.unir_shop_vpc_dev.id}"
  tags = {
    Environment = "${var.SUFFIX}"
    Name = "UNIR-publicGateway-${var.SUFFIX}"
  }
}

My variables:

SUFFIX="DEV"
ZONE="eu-west-1"
TERRAFORM_USER_ID=
TERRAFORM_USER_PASS=
ZONE_SUB="eu-west-1b"
ZONE_SUB_CLUSTER_1="eu-west-1a"
ZONE_SUB_CLUSTER_2="eu-west-1c"
NET_CIDR_BLOCK="172.15.0.0/24"
SUBNET_CIDR_APLICATIONS="172.15.0.0/27"
SUBNET_CIDR_CLUSTER_1="172.15.0.32/27"
SUBNET_CIDR_CLUSTER_2="172.15.0.64/27"
SUBNET_CIDR_CLUSTER_3="172.15.0.128/27"
SUBNET_CIDR_CLUSTER_4="172.15.0.160/27"
SUBNET_CIDR_CLUSTER_5="172.15.0.192/27"
SUBNET_CIDR_CLUSTER_6="172.15.0.224/27"
MONGO_SSH_KEY=
KIBANA_SSH_KEY=
CLUSTER_SSH_KEY=

Will be more logs necesary?

Body:
According to the AWS documentation:

If you receive the error "Instances failed to join the kubernetes
  cluster" in the AWS Management Console, ensure that either the
  cluster's private endpoint access is enabled, or that you have
  correctly configured CIDR blocks for public endpoint access. For more
  information, see Amazon EKS cluster endpoint access control.

I noticed that you are switching the availability zones for your subnets:

resource "aws_subnet" "unir_subnet_cluster_1" {
  vpc_id = "${aws_vpc.unir_shop_vpc_dev.id}"
  cidr_block = "${var.SUBNET_CIDR_CLUSTER_1}"
  map_public_ip_on_launch = true
  availability_zone = "${var.ZONE_SUB_CLUSTER_2}"

You have assigned var.ZONE_SUB_CLUSTER_2 to unir_subnet_cluster_1 and var.ZONE_SUB_CLUSTER_1 to unir_subnet_cluster_2. Maybe this could be a cause for the misconfiguration.


问:
Most portable video codec for the web?
I am looking for a method to embed videos in web pages without using a plugin like Flash or Silverlight. Ideally, I would be able to <embed src="movie.ext"> and expect this to work in most browsers.

I'm aiming to encode videos to a format that works across IE7 and later, Chrome and Firefox. But I need to know which codec is the most portable.

Unfortunately needing to support IE7 rules out HTML5 video support.

答:
H.264 and WebM is what you need.

H.264 is supported in Safari and IE (these also refuse to include WebM support), WebM is supported by alternative browsers Chrome (of course), Firefox and Opera.

I recommend using video tag first, then as a fallback option you can include a Flash player, which will play either version (H.264 support is already included, WebM support will be soon).

If you want to include 3rd party code, there is a comparison of "player" components here.

Title: Most portable video codec for the web?


问:
Add margins to multi-way tables in R
I have the following code in R to build a three-way contingency table:

```<code>txt="   death_p yes no
v_race  d_race
white   white   53  414
black   11  37
black   white   0   16
black   4   139"

mytable = as.table(read.ftable(textConnection(txt)))
mytable = addmargins(mytable, margin=c(1))
</code>```

It prints correctly

```<code>             death_p yes  no
v_race d_race
white  white           53 414
       black           11  37
black  white            0  16
       black            4 139
Sum    white           53 430
       black           15 176
</code>```

I'd like to add a "percentage_yes" after the column "no" preserving the structure of the table.

```<code>                 death_p yes  no  %yes
v_race d_race
white  white             53   414  0.11
       black             11   37   0.00
black  white             0    16   0.11
       black             4    139  0.23
Sum    white             53   430  0.28
       black             15   176  0.79
</code>```

I've tried with

```<code>subset(as.data.frame(prop.table(mytable, c(1,2))), death_p=="yes", select=c("Freq"))
</code>```

but I don't know how to add this new column to the table using Abind (from DescTools). I don't know if there is possibly a better way to accomplish this.
Thanks in advance for your help.

答:
For those who might be interested, I managed to do this by defining a function to calculate the percentage and then pass it to addmargins.

```<code>p_yes = function(x) x[1]/sum(x)
mytable = addmargins(mytable, margin=c(3), FUN = list(p_yes))
</code>```

It gives

```<code>               death_p   yes     no     %yes
v_race d_race
white  white             53.00   414.00  0.11
       black             11.00   37.00   0.00
black  white             0.00    16.00   0.11
       black             4.00    139.00  0.23
Sum    white             53.00   430.00  0.28
       black             15.00   176.00  0.79
</code>```

Title: Add margins to multi-way tables in R

Body:
I have the following code in R to build a three-way contingency table:

txt="   death_p yes no
v_race  d_race
white   white   53  414
black   11  37
black   white   0   16
black   4   139"

mytable = as.table(read.ftable(textConnection(txt)))
mytable = addmargins(mytable, margin=c(1))

It prints correctly

             death_p yes  no
v_race d_race
white  white           53 414
       black           11  37
black  white            0  16
       black            4 139
Sum    white           53 430
       black           15 176

I'd like to add a "percentage_yes" after the column "no" preserving the structure of the table.

                 death_p yes  no  %yes
v_race d_race
white  white             53   414  0.11
       black             11   37   0.00
black  white             0    16   0.11
       black             4    139  0.23
Sum    white             53   430  0.28
       black             15   176  0.79

I've tried with

subset(as.data.frame(prop.table(mytable, c(1,2))), death_p=="yes", select=c("Freq"))

but I don't know how to add this new column to the table using Abind (from DescTools). I don't know if there is possibly a better way to accomplish this.
Thanks in advance for your help.

Body:
For those who might be interested, I managed to do this by defining a function to calculate the percentage and then pass it to addmargins.

p_yes = function(x) x[1]/sum(x)
mytable = addmargins(mytable, margin=c(3), FUN = list(p_yes))

It gives

               death_p   yes     no     %yes
v_race d_race
white  white             53.00   414.00  0.11
       black             11.00   37.00   0.00
black  white             0.00    16.00   0.11
       black             4.00    139.00  0.23
Sum    white             53.00   430.00  0.28
       black             15.00   176.00  0.79


问:
How to generate the html form data in the qr code?
I have searched many way in the online to find how to generate the html form data become qr code, but I can't get the suitable result for me. Hope anyone can share the guideline or tutorial for me how to generate the html form data become qr code.

This is my example situation:

I have a form to save the data in the table, after that in the table qr code button when I've clicked, it will show me the qr code picture. If I've scanned the qr code, the content will show me in the phone what I've selected .

For example, I want the expected result like below the picture after I've scan the qr code and see the selected result on my phone:

Hope someone can guide me or give the logic for me to solve my problem. Thanks.

答:
Please have a look at the answer below.
if you use JS and Jquery it can be done.
Link: Generating a Simple QR-Code with just HTML</p>


问:
Why I am unable to change the QR Code's size in iText7?
How to change QR Code size?

```<code>            using (iText.Kernel.Pdf.PdfReader _pdf_reader =
                new iText.Kernel.Pdf.PdfReader("tmp/example.pdf"))
            {
                using (iText.Kernel.Pdf.PdfDocument pdfDoc = new iText.Kernel.Pdf.PdfDocument(_pdf_reader, new iText.Kernel.Pdf.PdfWriter("tmp/output.pdf").SetSmartMode(true)))
                {
                    BarcodeQRCode qrc = new BarcodeQRCode("https://google.com");

                    PdfFormXObject xObject = qrc.CreateFormXObject(ColorConstants.BLACK, pdfDoc);

                    float _w = pdfDoc.GetPage(1).GetPageSize().GetWidth();
                    float _h = pdfDoc.GetPage(1).GetPageSize().GetHeight();
                    PdfCanvas canvas = new PdfCanvas(pdfDoc.GetPage(1));
                    canvas.SaveState();
                    canvas.SetFillColor(ColorConstants.LIGHT_GRAY);
                    //canvas.Rectangle(_w - 90, _h - 90, 100, 100);
                    canvas.Fill();
                    canvas.RestoreState();
                    canvas.AddXObject(xObject, _w - qrc.GetBarcodeSize().GetWidth(), _h - qrc.GetBarcodeSize().GetHeight());
                }
            }
</code>```

I try:

```<code> qrc.GetBarcodeSize().GetHeight();
 qrc.GetBarcodeSize().GetWidth();
</code>```

it returns 33

I try to set Height & Width to 100 like below:

```<code> qrc.GetBarcodeSize().SetHeight(100);
 qrc.GetBarcodeSize().SetWidth(100);
</code>```

and then check the size again, but it keeps returning 33, is it a bug? or Did I miss something?

please help

thanks
Don

答:
I try to set Height & Width to 100 like below:

Actually, you can`t change the QrCode side this way.
In fact, QRcode is an n*n grid where n depends on some parameters as a QR code version and the error correction level.
When generating, iText uses the smallest version that can fit the content. This is version 4 (33*33) in your case.

The easiest way to change the size of QrCode in a document is by using the version of the createFormXObject method which accepts the moduleSide parameter.

```<code>float moduleSize = 100/qrc.GetBarcodeSize().GetHeight();
qrc.createFormXObject(foreground, moduleSize, document)
</code>```

Module size here is size of the barcode`s grid cell (1 by default).

Body:
How to change QR Code size?

            using (iText.Kernel.Pdf.PdfReader _pdf_reader =
                new iText.Kernel.Pdf.PdfReader("tmp/example.pdf"))
            {
                using (iText.Kernel.Pdf.PdfDocument pdfDoc = new iText.Kernel.Pdf.PdfDocument(_pdf_reader, new iText.Kernel.Pdf.PdfWriter("tmp/output.pdf").SetSmartMode(true)))
                {
                    BarcodeQRCode qrc = new BarcodeQRCode("https://google.com");

                    PdfFormXObject xObject = qrc.CreateFormXObject(ColorConstants.BLACK, pdfDoc);

                    float _w = pdfDoc.GetPage(1).GetPageSize().GetWidth();
                    float _h = pdfDoc.GetPage(1).GetPageSize().GetHeight();
                    PdfCanvas canvas = new PdfCanvas(pdfDoc.GetPage(1));
                    canvas.SaveState();
                    canvas.SetFillColor(ColorConstants.LIGHT_GRAY);
                    //canvas.Rectangle(_w - 90, _h - 90, 100, 100);
                    canvas.Fill();
                    canvas.RestoreState();
                    canvas.AddXObject(xObject, _w - qrc.GetBarcodeSize().GetWidth(), _h - qrc.GetBarcodeSize().GetHeight());
                }
            }

I try:

 qrc.GetBarcodeSize().GetHeight();
 qrc.GetBarcodeSize().GetWidth();

it returns 33

I try to set Height & Width to 100 like below:

 qrc.GetBarcodeSize().SetHeight(100);
 qrc.GetBarcodeSize().SetWidth(100);

and then check the size again, but it keeps returning 33, is it a bug? or Did I miss something?

please help

thanks
Don

Body:
I try to set Height & Width to 100 like below:

Actually, you can`t change the QrCode side this way.
In fact, QRcode is an n*n grid where n depends on some parameters as a QR code version and the error correction level.
When generating, iText uses the smallest version that can fit the content. This is version 4 (33*33) in your case.

The easiest way to change the size of QrCode in a document is by using the version of the createFormXObject method which accepts the moduleSide parameter.

float moduleSize = 100/qrc.GetBarcodeSize().GetHeight();
qrc.createFormXObject(foreground, moduleSize, document)

Module size here is size of the barcode`s grid cell (1 by default).


问:
Is un-initialized integer always default to 0 in c?
I'm reading source code of nginx and find it's not initializing many of the numerical variables, including ngx_int_t ngx_last_process;,here ngx_int_t defined as long int

```<code>#if 0
    ngx_last_process = 0;
#endif
</code>```

So here @Igor Sysoev think it unnecessary to do the initialization?

But in the programe it's assuming the default value is 0:

```<code>    for (s = 0; s < ngx_last_process; s++) {
        if (ngx_processes[s].pid == -1) {
            break;
        }
    }
</code>```

Is it guranteed that un-initialized variable will have 0 value in c at all?

答:
Variables declared (as int)at file scope are initialized to 0.

Example

```<code>int i;
int main()
{
   int x;
   printf("%d",i); // prints 0
   printf("%d",x); // prints some unspecified value
}
</code>```

Is it guranteed that un-initialized variable will have 0 value in c at all?

Nopes! That doesn't hold for variables declared at function scope.

Body:
I'm reading source code of nginx and find it's not initializing many of the numerical variables, including ngx_int_t ngx_last_process;,here ngx_int_t defined as long int

#if 0
    ngx_last_process = 0;
#endif

So here @Igor Sysoev think it unnecessary to do the initialization?

But in the programe it's assuming the default value is 0:

    for (s = 0; s < ngx_last_process; s++) {
        if (ngx_processes[s].pid == -1) {
            break;
        }
    }

Is it guranteed that un-initialized variable will have 0 value in c at all?

Body:
Variables declared (as int)at file scope are initialized to 0.

Example

int i;
int main()
{
   int x;
   printf("%d",i); // prints 0
   printf("%d",x); // prints some unspecified value
}

Is it guranteed that un-initialized variable will have 0 value in c at all?

Nopes! That doesn't hold for variables declared at function scope.


问:
rename command for replacing text in filename from a certain point (character), but only up to, and maintaining the file extension
I've got a ton of files as follows

```<code>audiofile_drums_1-ktpcwybsh5c.wav
soundsample_drums_2-fghlkjy57sa.wav
noise_snippet_guitar_5-mxjtgqta3o1.wav
louder_flute_9-mdlsiqpfj6c.wav
</code>```

I want to remove everything between and including the "-" and the .wav file extension, to be left with

```<code>audiofile_drums_1.wav
soundsample_drums_2.wav
noise_snippet_guitar_5.wav
louder_flute_9.wav
</code>```

I've tried to do delete everything following and including the character "-" using

```<code>rename 's/-.*//' *
</code>```

Which gives me

```<code>audiofile_drums_1
soundsample_drums_2
noise_snippet_guitar_5
louder_flute_9
</code>```

And for lack of finding an easy way to rename all the files again, adding .wav the extension, I am hoping there is a slicker way to do this in one nifty command in one stage instead of 2.

Any suggestions?

Thanks

答:
You can use rename 's/-[^\.]*\.wav$/\.wav/' *

The first part -[^\.]*\.wav$ searchs for a - followed by n chars that are not . followed by .wav and the end of filename. The end of filename and .wav is not strictly needed but it helps avoid renaming files you don't want to rename.

The /\.wav/ preserves the extension.

Please not that rename is not a standard utility, and is part of perl, so rename may not be available on every linux system.

Body:
I've got a ton of files as follows

audiofile_drums_1-ktpcwybsh5c.wav
soundsample_drums_2-fghlkjy57sa.wav
noise_snippet_guitar_5-mxjtgqta3o1.wav
louder_flute_9-mdlsiqpfj6c.wav

I want to remove everything between and including the "-" and the .wav file extension, to be left with

audiofile_drums_1.wav
soundsample_drums_2.wav
noise_snippet_guitar_5.wav
louder_flute_9.wav

I've tried to do delete everything following and including the character "-" using

rename 's/-.*//' *

Which gives me

audiofile_drums_1
soundsample_drums_2
noise_snippet_guitar_5
louder_flute_9

And for lack of finding an easy way to rename all the files again, adding .wav the extension, I am hoping there is a slicker way to do this in one nifty command in one stage instead of 2.

Any suggestions?

Thanks


问:
Android navigation component: how save fragment state
I use bottomNavigationView and navigation component. Please tell me how I don't destroy the fragment after switching to another tab and return to the old one? For example I have three tabs - A, B, C. My start tab is A. After I navigate to B, then return A. When I return to tab A, I do not want it to be re-created. How do it? Thanks</p>

答:
In case you can deal with destroying fragment, but want to save ViewModel, you can scope it into the Navigation Graph:

```<code>private val viewModel: FavouritesViewModel by
    navGraphViewModels(R.id.mobile_navigation) {
        viewModelFactory
    }
</code>```

Read more here

EDIT

As @SpiralDev noted, using Hilt simplifies a bit:

```<code>private val viewModel: MainViewModel by
    navGraphViewModels(R.id.mobile_navigation) {
         defaultViewModelProviderFactory
    }
</code>```

Body:
In case you can deal with destroying fragment, but want to save ViewModel, you can scope it into the Navigation Graph:

private val viewModel: FavouritesViewModel by
    navGraphViewModels(R.id.mobile_navigation) {
        viewModelFactory
    }

Read more here

EDIT

As @SpiralDev noted, using Hilt simplifies a bit:

private val viewModel: MainViewModel by
    navGraphViewModels(R.id.mobile_navigation) {
         defaultViewModelProviderFactory
    }


问:
Prime numbers upto 10^8 using sieve
Why this code is working only number less than 10^4? i need to find all the  prime numbers less than 10^8 but this is showing arrayindexoutofbound exception? why? i know we can only create array till size10^8(correct me if i am wrong)  but this is not even working for 10^5.  </p>

```<code> class Prime
    {
        public static void main (String[] args) throws java.lang.Exception
        {
            boolean[] prime = new boolean[100000000];
            prime[2]=true;
            int i;
            for(i=3; i<100000000; i+=2)
                prime[i]=true;
            for(i=3; i<100000000; i++)
            {
                if(prime[i]==true)
                    for(int j=i*i; j<100000000; j=j+i)
                        prime[j]=false;
            }
            for(i=1; i<100000000; i++)
            {
                if(prime[i]==true)
                System.out.println(i);
            }
        }
    }
</code>```

答:
The problem is here:

```<code>for(int j=i*i; j<100000000; j=j+i)
</code>```

Since i can be as large as 99999999, i*i may be higher than Integer.MAX_VALUE, which will cause numeric overflow. As a result, j will be initialized to a negative value, and prime[j] will throw an exception.

To fix the problem, you can simply add a condition that requires the j must be positive:

```<code>for(int j=i*i; j > 0 && j<100000000; j=j+i)
</code>```

Title: Prime numbers upto 10^8 using sieve

Body:
Why this code is working only number less than 10^4? i need to find all the  prime numbers less than 10^8 but this is showing arrayindexoutofbound exception? why? i know we can only create array till size10^8(correct me if i am wrong)  but this is not even working for 10^5.

 class Prime
    {
        public static void main (String[] args) throws java.lang.Exception
        {
            boolean[] prime = new boolean[100000000];
            prime[2]=true;
            int i;
            for(i=3; i<100000000; i+=2)
                prime[i]=true;
            for(i=3; i<100000000; i++)
            {
                if(prime[i]==true)
                    for(int j=i*i; j<100000000; j=j+i)
                        prime[j]=false;
            }
            for(i=1; i<100000000; i++)
            {
                if(prime[i]==true)
                System.out.println(i);
            }
        }
    }

Body:
The problem is here:

for(int j=i*i; j<100000000; j=j+i)

Since i can be as large as 99999999, i*i may be higher than Integer.MAX_VALUE, which will cause numeric overflow. As a result, j will be initialized to a negative value, and prime[j] will throw an exception.

To fix the problem, you can simply add a condition that requires the j must be positive:

for(int j=i*i; j > 0 && j<100000000; j=j+i)


问:
How to run a Qt application?
I have been using Qt creator to make applications using the Qt libraries. I can run these applications by just clicking the play button, but I want to learn how to make applications run just by double clicking on a .exe. So how can I do this?</p>

答: I'm assuming you are running windows since you mention an .exe file extension. Look in the debug and/or release subdirectories of your project to find the produced binary. You can double-click on it to run the application. However, there are several DLL's that will be required. So, make sure they are in your PATH or copy them in the same directory. Dependency Walker is useful for finding out what you need.</p>

OwnerDisplayName: Lucas Aardvark

ContentLicense: CC BY-SA 2.5

Title: How to run a Qt application?

OwnerDisplayName: monjardin


问:
Xcode 11 (11A420a) not displaying "Embed in H/VStack" menu items when using Command-Click on declaration
I've been playing around with SwiftUI and I'm noticing all these tutorials mentioning to Command-Click Text for example and expecting the following menu items to appear in order to Embed in HStack for example:

The problem is I'm not seeing any of these "Embed in H/VStack" menu items appear. Even if I search for "Embed" it doesn't return anything.

This is what I'm seeing:

I'm on:

Mojave 10.14.6 (18G95).

Xcode Version 11.0 (11A420a).

答:
I've never seen them as shown but they do exist for me in Xcode 11.4.1 under Show Code Actions rather than Refactor.

The shortcut to get there is [Command][Shift][Left Click] on a SwiftUI element.

 Show Code Actions">


问:
Umbraco 8 - Get Children Of Node Using ContentAtXPath() Method
I've been refactoring an existing Umbraco project to use more performant querying when getting back document data as everything was previously being returned using LINQ. I have been using a combination of Umbraco's querying via XPaths and Examine.

I am currently stumped on trying to get child documents using the Umbraco.ContentAtXPath() method. What I would like to do is get child document based on a path I parse to the method. This is what I have currently:

```<code>IEnumerable<IPublishedContent> umbracoPages = Umbraco.ContentAtXPath("//* [@isDoc]/descendant::/About [@isDoc]");
</code>```

Running this returns a "Object reference not set to an instance of an object." error and unable to see exactly where I'm going wrong (new to this form of querying in Umbraco).

Ideally, I'd like to enhance the querying to also carry out sorting using the non-LINQ approach, as demonstrated here.

答:
It certainly depends on how big your dataset is.

As Umbraco has moved away from the XML backed cache, you should look into Linq queries against your content models. Make sure you use ModelsBuilder to generate the models.

On a small dataset Linq will be much quicker than examine.  On a large dataset Examine/Lucene will be much more steady on performance.

Body:
I've been refactoring an existing Umbraco project to use more performant querying when getting back document data as everything was previously being returned using LINQ. I have been using a combination of Umbraco's querying via XPaths and Examine.

I am currently stumped on trying to get child documents using the Umbraco.ContentAtXPath() method. What I would like to do is get child document based on a path I parse to the method. This is what I have currently:

IEnumerable<IPublishedContent> umbracoPages = Umbraco.ContentAtXPath("//* [@isDoc]/descendant::/About [@isDoc]");

Running this returns a "Object reference not set to an instance of an object." error and unable to see exactly where I'm going wrong (new to this form of querying in Umbraco).

Ideally, I'd like to enhance the querying to also carry out sorting using the non-LINQ approach, as demonstrated here.


问:
Easier management of DOM creation of elements in PHP
I'm trying to find an easier way to create  elements and inserting text values into them.

There has to be an easier way than creating a new variable for each  element, right? Perhaps making a class with some abstraction? Or maybe I'm doing it the wrong way?

At this rate creating 7 s will require me to  create 7 variables, 7 different createTextNodes for each of them and 14 more lines of appendChild().

That will be 28 lines for only 7 s. This seems excessive to me. Not to mention there's more than one
in the table. Is there any way to shorten the amount of lines I can type to create something like:

```<code><table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</code>```

Short example code of what I'm doing:

```<code>$doc = new DOMDocument;

$table = $doc->createElement('table');

        $doc->appendChild($table);

        $tr1 = $doc->createElement('tr');
        $table->appendChild($tr1);

        $td1 = $doc->createElement('td');
        $tr1->appendChild($td1);

        $td1_1 = $doc->createElement('td');
        $tr1->appendChild($td1_1);

        $td1_2 = $doc->createElement('td');
        $tr1->appendChild($td1_2);

        $title1 = $doc->createTextNode('This is title #1');
        $title2 = $doc->createTextNode('This is title #2');
        $title3 = $doc->createTextNode('This is title #3');

        $td1->appendChild($title1);
        $td1_1->appendChild($title2);
        $td1_2->appendChild($title3);

        echo $doc->saveXML();

?>
</code>```

答:
Loops are your friends</p>

```<code>$added=array();
for($i=0;$i<7;$i++) {
   $added[]= $doc->createElement('td');
   $tr1->appendChild($td1);

}
</code>```

Body:
I'm trying to find an easier way to create  elements and inserting text values into them.

There has to be an easier way than creating a new variable for each  element, right? Perhaps making a class with some abstraction? Or maybe I'm doing it the wrong way?

At this rate creating 7 s will require me to  create 7 variables, 7 different createTextNodes for each of them and 14 more lines of appendChild().

That will be 28 lines for only 7 s. This seems excessive to me. Not to mention there's more than one
in the table. Is there any way to shorten the amount of lines I can type to create something like:

Short example code of what I'm doing:

$doc = new DOMDocument;

$table = $doc->createElement('table');

        $doc->appendChild($table);

        $tr1 = $doc->createElement('tr');
        $table->appendChild($tr1);

        $td1 = $doc->createElement('td');
        $tr1->appendChild($td1);

        $td1_1 = $doc->createElement('td');
        $tr1->appendChild($td1_1);

        $td1_2 = $doc->createElement('td');
        $tr1->appendChild($td1_2);

        $title1 = $doc->createTextNode('This is title #1');
        $title2 = $doc->createTextNode('This is title #2');
        $title3 = $doc->createTextNode('This is title #3');

        $td1->appendChild($title1);
        $td1_1->appendChild($title2);
        $td1_2->appendChild($title3);

        echo $doc->saveXML();

?>

Body:
Loops are your friends

$added=array();
for($i=0;$i<7;$i++) {
   $added[]= $doc->createElement('td');
   $tr1->appendChild($td1);

}


问:
What would happen if entity model has relations but data (views) in database doesn't have relations and if they are inconsistent?
My question is would Spring JPA throw exceptions for every query?

I mean, let say there are tables without any relation (FK) between them in database. It is bad design but you cannot change it and it is not up to you.

But you know that data itself should be as there are relations.

That's why you create Entity model with all relations like they are there.

But as I said there is no real relations in database.

And in one point data are inconsistent in database.

Would Spring JPA throw exceptions if there are inconsistency or it will just return you inconsistent data?

答:
I assume with "relations" you mean "foreign keys".

JPA doesn't care about foreign keys.
All it cares about is if the data matches the mapping information on the entities.

So if you have an entity A that references an entity B with id b but such a B does not exist you might eventually get an exception.
Or you might just get an A with a null reference to B.
If the reference is marked as mandatory you might actually not be able to load the A in the first place, because a join is used and therefore not returning any data at all.

Side note: All this depends more on the JPA implementation you are using than on Spring Data JPA.


问:
Check if a specific user reacted discord.py
I am looking for a script to check if the user that executed the command (ctx.message.author) has reacted to the message with a checkmark, it should look like this:

```<code>@client.command()
async def test(ctx):
    message = await ctx.send("Test")
    for emoji in ('✅'):
        await message.add_reaction(emoji)
        # Here it should detect if the ctx.message.author has reacted
</code>```

答:
You can check via the user's ID and using wait_for:

import asyncio # for the exception

@client.command()
async def test(ctx):
    message = await ctx.send("Test")
    for emoji in ('✅'):
        await message.add_reaction(emoji)

        try:

            # the wait_for will only register if the following conditions are met
            def check(rctn, user):
                return user.id == ctx.author.id and str(rctn) == '✅'

            # timeout kwarg is optional
            rctn, user = await client.wait_for("reaction_add", check=check, timeout=30)

            # then execute your code here if the author reacts, like so:
            await ctx.send("I detected the author reacting!")

        # throws this error if user doesn't react in time
        # you won't need this if you don't provide a timeout kwarg in wait_for()
        except asyncio.TimeoutError:
            await ctx.send("Sorry, you didn't react in time!")
```

References:

Client.wait_for()

Member.id

Body:
I am looking for a script to check if the user that executed the command (ctx.message.author) has reacted to the message with a checkmark, it should look like this:

@client.command()
async def test(ctx):
    message = await ctx.send("Test")
    for emoji in ('✅'):
        await message.add_reaction(emoji)
        # Here it should detect if the ctx.message.author has reacted

Body:
You can check via the user's ID and using wait_for:

import asyncio # for the exception

@client.command()
async def test(ctx):
    message = await ctx.send("Test")
    for emoji in ('✅'):
        await message.add_reaction(emoji)

        try:

            # the wait_for will only register if the following conditions are met
            def check(rctn, user):
                return user.id == ctx.author.id and str(rctn) == '✅'

            # timeout kwarg is optional
            rctn, user = await client.wait_for("reaction_add", check=check, timeout=30)

            # then execute your code here if the author reacts, like so:
            await ctx.send("I detected the author reacting!")

        # throws this error if user doesn't react in time
        # you won't need this if you don't provide a timeout kwarg in wait_for()
        except asyncio.TimeoutError:
            await ctx.send("Sorry, you didn't react in time!")

References:

Client.wait_for()

Member.id


问:
Loop through several ranges with same code
I am quite new to VBA and I would like to ask for help.
I want to clear the code as I am using same loop code for several ranges.

I have form, where I have like 10 tables (located in 2 columns x 5 below). Each table can contains up to 5 lines, and have 4 columns (5x4).

I want to import inputs from the tables in new sheet via vba.
So I create a loop for certain ranges. The ranges are (line 54:58, 65:69, 76:80, 87:91, 98:102), columns (3-6) & (9-12)
I do not want to import blanks fields, therefore there is a condition if.

Is there a way how to simplified the code, that I do not have to loop each range? something like "loop these ranges" and having there the code only once?

```<code>Dim wb As Workbook
Dim wsSource As Worksheet
Dim wsTarget As Worksheet
Dim p As Long, i As Long
Dim lastrowPest As Long, lastrowField As Long

Set wb = ActiveWorkbook
Set wsSource = wb.Sheets("Field entry - plan")
Set wsTarget = wb.Sheets("List3")

lastrowField = wsSource.Cells(Rows.Count, 20).End(xlUp).row

For p = 54 To 58

    For i = 3 To lastrowField

        If wsSource.Cells(p, 4) <> "" Then

        lastrowPest = wsTarget.Cells(Rows.Count, 24).End(xlUp).Offset(1, 0).row

        wsSource.Range(wsSource.Cells(i, 20), wsSource.Cells(i, 20)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 24), wsTarget.Cells(lastrowPest, 24)).PasteSpecial Paste:=xlPasteValues

        wsSource.Range(wsSource.Cells(i, 34), wsSource.Cells(i, 34)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 30), wsTarget.Cells(lastrowPest, 30)).PasteSpecial Paste:=xlPasteValues

        wsSource.Range(wsSource.Cells(p, 3), wsSource.Cells(p, 6)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 26), wsTarget.Cells(lastrowPest, 28)).PasteSpecial Paste:=xlPasteValues

        End If

        If wsSource.Cells(p, 10) <> "" Then

        lastrowPest = wsTarget.Cells(Rows.Count, 24).End(xlUp).Offset(1, 0).row

        wsSource.Range(wsSource.Cells(i, 20), wsSource.Cells(i, 20)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 24), wsTarget.Cells(lastrowPest, 24)).PasteSpecial Paste:=xlPasteValues

        wsSource.Range(wsSource.Cells(i, 34), wsSource.Cells(i, 34)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 30), wsTarget.Cells(lastrowPest, 30)).PasteSpecial Paste:=xlPasteValues

        wsSource.Range(wsSource.Cells(p, 9), wsSource.Cells(p, 12)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 26), wsTarget.Cells(lastrowPest, 28)).PasteSpecial Paste:=xlPasteValues

        End If
    Next i

Next p

For p = 65 To 69

    For i = 3 To lastrowField

        If wsSource.Cells(p, 4) <> "" Then

        lastrowPest = wsTarget.Cells(Rows.Count, 24).End(xlUp).Offset(1, 0).row

        wsSource.Range(wsSource.Cells(i, 20), wsSource.Cells(i, 20)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 24), wsTarget.Cells(lastrowPest, 24)).PasteSpecial Paste:=xlPasteValues

        wsSource.Range(wsSource.Cells(i, 34), wsSource.Cells(i, 34)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 30), wsTarget.Cells(lastrowPest, 30)).PasteSpecial Paste:=xlPasteValues

        wsSource.Range(wsSource.Cells(p, 3), wsSource.Cells(p, 6)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 26), wsTarget.Cells(lastrowPest, 28)).PasteSpecial Paste:=xlPasteValues

        End If

        If wsSource.Cells(p, 10) <> "" Then

        lastrowPest = wsTarget.Cells(Rows.Count, 24).End(xlUp).Offset(1, 0).row

        wsSource.Range(wsSource.Cells(i, 20), wsSource.Cells(i, 20)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 24), wsTarget.Cells(lastrowPest, 24)).PasteSpecial Paste:=xlPasteValues

        wsSource.Range(wsSource.Cells(i, 34), wsSource.Cells(i, 34)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 30), wsTarget.Cells(lastrowPest, 30)).PasteSpecial Paste:=xlPasteValues

        wsSource.Range(wsSource.Cells(p, 9), wsSource.Cells(p, 12)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 26), wsTarget.Cells(lastrowPest, 28)).PasteSpecial Paste:=xlPasteValues

        End If
    Next i

Next p
</code>```

答:
You can put the repetitive code in a different procedure and call it with arguments like this:

```<code>Option Explicit
Sub Test()

    Dim FirstRows(1 To 2) As Long
    FirstRows(1) = 54
    FirstRows(2) = 65
    Dim LastRows(1 To 2) As Long
    LastRows(1) = 58
    LastRows(2) = 69

    Dim i As Long
    For i = LBound(FirstRows) To UBound(FirstRows)
        CopyPaste FirstRows(i), LastRows(i)
    Next i

End Sub
Private Sub CopyPaste(FirstRow As Long, LastRow As Long)

    Dim wb As Workbook
    Dim wsSource As Worksheet
    Dim wsTarget As Worksheet
    Dim p As Long, i As Long
    Dim lastrowPest As Long, lastrowField As Long

    Set wb = ActiveWorkbook
    Set wsSource = wb.Sheets("Field entry - plan")
    Set wsTarget = wb.Sheets("List3")

    lastrowField = wsSource.Cells(Rows.Count, 20).End(xlUp).Row

    For p = FirstRow To LastRow

        For i = 3 To lastrowField

            If wsSource.Cells(p, 4) <> "" Then

            lastrowPest = wsTarget.Cells(Rows.Count, 24).End(xlUp).Offset(1, 0).Row

            wsSource.Range(wsSource.Cells(i, 20), wsSource.Cells(i, 20)).Copy
            wsTarget.Range(wsTarget.Cells(lastrowPest, 24), wsTarget.Cells(lastrowPest, 24)).PasteSpecial Paste:=xlPasteValues

            wsSource.Range(wsSource.Cells(i, 34), wsSource.Cells(i, 34)).Copy
            wsTarget.Range(wsTarget.Cells(lastrowPest, 30), wsTarget.Cells(lastrowPest, 30)).PasteSpecial Paste:=xlPasteValues

            wsSource.Range(wsSource.Cells(p, 3), wsSource.Cells(p, 6)).Copy
            wsTarget.Range(wsTarget.Cells(lastrowPest, 26), wsTarget.Cells(lastrowPest, 28)).PasteSpecial Paste:=xlPasteValues

            End If

            If wsSource.Cells(p, 10) <> "" Then

            lastrowPest = wsTarget.Cells(Rows.Count, 24).End(xlUp).Offset(1, 0).Row

            wsSource.Range(wsSource.Cells(i, 20), wsSource.Cells(i, 20)).Copy
            wsTarget.Range(wsTarget.Cells(lastrowPest, 24), wsTarget.Cells(lastrowPest, 24)).PasteSpecial Paste:=xlPasteValues

            wsSource.Range(wsSource.Cells(i, 34), wsSource.Cells(i, 34)).Copy
            wsTarget.Range(wsTarget.Cells(lastrowPest, 30), wsTarget.Cells(lastrowPest, 30)).PasteSpecial Paste:=xlPasteValues

            wsSource.Range(wsSource.Cells(p, 9), wsSource.Cells(p, 12)).Copy
            wsTarget.Range(wsTarget.Cells(lastrowPest, 26), wsTarget.Cells(lastrowPest, 28)).PasteSpecial Paste:=xlPasteValues

            End If
        Next i

    Next p

End Sub
</code>```

You can make larger your arrays on the Test procedure by changing the 1 to 2to 1 to whatever number and suit it to your needs.

Body:
I am quite new to VBA and I would like to ask for help.
I want to clear the code as I am using same loop code for several ranges.

I have form, where I have like 10 tables (located in 2 columns x 5 below). Each table can contains up to 5 lines, and have 4 columns (5x4).

I want to import inputs from the tables in new sheet via vba.
So I create a loop for certain ranges. The ranges are (line 54:58, 65:69, 76:80, 87:91, 98:102), columns (3-6) & (9-12)
I do not want to import blanks fields, therefore there is a condition if.

Is there a way how to simplified the code, that I do not have to loop each range? something like "loop these ranges" and having there the code only once?

Dim wb As Workbook
Dim wsSource As Worksheet
Dim wsTarget As Worksheet
Dim p As Long, i As Long
Dim lastrowPest As Long, lastrowField As Long

Set wb = ActiveWorkbook
Set wsSource = wb.Sheets("Field entry - plan")
Set wsTarget = wb.Sheets("List3")

lastrowField = wsSource.Cells(Rows.Count, 20).End(xlUp).row

For p = 54 To 58

    For i = 3 To lastrowField

        If wsSource.Cells(p, 4) <> "" Then

        lastrowPest = wsTarget.Cells(Rows.Count, 24).End(xlUp).Offset(1, 0).row

        wsSource.Range(wsSource.Cells(i, 20), wsSource.Cells(i, 20)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 24), wsTarget.Cells(lastrowPest, 24)).PasteSpecial Paste:=xlPasteValues

        wsSource.Range(wsSource.Cells(i, 34), wsSource.Cells(i, 34)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 30), wsTarget.Cells(lastrowPest, 30)).PasteSpecial Paste:=xlPasteValues

        wsSource.Range(wsSource.Cells(p, 3), wsSource.Cells(p, 6)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 26), wsTarget.Cells(lastrowPest, 28)).PasteSpecial Paste:=xlPasteValues

        End If

        If wsSource.Cells(p, 10) <> "" Then

        lastrowPest = wsTarget.Cells(Rows.Count, 24).End(xlUp).Offset(1, 0).row

        wsSource.Range(wsSource.Cells(i, 20), wsSource.Cells(i, 20)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 24), wsTarget.Cells(lastrowPest, 24)).PasteSpecial Paste:=xlPasteValues

        wsSource.Range(wsSource.Cells(i, 34), wsSource.Cells(i, 34)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 30), wsTarget.Cells(lastrowPest, 30)).PasteSpecial Paste:=xlPasteValues

        wsSource.Range(wsSource.Cells(p, 9), wsSource.Cells(p, 12)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 26), wsTarget.Cells(lastrowPest, 28)).PasteSpecial Paste:=xlPasteValues

        End If
    Next i

Next p

For p = 65 To 69

    For i = 3 To lastrowField

        If wsSource.Cells(p, 4) <> "" Then

        lastrowPest = wsTarget.Cells(Rows.Count, 24).End(xlUp).Offset(1, 0).row

        wsSource.Range(wsSource.Cells(i, 20), wsSource.Cells(i, 20)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 24), wsTarget.Cells(lastrowPest, 24)).PasteSpecial Paste:=xlPasteValues

        wsSource.Range(wsSource.Cells(i, 34), wsSource.Cells(i, 34)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 30), wsTarget.Cells(lastrowPest, 30)).PasteSpecial Paste:=xlPasteValues

        wsSource.Range(wsSource.Cells(p, 3), wsSource.Cells(p, 6)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 26), wsTarget.Cells(lastrowPest, 28)).PasteSpecial Paste:=xlPasteValues

        End If

        If wsSource.Cells(p, 10) <> "" Then

        lastrowPest = wsTarget.Cells(Rows.Count, 24).End(xlUp).Offset(1, 0).row

        wsSource.Range(wsSource.Cells(i, 20), wsSource.Cells(i, 20)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 24), wsTarget.Cells(lastrowPest, 24)).PasteSpecial Paste:=xlPasteValues

        wsSource.Range(wsSource.Cells(i, 34), wsSource.Cells(i, 34)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 30), wsTarget.Cells(lastrowPest, 30)).PasteSpecial Paste:=xlPasteValues

        wsSource.Range(wsSource.Cells(p, 9), wsSource.Cells(p, 12)).copy
        wsTarget.Range(wsTarget.Cells(lastrowPest, 26), wsTarget.Cells(lastrowPest, 28)).PasteSpecial Paste:=xlPasteValues

        End If
    Next i

Next p

Body:
You can put the repetitive code in a different procedure and call it with arguments like this:

Option Explicit
Sub Test()

    Dim FirstRows(1 To 2) As Long
    FirstRows(1) = 54
    FirstRows(2) = 65
    Dim LastRows(1 To 2) As Long
    LastRows(1) = 58
    LastRows(2) = 69

    Dim i As Long
    For i = LBound(FirstRows) To UBound(FirstRows)
        CopyPaste FirstRows(i), LastRows(i)
    Next i

End Sub
Private Sub CopyPaste(FirstRow As Long, LastRow As Long)

    Dim wb As Workbook
    Dim wsSource As Worksheet
    Dim wsTarget As Worksheet
    Dim p As Long, i As Long
    Dim lastrowPest As Long, lastrowField As Long

    Set wb = ActiveWorkbook
    Set wsSource = wb.Sheets("Field entry - plan")
    Set wsTarget = wb.Sheets("List3")

    lastrowField = wsSource.Cells(Rows.Count, 20).End(xlUp).Row

    For p = FirstRow To LastRow

        For i = 3 To lastrowField

            If wsSource.Cells(p, 4) <> "" Then

            lastrowPest = wsTarget.Cells(Rows.Count, 24).End(xlUp).Offset(1, 0).Row

            wsSource.Range(wsSource.Cells(i, 20), wsSource.Cells(i, 20)).Copy
            wsTarget.Range(wsTarget.Cells(lastrowPest, 24), wsTarget.Cells(lastrowPest, 24)).PasteSpecial Paste:=xlPasteValues

            wsSource.Range(wsSource.Cells(i, 34), wsSource.Cells(i, 34)).Copy
            wsTarget.Range(wsTarget.Cells(lastrowPest, 30), wsTarget.Cells(lastrowPest, 30)).PasteSpecial Paste:=xlPasteValues

            wsSource.Range(wsSource.Cells(p, 3), wsSource.Cells(p, 6)).Copy
            wsTarget.Range(wsTarget.Cells(lastrowPest, 26), wsTarget.Cells(lastrowPest, 28)).PasteSpecial Paste:=xlPasteValues

            End If

            If wsSource.Cells(p, 10) <> "" Then

            lastrowPest = wsTarget.Cells(Rows.Count, 24).End(xlUp).Offset(1, 0).Row

            wsSource.Range(wsSource.Cells(i, 20), wsSource.Cells(i, 20)).Copy
            wsTarget.Range(wsTarget.Cells(lastrowPest, 24), wsTarget.Cells(lastrowPest, 24)).PasteSpecial Paste:=xlPasteValues

            wsSource.Range(wsSource.Cells(i, 34), wsSource.Cells(i, 34)).Copy
            wsTarget.Range(wsTarget.Cells(lastrowPest, 30), wsTarget.Cells(lastrowPest, 30)).PasteSpecial Paste:=xlPasteValues

            wsSource.Range(wsSource.Cells(p, 9), wsSource.Cells(p, 12)).Copy
            wsTarget.Range(wsTarget.Cells(lastrowPest, 26), wsTarget.Cells(lastrowPest, 28)).PasteSpecial Paste:=xlPasteValues

            End If
        Next i

    Next p

End Sub

You can make larger your arrays on the Test procedure by changing the 1 to 2to 1 to whatever number and suit it to your needs.


问:
SQLite3 MinGW on Windows 10
I want to run sqlite natively in MinGW as I do in Linux.

Tried downloading SQLite3 for Windows. Though it runs in Windows Command prompt, just like it does in Linux, in MinGW terminal the console hangs.

What can I do to ensure the MinGW plays as nice as Windows?

答:
Compile against a version of readline that works properly on Windows.
I build sqlite3 against readline from http://tiswww.case.edu/php/chet/readline/rltop.html and have no issues.</p>

Title: SQLite3 MinGW on Windows 10