问:
How to select two SUMs from one table but one SUM must be made from only max. data
I have this table

```<code>Room       Papers    Pens
1           30        30
3           10        10
4           15        15
4           35        25
3           25        5
2           15        45
2           5         15
4           7         8
4           11        9
4           12        11
1           8         8
</code>```

I need to get SUM(Papers) for Rooms 2,4 which I know how to get (it will be together 100) but then I need also get in this query SUM(Pens) also for Rooms 2,4 BUT only for highest value for each Room. It will be for Room 2 value 45 and for Room 4 value 25 in this table and SUM must be 70.

I have used this code but ofcourse it is not working correct for Pens value...

```<code>SELECT SUM(Papers) AS Papers, SUM(DISTINCT Pens) AS Pens FROM MyTable
WHERE (Room = '2' OR Room = '4')
</code>```

THX for help

答:
You can do it with conditional aggregation:</p>

```<code>SELECT
  SUM(Papers) AS Papers,
  SUM(
    CASE
      WHEN EXISTS (
        SELECT 1 FROM MyTable
        WHERE Room = m.Room AND Pens > m.Pens
      ) THEN 0
      ELSE Pens
    END
  ) AS Pens
  FROM MyTable m
WHERE (Room = '2' OR Room = '4')
</code>```

Body:
I have this table

Room       Papers    Pens
1           30        30
3           10        10
4           15        15
4           35        25
3           25        5
2           15        45
2           5         15
4           7         8
4           11        9
4           12        11
1           8         8

I need to get SUM(Papers) for Rooms 2,4 which I know how to get (it will be together 100) but then I need also get in this query SUM(Pens) also for Rooms 2,4 BUT only for highest value for each Room. It will be for Room 2 value 45 and for Room 4 value 25 in this table and SUM must be 70.

I have used this code but ofcourse it is not working correct for Pens value...

SELECT SUM(Papers) AS Papers, SUM(DISTINCT Pens) AS Pens FROM MyTable
WHERE (Room = '2' OR Room = '4')

THX for help

Body:
You can do it with conditional aggregation:

SELECT
  SUM(Papers) AS Papers,
  SUM(
    CASE
      WHEN EXISTS (
        SELECT 1 FROM MyTable
        WHERE Room = m.Room AND Pens > m.Pens
      ) THEN 0
      ELSE Pens
    END
  ) AS Pens
  FROM MyTable m
WHERE (Room = '2' OR Room = '4')


来源: stackexchange

问:
ASP.NET w/ VB.NET - MultiSelect on ListBox Or CheckBoxList w/ AutoPostback enabled
Background: I have a winForm app that registers a user in the database based on the user input provided in the form, auto-generates a random password and username for the user, and e-mails the user a link to take an application based on the marketing company selected.

Problem:
I got the bundles listbox to populate w/ autopostback set to true but the bundles listbox populates as soon as you click on an lbcarrier and it doesn't allow you select more than one carrier.

Do you have any ideas on how to allow multiselect with the postback feature on?

Here's a screenshot of the interface:

code on default.aspx:

```<code>        <td class="style1">
            Carriers:</td>
        <td bgcolor="#ffffff" class="style2">
            <asp:ListBox AutoPostback="true" ID="lbCarriers" runat="server" Height="86px" Width="250px">
            </asp:ListBox>
                </td>
            </tr>

        <td class="style1">
            Bundles:</td>
        <td bgcolor="#ffffff" class="style2">
            <asp:ListBox ID="bundles" runat="server" Height="86px" Width="250px">
            </asp:ListBox>
                </td>
            </tr>
</code>```

code on default.aspx.vb:

```<code>Protected Sub lbCarriers_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lbCarriers.SelectedIndexChanged

    Dim splt() As String
    Dim ac1 As Array
    bundles.Items.Clear()
    Dim item As ListItem = lbCarriers.SelectedItem
    splt = item.ToString().Split("|")
    ac1 = proxy.GetContractingBundles("test", "test", Trim(splt(0)))
    For Each Pitem In ac1
        bundles.Items.Add(Trim(splt(2)) & " | " & Pitem.FormBundleName)
    Next
End Sub
</code>```

Thanks for looking!

答:
By definition the AutoPostBack property will automatically cause a postback to occur when the user changes the list selection.

To enable multiple selections you'll need to turn AutoPostBack off and enable the SelectionMode property:

```<code><asp:ListBox SelectionMode="Multiple" ID="lbCarriers" runat="server"
    Height="86px" Width="250px">
</code>```

Note that AutoPostBack is false by default so I simply omitted it.

Once the user submits you can process the selected list box items with logic similar to what you have in the lbCarriers_SelectedIndexChanged event. You can then loop through the items and check the item's Selected property or loop through the results of the GetSelectedIndices method and reference the items by their indices.

If that's not the route you want to take, and you want it to be handled on the fly without a postback, then you'll need to write some JavaScript.

EDIT: the code to go through your selected items would be similar to the code below, and you would probably place it in a method that is called by the submitted button's event handler.

```<code>bundles.Items.Clear()
For Each item As ListItem In lbCarriers.Items
    If item.Selected Then
        Dim splt() As String
        Dim ac1 As Array
        splt = item.ToString().Split("|")
        ac1 = proxy.GetContractingBundles("test", "test", Trim(splt(0)))
        For Each Pitem In ac1
            bundles.Items.Add(Trim(splt(2)) & " | " & Pitem.FormBundleName)
        Next
    End If
Next
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Background: I have a winForm app that registers a user in the database based on the user input provided in the form, auto-generates a random password and username for the user, and e-mails the user a link to take an application based on the marketing company selected.

Problem:
I got the bundles listbox to populate w/ autopostback set to true but the bundles listbox populates as soon as you click on an lbcarrier and it doesn't allow you select more than one carrier.

Do you have any ideas on how to allow multiselect with the postback feature on?

Here's a screenshot of the interface:

code on default.aspx:

            Carriers:

            <asp:ListBox AutoPostback="true" ID="lbCarriers" runat="server" Height="86px" Width="250px">
            </asp:ListBox>

            Bundles:

            <asp:ListBox ID="bundles" runat="server" Height="86px" Width="250px">
            </asp:ListBox>

code on default.aspx.vb:

Protected Sub lbCarriers_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lbCarriers.SelectedIndexChanged

    Dim splt() As String
    Dim ac1 As Array
    bundles.Items.Clear()
    Dim item As ListItem = lbCarriers.SelectedItem
    splt = item.ToString().Split("|")
    ac1 = proxy.GetContractingBundles("test", "test", Trim(splt(0)))
    For Each Pitem In ac1
        bundles.Items.Add(Trim(splt(2)) & " | " & Pitem.FormBundleName)
    Next
End Sub

Thanks for looking!

Body:
By definition the AutoPostBack property will automatically cause a postback to occur when the user changes the list selection.

To enable multiple selections you'll need to turn AutoPostBack off and enable the SelectionMode property:

<asp:ListBox SelectionMode="Multiple" ID="lbCarriers" runat="server"
    Height="86px" Width="250px">

Note that AutoPostBack is false by default so I simply omitted it.

Once the user submits you can process the selected list box items with logic similar to what you have in the lbCarriers_SelectedIndexChanged event. You can then loop through the items and check the item's Selected property or loop through the results of the GetSelectedIndices method and reference the items by their indices.

If that's not the route you want to take, and you want it to be handled on the fly without a postback, then you'll need to write some JavaScript.

EDIT: the code to go through your selected items would be similar to the code below, and you would probably place it in a method that is called by the submitted button's event handler.

bundles.Items.Clear()
For Each item As ListItem In lbCarriers.Items
    If item.Selected Then
        Dim splt() As String
        Dim ac1 As Array
        splt = item.ToString().Split("|")
        ac1 = proxy.GetContractingBundles("test", "test", Trim(splt(0)))
        For Each Pitem In ac1
            bundles.Items.Add(Trim(splt(2)) & " | " & Pitem.FormBundleName)
        Next
    End If
Next


问:
QnA Maker with cards
I want to add cards in my QnA Maker. I my QnA maker if anyone asks about "what services we provide?" Bot should answer (for example: We provide following services /n/n 1: Bot Development /n/n 2: Web Development /n/n 3: Documentation). In this example bot should reply it with the card and if user clicks on any of the above mentioned services than it should gives details about that.
Thanks in advance...</p>

答:
QnA Maker has just released a new feature called multi-turn conversations whcih does exactly what you are looking for.

Once you have added some multi-turn conversations to your knowledge base you can try this out by downloading the BotBuilder-Samples repo and opening the qnamaker-prompting sample (C# and NodeJS provided) then you can plug your knowledge base details into the appsettings.json (C#) or .env (NodeJS) file and test the functionality locally using the Bot Framework Emulator.

The key part is this method which checks to see if the result contains any prompts and returns the response accordingly - it is called inside the controller.

This should give you a good idea of how to get started.

ContentLicense: CC BY-SA 4.0

Title: QnA Maker with cards


问:
Django rest api problem: should either include a `querylist` attribute, or override the `get_querylist()` method
This is my serializer class:

```<code>class JlistSerializers(serializers.ModelSerializer):
    class Meta:
        model = Jlist
        fields = ('id', 'name', 'news_channel', 'wiki', 'image', 'total_star', 'total_user')
</code>```

This is my views

```<code>class JlistView(ObjectMultipleModelAPIView):
    queryset = Jlist.objects.all()

    def get_queryset(self, *args, **kwargs):
        userId = self.kwargs.get('pk')
        queryset = [
            {'queryset': Jlist.objects.all(),
             'serializer_class': JlistSerializers},
            {'queryset': JStarList.objects.filter(userId=userId),
             'serializer_class': JStarList}
        ]
        return queryset
</code>```

I am getting followiing error

```<code>AssertionError at /api/jlist
JlistView should either include a `querylist` attribute, or override the `get_querylist()` method.
</code>```

I have used the same code to create api for other serializer class but getting error in creating this api.Please help me figure out what is problem here?

答:
You defined get_queryset, but it should be get_querylist. And remove queryset member too.</p>

```<code>class JlistView(ObjectMultipleModelAPIView):

    def get_querylist(self, *args, **kwargs):
        userId = self.kwargs.get('pk')
        queryset = [
            {'queryset': Jlist.objects.all(),
             'serializer_class': JlistSerializers},
            {'queryset': JStarList.objects.filter(userId=userId),
             'serializer_class': JStarList}
        ]
        return queryset
</code>```

Body:
This is my serializer class:

class JlistSerializers(serializers.ModelSerializer):
    class Meta:
        model = Jlist
        fields = ('id', 'name', 'news_channel', 'wiki', 'image', 'total_star', 'total_user')

This is my views

class JlistView(ObjectMultipleModelAPIView):
    queryset = Jlist.objects.all()

    def get_queryset(self, *args, **kwargs):
        userId = self.kwargs.get('pk')
        queryset = [
            {'queryset': Jlist.objects.all(),
             'serializer_class': JlistSerializers},
            {'queryset': JStarList.objects.filter(userId=userId),
             'serializer_class': JStarList}
        ]
        return queryset

I am getting followiing error

AssertionError at /api/jlist
JlistView should either include a `querylist` attribute, or override the `get_querylist()` method.

I have used the same code to create api for other serializer class but getting error in creating this api.Please help me figure out what is problem here?

Body:
You defined get_queryset, but it should be get_querylist. And remove queryset member too.

class JlistView(ObjectMultipleModelAPIView):

    def get_querylist(self, *args, **kwargs):
        userId = self.kwargs.get('pk')
        queryset = [
            {'queryset': Jlist.objects.all(),
             'serializer_class': JlistSerializers},
            {'queryset': JStarList.objects.filter(userId=userId),
             'serializer_class': JStarList}
        ]
        return queryset


问:
IN clause with spring boot specification for list of string
I have a table Media that has a column "tagList" that contains the list of string. I m trying to write the specification for search query.

Below specification is working fine if inputTag is mentos and tagList is ["mentos","bollywood","cinema"] but if inputTag is "men" it is not returning any row. How to replace the isMember with in so that it matches for substring as well.

This is the code:

```<code>public class MediaRepositoryService {

@PersistenceContext
private EntityManager entityManager;

@Autowired
private MediaRepository mediaRepo;

@Transactional
public List<Media> searchMedia(final String inputTag) {
    List<Media> cases = mediaRepo.findAll(MediaSearchSpecificaton.findByCriteria(inputTag));
    return cases;
}

private static class MediaSearchSpecificaton {

    private static Specification<Media> findByCriteria(String inputTag) {

        return new Specification<Media>() {
            /**
             *
             */
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<Media> root, CriteriaQuery<?> query,
                    CriteriaBuilder criteriaBuilder) {

                Predicate predicate = criteriaBuilder.conjunction();
                predicate = criteriaBuilder.and(predicate, criteriaBuilder.isMember(inputTag, root.get("tagList")));

                return predicate;
            }
        };
    }
}

}
</code>```

答:
You can use JPA's Repository Like query method like:

Add this method in MediaRepository

```<code>List<Media> findByTagListContaining(String inputTag);
</code>```

and then call it from your method like

```<code>List<Media> cases = mediaRepo.findByTagListContaining(inputTag);
</code>```

Body:
I have a table Media that has a column "tagList" that contains the list of string. I m trying to write the specification for search query.

Below specification is working fine if inputTag is mentos and tagList is ["mentos","bollywood","cinema"] but if inputTag is "men" it is not returning any row. How to replace the isMember with in so that it matches for substring as well.

This is the code:

public class MediaRepositoryService {

@PersistenceContext
private EntityManager entityManager;

@Autowired
private MediaRepository mediaRepo;

@Transactional
public List<Media> searchMedia(final String inputTag) {
    List<Media> cases = mediaRepo.findAll(MediaSearchSpecificaton.findByCriteria(inputTag));
    return cases;
}

private static class MediaSearchSpecificaton {

    private static Specification<Media> findByCriteria(String inputTag) {

        return new Specification<Media>() {
            /**
             *
             */
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<Media> root, CriteriaQuery<?> query,
                    CriteriaBuilder criteriaBuilder) {

                Predicate predicate = criteriaBuilder.conjunction();
                predicate = criteriaBuilder.and(predicate, criteriaBuilder.isMember(inputTag, root.get("tagList")));

                return predicate;
            }
        };
    }
}

}

Body:
You can use JPA's Repository Like query method like:

Add this method in MediaRepository

List<Media> findByTagListContaining(String inputTag);

and then call it from your method like

List<Media> cases = mediaRepo.findByTagListContaining(inputTag);


问:
PowerShell - Rename duplicate filenames in an object array
If I have some JSON like this:

```<code>$inputJson = @"
{
    "attachments" :
        [
            {
                "name":  "attachment.eml",
                "attachment_url":  "https://www.attachment1.com"
            },
            {
                "name":  "attachment.eml",
                "attachment_url":  "https://www.attachment2.com"
            },
            {
                "name":  "attachment.eml",
                "attachment_url":  "https://www.attachment3.com"
            }
        ]
}
</code>```

where there is an attachments array and each element in that array has the same name but different URLs, how can I change all the names so that it outputs like this:

```<code>$outputJson = @"
{
    "attachments" :
        [
            {
                "name":  "(attachment.eml)[1].eml",
                "attachment_url":  "https://www.attachment1.com"
            },
            {
                "name":  "(attachment.eml)[2].eml",
                "attachment_url":  "https://www.attachment2.com"
            },
            {
                "name":  "(attachment.eml)[3].eml",
                "attachment_url":  "https://www.attachment3.com"
            }
        ]
}
"@
</code>```

which renames each attachment to prevent duplicate names, but it preserves the URLs.

Ideally, the code would also make sure none of the new names already exist in the array as well. So if there is already an attachment named (attachment.eml)[1].eml in the array, it would handle that as well.

I've thought about somehow using Group-Object but I haven't quite figured out how to make that work.

答:
I think that the following should work:

```<code>uniques = []
new_attachments = []
attachments.forEach( a=>
    { var u = uniques.find( u => u.name == a.name);
        if (u == undefined) {
            uniques.push({name: a.name, count: 1});
            u = uniques.find(u => u.name == a.name)
        }else{
            u.count++
        }
        new_attachments.push( "(" + a.name.slice(0,-4) + ")[" + u.count + "].eml" )
} )
</code>```

You would have to change the last line from:

```<code>new_attachments.push( "(" + a.name.slice(0,-4) + ")[" + u.count + "].eml" )
</code>```

to:

```<code>a.name = "(" + a.name.slice(0,-4) + ")[" + u.count + "].eml"
</code>```

Body:
If I have some JSON like this:

$inputJson = @"
{
    "attachments" :
        [
            {
                "name":  "attachment.eml",
                "attachment_url":  "https://www.attachment1.com"
            },
            {
                "name":  "attachment.eml",
                "attachment_url":  "https://www.attachment2.com"
            },
            {
                "name":  "attachment.eml",
                "attachment_url":  "https://www.attachment3.com"
            }
        ]
}

where there is an attachments array and each element in that array has the same name but different URLs, how can I change all the names so that it outputs like this:

$outputJson = @"
{
    "attachments" :
        [
            {
                "name":  "(attachment.eml)[1].eml",
                "attachment_url":  "https://www.attachment1.com"
            },
            {
                "name":  "(attachment.eml)[2].eml",
                "attachment_url":  "https://www.attachment2.com"
            },
            {
                "name":  "(attachment.eml)[3].eml",
                "attachment_url":  "https://www.attachment3.com"
            }
        ]
}
"@

which renames each attachment to prevent duplicate names, but it preserves the URLs.

Ideally, the code would also make sure none of the new names already exist in the array as well. So if there is already an attachment named (attachment.eml)[1].eml in the array, it would handle that as well.

I've thought about somehow using Group-Object but I haven't quite figured out how to make that work.

Body:
I think that the following should work:

uniques = []
new_attachments = []
attachments.forEach( a=>
    { var u = uniques.find( u => u.name == a.name);
        if (u == undefined) {
            uniques.push({name: a.name, count: 1});
            u = uniques.find(u => u.name == a.name)
        }else{
            u.count++
        }
        new_attachments.push( "(" + a.name.slice(0,-4) + ")[" + u.count + "].eml" )
} )

You would have to change the last line from:

new_attachments.push( "(" + a.name.slice(0,-4) + ")[" + u.count + "].eml" )

to:

a.name = "(" + a.name.slice(0,-4) + ")[" + u.count + "].eml"


问:
PySpark: How to Append Dataframes in For Loop
I am performing a rolling median calculation on individual time series dataframes, then I want to concat/append the results.

```<code># UDF for rolling median
median_udf = udf(lambda x: float(np.median(x)), FloatType())

series_list = ['0620', '5914']
SeriesAppend=[]

for item in series_list:
    # Filter for select item
    series = test_df.where(col("ID").isin([item]))
    # Sort time series
    series_sorted = series.sort(series.ID,
    series.date).persist()
    # Calculate rolling median
    series_sorted = series_sorted.withColumn("list",
        collect_list("metric").over(w)) \
        .withColumn("rolling_median", median_udf("list"))

    SeriesAppend.append(series_sorted)

SeriesAppend
</code>```

[DataFrame[ntwrk_genre_cd: string, date: date, mkt_cd: string, syscode: string, ntwrk_cd: string, syscode_ntwrk: string, metric: double, list: array, rolling_median: float], DataFrame[ntwrk_genre_cd: string, date: date, mkt_cd: string, syscode: string, ntwrk_cd: string, syscode_ntwrk: string, metric: double, list: array, rolling_median: float]]

When I attempt to .show():

```<code>'list' object has no attribute 'show'
Traceback (most recent call last):
AttributeError: 'list' object has no attribute 'show'
</code>```

I realize this is saying the object is a list of dataframes. How do I convert to a single dataframe?

I know that the following solution works for an explicit number of dataframes, but I want my for-loop to be agnostic to the number of dataframes:

```<code>from functools import reduce
from pyspark.sql import DataFrame

dfs = [df1,df2,df3]
df = reduce(DataFrame.unionAll, dfs)
</code>```

Is there a way to generalize this to non-explicit dataframe names?

答:
Thanks everyone! To sum up - the solution uses Reduce and unionAll:</p>
```<code>from functools import reduce
from pyspark.sql import DataFrame

SeriesAppend=[]

for item in series_list:
    # Filter for select item
    series = test_df.where(col("ID").isin([item]))
    # Sort time series
    series_sorted = series.sort(series.ID,
    series.date).persist()
    # Calculate rolling median
    series_sorted = series_sorted.withColumn("list",
         collect_list("metric").over(w)) \
         .withColumn("rolling_median", median_udf("list"))

    SeriesAppend.append(series_sorted)

df_series = reduce(DataFrame.unionAll, SeriesAppend)
</code>```

Body:
I am performing a rolling median calculation on individual time series dataframes, then I want to concat/append the results.

# UDF for rolling median
median_udf = udf(lambda x: float(np.median(x)), FloatType())

series_list = ['0620', '5914']
SeriesAppend=[]

for item in series_list:
    # Filter for select item
    series = test_df.where(col("ID").isin([item]))
    # Sort time series
    series_sorted = series.sort(series.ID,
    series.date).persist()
    # Calculate rolling median
    series_sorted = series_sorted.withColumn("list",
        collect_list("metric").over(w)) \
        .withColumn("rolling_median", median_udf("list"))

    SeriesAppend.append(series_sorted)

SeriesAppend

[DataFrame[ntwrk_genre_cd: string, date: date, mkt_cd: string, syscode: string, ntwrk_cd: string, syscode_ntwrk: string, metric: double, list: array, rolling_median: float], DataFrame[ntwrk_genre_cd: string, date: date, mkt_cd: string, syscode: string, ntwrk_cd: string, syscode_ntwrk: string, metric: double, list: array, rolling_median: float]]

When I attempt to .show():

'list' object has no attribute 'show'
Traceback (most recent call last):
AttributeError: 'list' object has no attribute 'show'

I realize this is saying the object is a list of dataframes. How do I convert to a single dataframe?

I know that the following solution works for an explicit number of dataframes, but I want my for-loop to be agnostic to the number of dataframes:

from functools import reduce
from pyspark.sql import DataFrame

dfs = [df1,df2,df3]
df = reduce(DataFrame.unionAll, dfs)

Is there a way to generalize this to non-explicit dataframe names?

Body:
Thanks everyone! To sum up - the solution uses Reduce and unionAll:

from functools import reduce
from pyspark.sql import DataFrame

SeriesAppend=[]

for item in series_list:
    # Filter for select item
    series = test_df.where(col("ID").isin([item]))
    # Sort time series
    series_sorted = series.sort(series.ID,
    series.date).persist()
    # Calculate rolling median
    series_sorted = series_sorted.withColumn("list",
         collect_list("metric").over(w)) \
         .withColumn("rolling_median", median_udf("list"))

    SeriesAppend.append(series_sorted)

df_series = reduce(DataFrame.unionAll, SeriesAppend)


问:
How I can use infinite scrolling in the webpage where I want it?
I am using an infinite scrolling jQuery plugin to implement a Twitter-like paging feature. Now, when I click on the more link, the request goes to server and it gives the response as HTML. First I tries using jQuery templates, and later I changed everything because I found nothing online to do that using JSON.

Well, now I have a problem that only the code does not append the response to the existing content on the page. It just sends the request and never appends to document's existing mockup.

Demo of plugin: http://www.infinite-scroll.com/trigger.html

I want to have code like this

```<code><div id="result">
    <ul>
        <li>
        </li>
        <li>
        </li>
        <li>
        </li>
        <li>
        </li>
    </ul>
</div>
</code>```

I need it that when user clicks on the more link, then more 'li's come from response and append to the 'li' inside of the result 'ul'.

```<code> $('#result ul').infinitescroll({
        navSelector: "a#next:last",
        // selector for the paged navigation (it will be hidden)
        nextSelector: "a#next:last",
        // selector for the NEXT link (to page 2)
        itemSelector: "#result ul"
        // selector for all items you'll retrieve
    });

    // kill scroll binding
    $(window).unbind('.infscr');

    // hook up the manual click guy.
    $('a#next').click(function () {
        $(document).trigger('retrieve.infscr');
        return false;
    });

    // remove the paginator when we're done.
    $(document).ajaxError(function (e, xhr, opt) {
    });
</code>```

答:
You don't even need a plugin to accomplish this. This is done with some simple lines of jQuery:

Example: http://jsfiddle.net/6fnTT/9/

```<code>$("a").live("click", function(){
    var data = "<li style='display:none'>Text3</li>";

    $("ul").append(data);
    $("li:hidden").fadeIn('slow');
});
</code>```

data might be anything (just be sure it is invisible to have the fade effect and you need to edit the li:hidden). E.g. it could be the result of an ajax request. Depending on the type of result (e.g. html or json) you would need to prepare it to make it fit into your html.

If you have trouble with your ajax response please post the code.

OwnerDisplayName: delete my account

Body:
I am using an infinite scrolling jQuery plugin to implement a Twitter-like paging feature. Now, when I click on the more link, the request goes to server and it gives the response as HTML. First I tries using jQuery templates, and later I changed everything because I found nothing online to do that using JSON.

Well, now I have a problem that only the code does not append the response to the existing content on the page. It just sends the request and never appends to document's existing mockup.

Demo of plugin: http://www.infinite-scroll.com/trigger.html

I want to have code like this

I need it that when user clicks on the more link, then more 'li's come from response and append to the 'li' inside of the result 'ul'.

 $('#result ul').infinitescroll({
        navSelector: "a#next:last",
        // selector for the paged navigation (it will be hidden)
        nextSelector: "a#next:last",
        // selector for the NEXT link (to page 2)
        itemSelector: "#result ul"
        // selector for all items you'll retrieve
    });

    // kill scroll binding
    $(window).unbind('.infscr');

    // hook up the manual click guy.
    $('a#next').click(function () {
        $(document).trigger('retrieve.infscr');
        return false;
    });

    // remove the paginator when we're done.
    $(document).ajaxError(function (e, xhr, opt) {
    });

Body:
You don't even need a plugin to accomplish this. This is done with some simple lines of jQuery:

Example: http://jsfiddle.net/6fnTT/9/

$("a").live("click", function(){
    var data = "<li style='display:none'>Text3</li>";

    $("ul").append(data);
    $("li:hidden").fadeIn('slow');
});

data might be anything (just be sure it is invisible to have the fade effect and you need to edit the li:hidden). E.g. it could be the result of an ajax request. Depending on the type of result (e.g. html or json) you would need to prepare it to make it fit into your html.

If you have trouble with your ajax response please post the code.


问:
Using Node.JS, how do I read a JSON file into (server) memory?

Background

I am doing some experimentation with Node.js and would like to read a JSON object, either from a text file or a .js file (which is better??) into memory so that I can access that object quickly from code.  I realize that there are things like Mongo, Alfred, etc out there, but that is not what I need right now.

Question

How do I read a JSON object out of a text or js file and into server memory using JavaScript/Node?

答:
Using fs-extra package is quite simple:

Sync:

```<code>const fs = require('fs-extra')

const packageObj = fs.readJsonSync('./package.json')
console.log(packageObj.version)
</code>```

Async:

```<code>const fs = require('fs-extra')

const packageObj = await fs.readJson('./package.json')
console.log(packageObj.version)
</code>```

Body:
Using fs-extra package is quite simple:

Sync:

const fs = require('fs-extra')

const packageObj = fs.readJsonSync('./package.json')
console.log(packageObj.version)

Async:

const fs = require('fs-extra')

const packageObj = await fs.readJson('./package.json')
console.log(packageObj.version)


问:
How to put two children of Kendo grid hierarchy into tab?
I have one parent table and two child tables in hierarchy. What I want is to have a design that the child table was in seperate tab.

This is the sample of what I've already tried. https://dojo.telerik.com/ubiZewAh

答:
I think the person who down voted was maybe looking for more info.  If I understand correctly you want each table within it's own tab.  Does not appear you are using bootstrap.  However, since you are in control of the template that is used for the data you will need to provide this functionality yourself. Upon clicking the arrow the data will be fetched.  So you will need to add a tab structure and default the first table as shown and all others as hidden. You almost have it but you need to visually show some tabs on the screen.  See HTML below for how your template should be set up. I will leave it up to you to style everything.  I am just going to give you functionality.

```<code><div id="detail-template" class="template-container">
    <div class="tabs">
       <div class="tab" data-tab-for="evidence">Evidence</div>
       <div class="tab" data-tab-for="notes">Notes</div>
    </div>
    <div role="tabpanel" class='tab-pane' id="evidence">
        <div class="evidence-grid"></div>
    </div>
    <div role="tabpanel" class='tab-pane' id="notes" style="display:none'>
        <div class="notes-grid"></div>
    </div>
</div>

//Jquery
$(document).ready(function () {
    $('#case-grid').on('click', '.tab', tabClicked);
});

function tabClicked(e) {
    var elClicked = $(this);

    //Hide all panes then show correct one
    $('.tab-pane').hide();
    var paneToShow = elClicked.data('tabFor');
    $('#' + paneToShow).show();

    //I would instead use the active flag on the tabs themselves
    //Style them however you want
    //Take the style off all tabs then add to correct one.
    $('.tab').removeClass('active');
    $(this).addClass('active');
}
</code>```

If you want to save yourself some trips to the backend when you do not need to I would not load the child grids upon loading of the grid init.  I would instead on click of the tab.  Find the grid within the tab pane selected and fetch the data at that time.  for example if the user never looks at the notes tab then there is no reason to go get it.  Unless you just want to prerender it with the expectation they will.  Also, you may want to change the class references I have within the tabClicked function to be relative to be sure we are only updating the correct one.  For example,

Change
    $('.tab-pane').hide();
To
    $('.tab-pane', elClicked.closest('.template-container')).hide();

After looking over my answer you may want to use class references everywhere since the template is used multiple times.  I didn't look at the generated code of kendo.  However, upon closing the row the DOM of the child grids are not removed. Therefore, with jquery it will modify all with the same id.  So for example your panes have id of evidence and notes.  You may want to make these data attributes and then just like I said above reference them relative to the clicked element(tab)

Body:
I think the person who down voted was maybe looking for more info.  If I understand correctly you want each table within it's own tab.  Does not appear you are using bootstrap.  However, since you are in control of the template that is used for the data you will need to provide this functionality yourself. Upon clicking the arrow the data will be fetched.  So you will need to add a tab structure and default the first table as shown and all others as hidden. You almost have it but you need to visually show some tabs on the screen.  See HTML below for how your template should be set up. I will leave it up to you to style everything.  I am just going to give you functionality.

<div id="detail-template" class="template-container">
    <div class="tabs">
       <div class="tab" data-tab-for="evidence">Evidence</div>
       <div class="tab" data-tab-for="notes">Notes</div>
    </div>
    <div role="tabpanel" class='tab-pane' id="evidence">
        <div class="evidence-grid"></div>
    </div>
    <div role="tabpanel" class='tab-pane' id="notes" style="display:none'>
        <div class="notes-grid"></div>
    </div>
</div>

//Jquery
$(document).ready(function () {
    $('#case-grid').on('click', '.tab', tabClicked);
});

function tabClicked(e) {
    var elClicked = $(this);

    //Hide all panes then show correct one
    $('.tab-pane').hide();
    var paneToShow = elClicked.data('tabFor');
    $('#' + paneToShow).show();

    //I would instead use the active flag on the tabs themselves
    //Style them however you want
    //Take the style off all tabs then add to correct one.
    $('.tab').removeClass('active');
    $(this).addClass('active');
}

If you want to save yourself some trips to the backend when you do not need to I would not load the child grids upon loading of the grid init.  I would instead on click of the tab.  Find the grid within the tab pane selected and fetch the data at that time.  for example if the user never looks at the notes tab then there is no reason to go get it.  Unless you just want to prerender it with the expectation they will.  Also, you may want to change the class references I have within the tabClicked function to be relative to be sure we are only updating the correct one.  For example,

Change
    $('.tab-pane').hide();
To
    $('.tab-pane', elClicked.closest('.template-container')).hide();

After looking over my answer you may want to use class references everywhere since the template is used multiple times.  I didn't look at the generated code of kendo.  However, upon closing the row the DOM of the child grids are not removed. Therefore, with jquery it will modify all with the same id.  So for example your panes have id of evidence and notes.  You may want to make these data attributes and then just like I said above reference them relative to the clicked element(tab)


问:
curl response is not understandable
when i send curl request to get access_token the response or outcome is not human understandable

when my authentication is competed them my redirect url is transfer to list()

```<code>public function list()
{
      $url = 'https://login.mailchimp.com/oauth2/token';
      $data = [
        'grant_type' => 'authorization_code',
        'client_id' => 2xxxxx177380,
        'client_secret' => '4b02xxxx21dcd32d5406a7d',
        'redirect_uri' => 'http://127.0.0.1:8000/success',
        'code' => $_GET['code']
        ];
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_POST, 1);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     $response = curl_exec ($ch);
     $err = curl_error($ch);  //if you need
     curl_close ($ch);
     return $response;
    }
</code>```

this is what i got as result where redirect link is:http://127.0.0.1:8000/list?access_token=9be9d4b1d724a0b19c7f4aff677b2b69&expires_in=0 response:

��VJ-*�/R�R��+K��L�/J-,M-.Q��6�

答:
does this change anything?</p>

```<code>curl_setopt($ch, CURLOPT_HTTPHEADER, 'text/plain;charset=UTF-8');
curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
</code>```

Title: curl response is not understandable

Body:
when i send curl request to get access_token the response or outcome is not human understandable

when my authentication is competed them my redirect url is transfer to list()

public function list()
{
      $url = 'https://login.mailchimp.com/oauth2/token';
      $data = [
        'grant_type' => 'authorization_code',
        'client_id' => 2xxxxx177380,
        'client_secret' => '4b02xxxx21dcd32d5406a7d',
        'redirect_uri' => 'http://127.0.0.1:8000/success',
        'code' => $_GET['code']
        ];
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_POST, 1);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     $response = curl_exec ($ch);
     $err = curl_error($ch);  //if you need
     curl_close ($ch);
     return $response;
    }

this is what i got as result where redirect link is:http://127.0.0.1:8000/list?access_token=9be9d4b1d724a0b19c7f4aff677b2b69&expires_in=0 response:

��VJ-*�/R�R��+K��L�/J-,M-.Q��6�

Body:
does this change anything?

curl_setopt($ch, CURLOPT_HTTPHEADER, 'text/plain;charset=UTF-8');
curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');


问:
AWS S3 Bucket name already exists
I know this question has been asked before, but replies didn't really help my case.
I am trying to create a bucket in S3 and I always receive the 'Bucket name already exists' error. I tried any possible combination but no luck, also the format is compliant to the docs.

Any idea of what I am doing wrong?

Thanks

答:
So, I finally solved my issue.

As I stated in the description of my question, my problem was not the formatting or the validity of the bucket name, the name was also unique and not used. Weirdly enough, I could not create the bucket when signed in using Chrome, but I succeeded doing it using Edge.

One note for the happy down-voters: maybe you can share some of your wisdom explaining the reason for down-voting, so we can all learn from it.

Title: AWS S3 Bucket name already exists


问:
Exclude a property from unobstrusive client Validation with MVC 3
I have a class User, that have an Email property, like that :

```<code>public class User : Entity
{
...
    [Display(Name = "Email"), Required(ErrorMessage = "Required."), Remote("EmailExists", "User", ErrorMessage = "Email already in Use.")]
    public virtual string Email { get; set; }
...
}
</code>```

My View Create works fine with all the validation ...
But in my view Edit, my Email texbox is Readonly, so The user cant change the email...

The problem is my Remote validation EmailExists keeps firing...

Is there a way to exclude the Email client validation just in that case? Or maybe another solution?

Thanks

答: Best solution would be to render Email as text content(span, p, etc) in that particular case -  validations would not fire. This would be best accomplished with editor templates.  But if you don't wish to, you could use some javascript to remove rules on client side. Take a look at Plugins/Validation/rules - you would remove rule when textbox is readonly. But for me the first way is preferred option</p>

Body:
I have a class User, that have an Email property, like that :

public class User : Entity
{
...
    [Display(Name = "Email"), Required(ErrorMessage = "Required."), Remote("EmailExists", "User", ErrorMessage = "Email already in Use.")]
    public virtual string Email { get; set; }
...
}

My View Create works fine with all the validation ...
But in my view Edit, my Email texbox is Readonly, so The user cant change the email...

The problem is my Remote validation EmailExists keeps firing...

Is there a way to exclude the Email client validation just in that case? Or maybe another solution?

Thanks


问:
Subarray assignment: initialization with "{...}" expected for aggregate object error
What's a good explanation for the error on Line 1?

```<code>/* Line 0 */    int foo[10][10];
/* Line 1 */    int foo_alias_compile_error[] = foo[0];
/* Line 2 */    int foo_alias_also_errors[10] = foo[0];
/* Line 3 */    int * foo_alias_works = foo[0];
</code>```

The error on Line 2 doesn't really bother me, because I don't need to be able to repeat myself and re-declare the size of the array.  However, the error on Line 1 (initialization with "{...}" expected for aggregate object) kind of confuses me.  I get that the int foo_alias_compile_error[] is probably the "aggregate object".  I just don't get why the language is setup for that not to work.  I understand why Line 3 works, but it kind of feels unrepresentative -- it's an array, so I'd rather self-document it as an array.

答:
One might hope to think of Line 1 as creating a reference for the 0th entry of foo.  However, that's not how C++ works.  Rather, the assignment operator (=) is invoking a copy operation.  So, C++ is interpreting Line 1 as a directive to copy the elements of foo[0] into a new array inappropriately named foo_alias_compile_error.

This isn't what was meant -- one wanted a reference, not a copy.  So, it's good that C++ happens to have caused an error for an unrelated reason and saved one from oneself.

A viable solution is suggested by @FrançoisAndrieux.  Here's a fuller example showing that a reference (not a copy) can be made with int (&foo_reference)[10] = foo[0];.

```<code>int foo[10][10];
for (int i = 0; i < 10; ++i) {
    for (int j = 0; j < 10; ++j) {
        foo[i][j] = i + j * 10;
    }
}
int (&foo_reference)[10] = foo[0];

for (int j = 0; j < 10; ++j) {
    foo_reference[j] = 100 + j;
}

for (int i = 0; i < 10; ++i) {
    printf("foo   [0][%i] is %i\n", i, foo[0][i]);
    printf("foo_refer[%i] is %i\n", i, foo_reference[i]);
}
</code>```

Output Snippet

```<code>foo   [0][0] is 100
foo_alias[0] is 100
foo   [0][1] is 101
foo_alias[1] is 101
foo   [0][2] is 102
foo_alias[2] is 102
foo   [0][3] is 103
foo_alias[3] is 103
</code>```

Side-note

It's worth mentioning that functions that take arrays as arguments implicitly convert their array arguments into pointers (as is shown in Line 3).  So, that's one reason why one might incorrectly think something like Line 1 should work.

In other words, the following code

```<code>void barz(int arg[]) {
    arg[2] = 99999;
}

int another_array[] = {0, 1, 2, 3, 4};
barz(another_array);
printf("another_array[2] is %i\n", another_array[2]);
</code>```

"Correctly" prints 99999, not 2.

Body:
What's a good explanation for the error on Line 1?

/* Line 0 */    int foo[10][10];
/* Line 1 */    int foo_alias_compile_error[] = foo[0];
/* Line 2 */    int foo_alias_also_errors[10] = foo[0];
/* Line 3 */    int * foo_alias_works = foo[0];

The error on Line 2 doesn't really bother me, because I don't need to be able to repeat myself and re-declare the size of the array.  However, the error on Line 1 (initialization with "{...}" expected for aggregate object) kind of confuses me.  I get that the int foo_alias_compile_error[] is probably the "aggregate object".  I just don't get why the language is setup for that not to work.  I understand why Line 3 works, but it kind of feels unrepresentative -- it's an array, so I'd rather self-document it as an array.

Body:
One might hope to think of Line 1 as creating a reference for the 0th entry of foo.  However, that's not how C++ works.  Rather, the assignment operator (=) is invoking a copy operation.  So, C++ is interpreting Line 1 as a directive to copy the elements of foo[0] into a new array inappropriately named foo_alias_compile_error.

This isn't what was meant -- one wanted a reference, not a copy.  So, it's good that C++ happens to have caused an error for an unrelated reason and saved one from oneself.

A viable solution is suggested by @FrançoisAndrieux.  Here's a fuller example showing that a reference (not a copy) can be made with int (&foo_reference)[10] = foo[0];.

int foo[10][10];
for (int i = 0; i < 10; ++i) {
    for (int j = 0; j < 10; ++j) {
        foo[i][j] = i + j * 10;
    }
}
int (&foo_reference)[10] = foo[0];

for (int j = 0; j < 10; ++j) {
    foo_reference[j] = 100 + j;
}

for (int i = 0; i < 10; ++i) {
    printf("foo   [0][%i] is %i\n", i, foo[0][i]);
    printf("foo_refer[%i] is %i\n", i, foo_reference[i]);
}

Output Snippet

foo   [0][0] is 100
foo_alias[0] is 100
foo   [0][1] is 101
foo_alias[1] is 101
foo   [0][2] is 102
foo_alias[2] is 102
foo   [0][3] is 103
foo_alias[3] is 103

Side-note

It's worth mentioning that functions that take arrays as arguments implicitly convert their array arguments into pointers (as is shown in Line 3).  So, that's one reason why one might incorrectly think something like Line 1 should work.

In other words, the following code

void barz(int arg[]) {
    arg[2] = 99999;
}

int another_array[] = {0, 1, 2, 3, 4};
barz(another_array);
printf("another_array[2] is %i\n", another_array[2]);

"Correctly" prints 99999, not 2.


问:
R - Removing the same name in two columns of a data frame
I am working with a data frame that has two columns, name and spouse. I am trying to calculate the interracial marriage frequency, but I need to remove repeated registers.
When I have the name of a creature I need to keep this register in the data frame but remove the register where that creature name is the spouse name. I have this following data sample:

```<code>                    name                      spouse
15                  Finarfin                  EÃ¤rwen
6             Tar-VanimeldÃ«                  Herucalmo
17                   Faramir                  owyn
8               Tar-Meneldur                  Almarian
14   Finduilas of Dol Amroth                  Denethor II
12                    FinwÃ«                  MÃriel SerindÃ« then ,Indis
9              Tar-AncalimÃ«                  Hallacar
7                Tar-MÃriel                   Ar-PharazÃ´n
5          Tarannon Falastur                  BerÃºthiel
21             Rufus Burrows                  Asphodel Brandybuck
2                     Angrod                  EldalÃ³tÃ«
4               Ar-GimilzÃ´r                  InzilbÃªth
19 Lobelia Sackville-Baggins                  Otho Sackville-Baggins
25            Mrs. Proudfoot                  Odo Proudfoot
22            Rudigar Bolger                  Belba Baggins
24             Odo Proudfoot                  Mrs. Proudfoot
3               Ar-PharazÃ´n                  Tar-MÃriel
13                 Fingolfin                  AnairÃ«
18                SilmariÃ«n                  Elatan
23           Rowan Greenhand                  Belba Baggins
20                     RÃan                   Huor
1                     Adanel                  Belemir
16           Fastolph Bolger                  Pansy Baggins
10         Morwen Steelsheen                  Thengel
11              Tar-Aldarion                  Erendis
25              Belemir                       Adanel
</code>```

For example, I ran the code and in line 1 it caught name Adanel and got Belemir as its spouse, so I need to keep line 1, but remove line 25, because with that I will avoid duplicated data.

I have tried this following code:

```<code>interacialMariage <-data %>% filter(spouse != name) %>% select(name, spouse)
</code>```

How can I get the same spouse name register out of the data frame registers?

P.S.: I would need it to avoid case sensitive (Belemir == belemir) so that I don't have problems in the future.

Thanks!

答:
My attempt with tidyverse:

```<code>library(tidyverse)

dat %>%
  mutate(id = 1:n()) %>%           # add id to label the pairs
  gather('key', 'name', -id) %>%   # transform: key (name | spouse), name, id
  group_by(name) %>%               # group by unique name to find duplicated
  top_n(-1, wt = id) %>%           # if name > 1, take row with the lower id
  spread(key, name) %>%            # spread data to original format
  select(-id)                      # remove id's

# # A tibble: 3 x 2
#   name              spouse
#   <chr>             <chr>
# 1 Adanel            Belemir
# 2 Fastolph Bolger   Pansy Baggins
# 3 Morwen Steelsheen Thengel
</code>```

Data:

```<code>dat <- data.frame(
  name   = c("Adanel",  "Fastolph Bolger", "Morwen Steelsheen", "Belemir"),
  spouse = c("Belemir", "Pansy Baggins",   "Thengel",           "Adanel" ),
  stringsAsFactors = F
)
</code>```

Body:
I am working with a data frame that has two columns, name and spouse. I am trying to calculate the interracial marriage frequency, but I need to remove repeated registers.
When I have the name of a creature I need to keep this register in the data frame but remove the register where that creature name is the spouse name. I have this following data sample:

                    name                      spouse
15                  Finarfin                  EÃ¤rwen
6             Tar-VanimeldÃ«                  Herucalmo
17                   Faramir                  owyn
8               Tar-Meneldur                  Almarian
14   Finduilas of Dol Amroth                  Denethor II
12                    FinwÃ«                  MÃriel SerindÃ« then ,Indis
9              Tar-AncalimÃ«                  Hallacar
7                Tar-MÃriel                   Ar-PharazÃ´n
5          Tarannon Falastur                  BerÃºthiel
21             Rufus Burrows                  Asphodel Brandybuck
2                     Angrod                  EldalÃ³tÃ«
4               Ar-GimilzÃ´r                  InzilbÃªth
19 Lobelia Sackville-Baggins                  Otho Sackville-Baggins
25            Mrs. Proudfoot                  Odo Proudfoot
22            Rudigar Bolger                  Belba Baggins
24             Odo Proudfoot                  Mrs. Proudfoot
3               Ar-PharazÃ´n                  Tar-MÃriel
13                 Fingolfin                  AnairÃ«
18                SilmariÃ«n                  Elatan
23           Rowan Greenhand                  Belba Baggins
20                     RÃan                   Huor
1                     Adanel                  Belemir
16           Fastolph Bolger                  Pansy Baggins
10         Morwen Steelsheen                  Thengel
11              Tar-Aldarion                  Erendis
25              Belemir                       Adanel

For example, I ran the code and in line 1 it caught name Adanel and got Belemir as its spouse, so I need to keep line 1, but remove line 25, because with that I will avoid duplicated data.

I have tried this following code:

interacialMariage <-data %>% filter(spouse != name) %>% select(name, spouse)

How can I get the same spouse name register out of the data frame registers?

P.S.: I would need it to avoid case sensitive (Belemir == belemir) so that I don't have problems in the future.

Thanks!

Body:
My attempt with tidyverse:

library(tidyverse)

dat %>%
  mutate(id = 1:n()) %>%           # add id to label the pairs
  gather('key', 'name', -id) %>%   # transform: key (name | spouse), name, id
  group_by(name) %>%               # group by unique name to find duplicated
  top_n(-1, wt = id) %>%           # if name > 1, take row with the lower id
  spread(key, name) %>%            # spread data to original format
  select(-id)                      # remove id's

# # A tibble: 3 x 2
#   name              spouse
#   <chr>             <chr>
# 1 Adanel            Belemir
# 2 Fastolph Bolger   Pansy Baggins
# 3 Morwen Steelsheen Thengel

Data:

dat <- data.frame(
  name   = c("Adanel",  "Fastolph Bolger", "Morwen Steelsheen", "Belemir"),
  spouse = c("Belemir", "Pansy Baggins",   "Thengel",           "Adanel" ),
  stringsAsFactors = F
)


问:
jQuery combine multiple elements
I was experimenting with jQuery and came across a question. Can I use an actual selector with existing element as a combined selector for jQuery?

So, suppose I've created a DIV element on-the-fly:

```<code>var $div = $('<div>')
               .css('position', 'absolute')
               .hide();    // Just to be short

$('body').append($div);
</code>```

And I want to show it when user hovers over P elements / paragraphs (at the cursor position):

```<code>$('p').hover(function(e) {

    // Change the position of $div with regards of cursor position

    $div.show();
}, function(e) {
    $div.hide();
});
</code>```

BUT also I want to apply this hover handlers to $div itself. So instead of duplicating my code, I want to do something like this:

```<code>$('p', $div).hover(...)
</code>```

which will select $div element along with all P elements.

I know I can write functions separately and pass the names as arguments to hover function.

Is there any solution to this kind of situation in jQuery? or is there a more accurate solution?

答:
If you have multiple elements to combine you don't wan to do

```<code>$('p').add($div1).add($div2).add($div3).add($div4).add($div5).add($div6) ...
</code>```

Instead you want to convert a JavaScript array into a jQuery object

```<code>$( $.map([x,y,z], a => [...$.makeArray(a)]) )
</code>```

Source: Merging jQuery objects

Title: jQuery combine multiple elements

Body:
I was experimenting with jQuery and came across a question. Can I use an actual selector with existing element as a combined selector for jQuery?

So, suppose I've created a DIV element on-the-fly:

var $div = $('
')
               .css('position', 'absolute')
               .hide();    // Just to be short

$('body').append($div);

And I want to show it when user hovers over P elements / paragraphs (at the cursor position):

$('p').hover(function(e) {

    // Change the position of $div with regards of cursor position

    $div.show();
}, function(e) {
    $div.hide();
});

BUT also I want to apply this hover handlers to $div itself. So instead of duplicating my code, I want to do something like this:

$('p', $div).hover(...)

which will select $div element along with all P elements.

I know I can write functions separately and pass the names as arguments to hover function.

Is there any solution to this kind of situation in jQuery? or is there a more accurate solution?

Body:
If you have multiple elements to combine you don't wan to do

$('p').add($div1).add($div2).add($div3).add($div4).add($div5).add($div6) ...

Instead you want to convert a JavaScript array into a jQuery object

$( $.map([x,y,z], a => [...$.makeArray(a)]) )

Source: Merging jQuery objects


问:
How to refactor method to replace OrganizationServiceProxy with IOrganizationService
I'm attempting to refactor my code so that I can unit test using fakexrmeasy.

As part of the suggested refactor mentioned here, I've attempted to pass IOrganizationService into all of my classes and methods. However, some of my classes use variables and methods that IOrganizationService doesn't have, such as Timeout. I'm trying to find a way to refactor to use IOrganizationService without losing functionality.

This is how it exists before refactoring.

```<code>class testClass () {

    public void testMethod(OrganizationServiceProxy service) {
        service.Timeout = new TimeSpan(0, 15, 0);
    }

}
</code>```

This is after the refactor.
I've tried casting IOrganizationService to OrganizationServiceProxy, but the faked service context can't handle this cast. An exception is thrown.

```<code>class testClass () {

    public void testMethod(IOrganizationService service) {
        var serviceProxy = (OrganizationServiceProxy) service; //This breaks when given a fake context
        service.Timeout = new TimeSpan(0, 15, 0);
    }

}
</code>```

I've tried using an IOrganizationServiceFactory, as suggested in this post. The problem is, factory.CreateOrganizationService() generates an IOrganizationService, not an OrganizationSeriviceProxy.

How can I refactor to use IOrganizationService instead of OrganizationServiceProxy without losing functionality? I'm guessing I might have to implement the IOrganizationService as an OrganizationServiceProxy somehow.

答:
Could something like this be viable?

```<code>public class OrganizationServiceProxy : IServiceProxy
  {
    public int SomeProp
    {
      get
      {
        return 1;
      }

      set
      {
      }
    }

    public TimeSpan Timeout
    {
      get
      {
        return new TimeSpan();
      }

      set
      {
      }
    }

    public void SomeMethod()
    {
    }
  }
  public interface IServiceProxy : IOrganizationService
  {
    TimeSpan Timeout { get; set; }
  }

  public interface IOrganizationService
  {
    void SomeMethod();
    int SomeProp { get; set; }
  }
</code>```

Since OrganizationServiceProxy implements IServiceProxy (which in turn implements IOrganizationService) you could check if the object you passed in implements the IServiceProxy interface and do your work inside of the if.

```<code>private void testMethod(IOrganizationService someService)
{
   if(someService is IServiceProxy)
   {
     IServiceProxy tempProxy = someService as IServiceProxy;
     tempProxy.Timeout = new TimeSpan();
   }
}
</code>```

Body:
I'm attempting to refactor my code so that I can unit test using fakexrmeasy.

As part of the suggested refactor mentioned here, I've attempted to pass IOrganizationService into all of my classes and methods. However, some of my classes use variables and methods that IOrganizationService doesn't have, such as Timeout. I'm trying to find a way to refactor to use IOrganizationService without losing functionality.

This is how it exists before refactoring.

class testClass () {

    public void testMethod(OrganizationServiceProxy service) {
        service.Timeout = new TimeSpan(0, 15, 0);
    }

}

This is after the refactor.
I've tried casting IOrganizationService to OrganizationServiceProxy, but the faked service context can't handle this cast. An exception is thrown.

class testClass () {

    public void testMethod(IOrganizationService service) {
        var serviceProxy = (OrganizationServiceProxy) service; //This breaks when given a fake context
        service.Timeout = new TimeSpan(0, 15, 0);
    }

}

I've tried using an IOrganizationServiceFactory, as suggested in this post. The problem is, factory.CreateOrganizationService() generates an IOrganizationService, not an OrganizationSeriviceProxy.

How can I refactor to use IOrganizationService instead of OrganizationServiceProxy without losing functionality? I'm guessing I might have to implement the IOrganizationService as an OrganizationServiceProxy somehow.

Body:
Could something like this be viable?

public class OrganizationServiceProxy : IServiceProxy
  {
    public int SomeProp
    {
      get
      {
        return 1;
      }

      set
      {
      }
    }

    public TimeSpan Timeout
    {
      get
      {
        return new TimeSpan();
      }

      set
      {
      }
    }

    public void SomeMethod()
    {
    }
  }
  public interface IServiceProxy : IOrganizationService
  {
    TimeSpan Timeout { get; set; }
  }

  public interface IOrganizationService
  {
    void SomeMethod();
    int SomeProp { get; set; }
  }

Since OrganizationServiceProxy implements IServiceProxy (which in turn implements IOrganizationService) you could check if the object you passed in implements the IServiceProxy interface and do your work inside of the if.

private void testMethod(IOrganizationService someService)
{
   if(someService is IServiceProxy)
   {
     IServiceProxy tempProxy = someService as IServiceProxy;
     tempProxy.Timeout = new TimeSpan();
   }
}


问:
Kafka rest api to get details of a consumer group
I am looking for a kafka rest api which will list the same details as

kafka-consumer-groups.sh  - - describe

Would return, basically i am trying to get the details of offset of each partition and its lag for a particular consumer group

答:
There's several tools outside of Kafka to do this

Remora https://github.com/zalando-incubator/remora

LinkedIn Burrow

Various Prometheus Kafka lag exporters


Title: Pandas: groupby is not computing pct_change properly

Body:
My data is:

>>> prices = pandas.DataFrame(
{"StkCode":["StockA","StockA","StockA","StockA","StockA","StockB","StockB","StockB","StockB","StockB","StockC","StockC","StockC","StockC","StockC",],
"Price":[1035.23, 1032.47, 1011.78, 1010.59, 1016.03, 1007.95, 1022.75, 1021.52, 1026.11, 1027.04, 1030.58, 1030.42, 1036.24, 1015.00, 1015.20]}
)

Which gives:

      Price StkCode
0   1035.23  StockA
1   1032.47  StockA
2   1011.78  StockA
3   1010.59  StockA
4   1016.03  StockA
5   1007.95  StockB
6   1022.75  StockB
7   1021.52  StockB
8   1026.11  StockB
9   1027.04  StockB
10  1030.58  StockC
11  1030.42  StockC
12  1036.24  StockC
13  1015.00  StockC
14  1015.20  StockC

Then, I call:

>>> prices["Return"] = prices.groupby("StkCode")["Price"].pct_change(1)

I expect:

      Price StkCode    Return
0   1035.23  StockA       NaN
1   1032.47  StockA -0.002666
2   1011.78  StockA -0.020039
3   1010.59  StockA -0.001176
4   1016.03  StockA  0.005383
5   1007.95  StockB       NaN
6   1022.75  StockB  0.014683
7   1021.52  StockB -0.001203
8   1026.11  StockB  0.004493
9   1027.04  StockB  0.000906
10  1030.58  StockC       NaN
11  1030.42  StockC -0.000155
12  1036.24  StockC  0.005648
13  1015.00  StockC -0.020497
14  1015.20  StockC  0.000197

But, I actually get:

    Price   StkCode Return
0   1035.23 StockA  NaN
1   1032.47 StockA  -0.002666
2   1011.78 StockA  -0.020039
3   1010.59 StockA  -0.001176
4   1016.03 StockA  0.005383
5   1007.95 StockB  -0.007953
6   1022.75 StockB  0.014683
7   1021.52 StockB  -0.001203
8   1026.11 StockB  0.004493
9   1027.04 StockB  0.000906
10  1030.58 StockC  0.003447
11  1030.42 StockC  -0.000155
12  1036.24 StockC  0.005648
13  1015.00 StockC  -0.020497
14  1015.20 StockC  0.000197

It looks like returns are being computed for the first instance of StockB and StockC.

I'm using Python 2.7.  Is there something wrong with my code that it's disregarding the groupby?

Thanks!

Body:
DataFrame's loc method will apply those values correctly:

prices.loc[:, 'Return'] = prices.groupby("StkCode")["Price"].pct_change(1)

    Price   StkCode Return
0   1035.23 StockA  NaN
1   1032.47 StockA  -0.002666
2   1011.78 StockA  -0.020039
3   1010.59 StockA  -0.001176
4   1016.03 StockA  0.005383
5   1007.95 StockB  NaN
6   1022.75 StockB  0.014683
7   1021.52 StockB  -0.001203
8   1026.11 StockB  0.004493
9   1027.04 StockB  0.000906
10  1030.58 StockC  NaN
11  1030.42 StockC  -0.000155
12  1036.24 StockC  0.005648
13  1015.00 StockC  -0.020497
14  1015.20 StockC  0.000197


问:
select with index on DataTable?
After I get DataTable from sqlAdapter I'm closing connection.
If I preform SELECT from this DataTable, does the select use the index
I created in the DB?

what code do I need to write for using the index?

答: If you've already selected your data from the database and placed it into an in-memory table, you won't have access to the db's indicies. However, because the table is now in-memory, you won't need those indicies, as the lookup performance will be improved due to the fact that it is an in-memory search.

Title: select with index on DataTable?


问:
immutablsjs order of Map.entrySeq
I have following piece of code

[array with keys].reduce((acc, key) => acc.set(key, 1), Map());

Map is immutablejs Map not js Map. When I call Map.entrySeq() on it it always gives me the same order in which I executed set() in reduce.

Can I realy on this order?

答:
The docs of immutable.js is good, you can rely on it. To quote:

```<code>Iteration order of a Map is undefined, however is stable.
Multiple iterations of the same Map will iterate in the same order.
</code>```

So the answer is yes. Note that your piece of code has terrible performance, it creates a new map N times.

Use withMutations to execute all manipulations on temporary, mutable map:

```<code>Immutable.Map().withMutations(mutableMap => {
  [array with keys].reduce((acc, key) => acc.set(key, 1), mutableMap);
});
</code>```

Title: immutablsjs order of Map.entrySeq

Body:
The docs of immutable.js is good, you can rely on it. To quote:

Iteration order of a Map is undefined, however is stable.
Multiple iterations of the same Map will iterate in the same order.

So the answer is yes. Note that your piece of code has terrible performance, it creates a new map N times.

Use withMutations to execute all manipulations on temporary, mutable map:

Immutable.Map().withMutations(mutableMap => {
  [array with keys].reduce((acc, key) => acc.set(key, 1), mutableMap);
});


问:
UnsafeMutablePointer<Int8> from String in Swift
I'm using the dgeev algorithm from the LAPACK implementation in the Accelerate framework to calculate eigenvectors and eigenvalues of a matrix. Sadly the LAPACK functions are not described in the Apple Documentation with a mere link to http://netlib.org/lapack/faq.html included.

If you look it up, you will find that the first two arguments in dgeev are characters signifying whether to calculate eigenvectors or not. In Swift, it is asking for UnsafeMutablePointer<Int8>. When I simply use "N", I get an error. The dgeev function and the error are described in the following screenshot

What should I do to solve this?

答:
With Swift 4.2 and 5 you can use this similar approach

```<code>let str = "string"
let unsafePointer = UnsafeMutablePointer<Int8>(mutating: (str as NSString).utf8String)
</code>```

You can get the result from unsafePointer.

Body:
With Swift 4.2 and 5 you can use this similar approach

let str = "string"
let unsafePointer = UnsafeMutablePointer<Int8>(mutating: (str as NSString).utf8String)

You can get the result from unsafePointer.


问:
Unable to get bounding box of Geohash
I'm trying to get the bounding box (x,y coordinates) of geohashes using Python's geohash module.  I'm able to successfully read in the geohashes and get their centroid, but when I try to use the geohash.bbox() method, it fails.  Here's code:

```<code>#import modules
import Geohash
import csv

    dataArray = []

    with open('C:\Users\Desktop\data.csv') as csvfile:
        readCSV = csv.reader(csvfile, delimiter=',')
        for row in readCSV:
            geoHash = row[0] # this is the geohash identifier
            trips = row[1]
            share_of_trips = row[2]
            time_ID = row[3]
            perc_trips = row[4]
            geoStr = str(geoHash)
            latLong = Geohash.decode_exactly(geoStr)
            # Get Bounding Box
            boundingBox = Geohash.bbox(geoStr)
            print boundingBox
</code>```

I'm able to successfully print the lat long pairs, but unable to get the bounding box.  The documentation says:

The error I'm getting is:

```<code>AttributeError: 'module' object has no attribute 'bbox'
</code>```

When I use geohash, as opposed to Geohash, it says geohash is not defined.

Any thoughts?  Thank you in advance.  I've read the documentation:

geohash.bbox(hashcode) Bounding box for a geohash hashcode. This method returns a dictionary with keys of "s", "e", "w" and "n" which means South, East, West and North respectively.

```<code>>>> geohash.bbox('ezs42')
{'s': 42.5830078125, 'e': -5.5810546875, 'w': -5.625, 'n': 42.626953125}
</code>```

答:
but when I try to use the geohash.bbox() method, it fails

Your code has Geohash.bbox() which is not the same thing.

When I use geohash, as opposed to Geohash, it says geohash is not defined.

That is because you have import Geohash. Maybe you need to change this to import geohash instead.

My google search for "python geohash" turns up at least two libraries. The documentation for one shows that you need to do import Geohash, but this library does not appear to have a bbox() function. The documentation for the second library has a bbox() function, but requires import geohash. I suggest you figure out which library you are using and look closely at the documentation for that library in order to determine correct usage.

Title: Unable to get bounding box of Geohash

Body:
I'm trying to get the bounding box (x,y coordinates) of geohashes using Python's geohash module.  I'm able to successfully read in the geohashes and get their centroid, but when I try to use the geohash.bbox() method, it fails.  Here's code:

#import modules
import Geohash
import csv

    dataArray = []

    with open('C:\Users\Desktop\data.csv') as csvfile:
        readCSV = csv.reader(csvfile, delimiter=',')
        for row in readCSV:
            geoHash = row[0] # this is the geohash identifier
            trips = row[1]
            share_of_trips = row[2]
            time_ID = row[3]
            perc_trips = row[4]
            geoStr = str(geoHash)
            latLong = Geohash.decode_exactly(geoStr)
            # Get Bounding Box
            boundingBox = Geohash.bbox(geoStr)
            print boundingBox

I'm able to successfully print the lat long pairs, but unable to get the bounding box.  The documentation says:

The error I'm getting is:

AttributeError: 'module' object has no attribute 'bbox'

When I use geohash, as opposed to Geohash, it says geohash is not defined.

Any thoughts?  Thank you in advance.  I've read the documentation:

geohash.bbox(hashcode) Bounding box for a geohash hashcode. This method returns a dictionary with keys of "s", "e", "w" and "n" which means South, East, West and North respectively.

>>> geohash.bbox('ezs42')
{'s': 42.5830078125, 'e': -5.5810546875, 'w': -5.625, 'n': 42.626953125}


问:
In Rails how to check if javascript file exists before using javascript_include_tag
In a rails 3.2 app, I would like to check for the existence of a javascript file in the asset pipeline before including the javascript_include_tag in a file.  Something like:

```<code><% if javascript_file_exists? %>
  <%= javascript_include_tag "#{controller_name}_controller" %>
<% end %>
</code>```

I would like to do this so that the absence of a javascript file will not result in an error.  Is there a way to do this?

答:
Catch the error:

```<code>    #/app/helpers/application_helpers.rb

    def javascript_include_tag_if_assets(*args)
      javascript_include_tag(*args)
    rescue Sprockets::Rails::Helper::AssetNotFound
      ''
    end
</code>```

Alternatively, since this asks to check before using the method, javascript_include_tag uses javascript_path so you might as well use it to check and then catch that error. This works for all javascript-like assets. For css-like assets, use stylesheet_path.

```<code>    #/app/helpers/application_helpers.rb

    def javascript_include_tag_if_assets(*files, **opts)
      files.each { |file| javascript_path(file) }
      javascript_include_tag(*files, **opts)
    rescue Sprockets::Rails::Helper::AssetNotFound
      ''
    end
</code>```

Body:
In a rails 3.2 app, I would like to check for the existence of a javascript file in the asset pipeline before including the javascript_include_tag in a file.  Something like:

<% if javascript_file_exists? %>
  <%= javascript_include_tag "#{controller_name}_controller" %>
<% end %>

I would like to do this so that the absence of a javascript file will not result in an error.  Is there a way to do this?

Body:
Catch the error:

    #/app/helpers/application_helpers.rb

    def javascript_include_tag_if_assets(*args)
      javascript_include_tag(*args)
    rescue Sprockets::Rails::Helper::AssetNotFound
      ''
    end

Alternatively, since this asks to check before using the method, javascript_include_tag uses javascript_path so you might as well use it to check and then catch that error. This works for all javascript-like assets. For css-like assets, use stylesheet_path.

    #/app/helpers/application_helpers.rb

    def javascript_include_tag_if_assets(*files, **opts)
      files.each { |file| javascript_path(file) }
      javascript_include_tag(*files, **opts)
    rescue Sprockets::Rails::Helper::AssetNotFound
      ''
    end


问:
Event handling after HTML injection with Vue.js
Vue is not registering event handler for HTML injected objects.  How do I do this manually or what is a better way to work around my problem?

Specifically, I send a query to my server to find a token in text and return the context (surrounding text) of that token as it exists in unstructured natural language.  The server also goes through the context and finds a list of those words that also happen to be in my token set.

When I render to my page I want all of these found tokens in the list to be clickable so that I can send the text of that token as a new search query.  The big problem I am having is my issue does not conform to a template.  The clickable text varies in number and positioning.

An example of what I am talking about is that my return may look like:

```<code>{
   "context": "When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected",
   "chunks": ['human events', 'one people', 'political bands']
}
</code>```

And the resulting output I am looking for is the sentence looks something like this in psuedocode:

```<code>When in the Course of <a @click='search("human events")'>human events</a>, it becomes necessary for <a @click='search("one people")'>one people</a> to dissolve the <a @click='search("political bands")'>political bands</a> which have connected
</code>```

This is what I have tried so far though the click handler is not registered and the function never gets called:

<v-flex xs10 v-html="addlink(context.context, context.chunks)"></v-flex>
```

<p>and in my methods section:</p>

```addlink: function(words, matchterms){
                for(var index in matchterms){
                    var regquery = matchterms[index].replace(this.regEscape, '\\$&');
                    var query = matchterms[index];
                    var regEx = new RegExp(regquery, "ig");
                    words = words.replace(regEx, '' + query + '');
                }
                return words;
            }
```

As I said, this does not work and I know why.  This is just showing that because of the nature of the problem is seems like regex is the correct solution but that gets me into a v-html injection situation.  Is there something I can do in Vue to register the event handlers or can some one tell me a better way to load this data so I keep my links inline with the sentence and make them functional as well?

答:
Here's one way you could approach it:

<template>

        <template v-for="segment in textSegments">

                {{ segment.text }}

            <template v-else>
                {{ segment.text }}
            </template>
        </template>

</template>

```

I've parsed the context text into an array of segments that can then be handled cleanly using Vue's template syntax.

I've used a single RegExp and split, which will not discard matches if you wrap them in a capture group, (...).

Going back to your original example, v-html only supports native HTML, not Vue template syntax. So you can add events using onclick attributes but not @click or v-on:click. However, using onclick wouldn't provide easy access to your search method, which is scoped to your component.

Body:
Vue is not registering event handler for HTML injected objects.  How do I do this manually or what is a better way to work around my problem?

Specifically, I send a query to my server to find a token in text and return the context (surrounding text) of that token as it exists in unstructured natural language.  The server also goes through the context and finds a list of those words that also happen to be in my token set.

When I render to my page I want all of these found tokens in the list to be clickable so that I can send the text of that token as a new search query.  The big problem I am having is my issue does not conform to a template.  The clickable text varies in number and positioning.

An example of what I am talking about is that my return may look like:

{
   "context": "When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected",
   "chunks": ['human events', 'one people', 'political bands']
}

And the resulting output I am looking for is the sentence looks something like this in psuedocode:

When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected

This is what I have tried so far though the click handler is not registered and the function never gets called:

<v-flex xs10 v-html="addlink(context.context, context.chunks)"></v-flex>

and in my methods section:

addlink: function(words, matchterms){
                for(var index in matchterms){
                    var regquery = matchterms[index].replace(this.regEscape, '\\$&');
                    var query = matchterms[index];
                    var regEx = new RegExp(regquery, "ig");
                    words = words.replace(regEx, '' + query + '');
                }
                return words;
            }

As I said, this does not work and I know why.  This is just showing that because of the nature of the problem is seems like regex is the correct solution but that gets me into a v-html injection situation.  Is there something I can do in Vue to register the event handlers or can some one tell me a better way to load this data so I keep my links inline with the sentence and make them functional as well?

Body:
Here's one way you could approach it:

<template>
    <div>
        <template v-for="segment in textSegments">
            <a v-if="segment.link" href="#" @click.prevent="search(segment.text)">
                {{ segment.text }}
            </a>
            <template v-else>
                {{ segment.text }}
            </template>
        </template>
    </div>
</template>

<script>
export default {
    data () {
        return {
            "context": "When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected",
            "chunks": ['human events', 'one people', 'political bands']
        }
    },

    computed: {
        textSegments () {
            const chunks = this.chunks

            // This needs escaping correctly
            const re = new RegExp('(' + chunks.join('|') + ')', 'gi')

            // The filter removes empty strings
            const segments = this.context.split(re).filter(text => text)

            return segments.map(segment => {
                return {
                    link: segment.match(re),
                    text: segment
                }
            })
        }
    },

    methods: {
        search (chunk) {
            console.log(chunk)
        }
    }
}
</script>

I've parsed the context text into an array of segments that can then be handled cleanly using Vue's template syntax.

I've used a single RegExp and split, which will not discard matches if you wrap them in a capture group, (...).

Going back to your original example, v-html only supports native HTML, not Vue template syntax. So you can add events using onclick attributes but not @click or v-on:click. However, using onclick wouldn't provide easy access to your search method, which is scoped to your component.


问:
Python Repo Cleanup
I have a script that I have almost 100% complete however there is just one more step that I can not figure out. My script currently checks the destination to see if the file already exists and if it does then the file from the source location is not moved over. The problem I am running into is that the code doesn't check all of the subdirectories as well just the root directory.

I am using os.walk to go through all of the files in the source folder but am not sure how to os.walk the destination folder and the source folder in conjunction with each other.

```<code>import time
import sys
import logging
import logging.config

def main():
    purge_files

def move_files(src_file):

    try:
        #Attempt to move files to dest
        shutil.move(src_file, dest)
        #making use of the OSError exception instead of FileExistsError due to older version of python not contaning that exception
    except OSError as e:
        #Log the files that have not been moved to the console
        logging.info(f'Files File already exists: {src_file}')
        print(f'File already exists: {src_file}')
        #os.remove to delete files that are already in dest repo
        os.remove(src_file)
        logging.warning(f'Deleting: {src_file}')

def file_loop(files, root):

    for file in files:
        #src_file is used to get the full path of everyfile
        src_file = os.path.join(root,file)

        #The two variables below are used to get the files creation date
        t = os.stat(src_file)
        c = t.st_ctime
        #If the file is older then cutoff code within the if statement executes

        if c<cutoff:

            move_files(src_file)
        #Log the file names that are not older then the cutoff and continue loop
        else:
            logging.info(f'File is not older than 14 days: {src_file}')
            continue

def purge_files():

    logging.info('invoke purge_files method')
    #Walk through root directory and all subdirectories
       for root, subdirs, files in os.walk(source):
          dst_dir = root.replace(source, dest)

           #Loop through files to grab every file
           file_loop(files, root)

       return files, root, subdirs

files, root, subdirs = purge_files()
</code>```

I expected the output to move all files from source to dest. Before the files are moved I expected to check all files in the dest location including subdir of dest if any of them are the same file as the source then they wont be moved to the dest. I do not want the folders that are in source. I just want all the files to be moved to the root directory.

答:
You might want to clean up your code, it is full of bugs. E.g. 'purge_files' instead of 'purge_files()' in main, indentation errors inside purge_files etc. Also the seemingly random newlines between the code makes it a bit awkward to read (for me at least) :)

EDIT: I quickly went over your code and changed a few things. Mainly variable names. I noticed that you had a few variables with undescriptive names ('i', 't', etc.) together with a comment describing what that variable meant. If you just change the variable name to something more descriptive, you don't need the comments and your code is even easier to rad. Note that I didn't test this code and tbh it probably does not even run (since that was not my goal but rather to show some of the style changes that I would suggest) :)

```<code>import os
import shutil
import time
import errno
import time
import sys
import logging
import logging.config

# NOTE: It is a convention to write constants in all caps
SOURCE = r'C:\Users\Desktop\BetaSource'
DEST = r'C:\Users\Desktop\BetaDest'
#Gets the current time from the time module
now = time.time()
#Timer of when to purge files
cutoff = now - (14 * 86400)
all_sources = []
all_dest_dirty = []
logging.basicConfig(level = logging.INFO,
                    filename = time.strftime("main-%Y-%m-%d.log"))

def main():
    # NOTE: Why is this function called / does it exist? It only sets a global
    # 'dest_files' which is never used...
    dest_files()
    purge_files()

# I used the dess_files function to get all of the destination files
def dest_files():
    for root, subdirs, files in os.walk(DEST):
        for file in files:
            # NOTE: Is it really necessary to use a global here?
            global all_dirty
            all_dirty.append(files)

def purge_files():
    logging.info('invoke purge_files method')
    # I removed all duplicates from dest because cleaning up duplicates in
    # dest is out of the scope
    # NOTE: This is the perfect usecase for a set
    all_dest_clean = set(all_dest_dirty)
    # os.walk used to get all files in the source location
    for source_root, source_subdirs, source_files in os.walk(SOURCE):
        # looped through every file in source_files
        for file in source_files:
            # appending all_sources to get the application name from the
            # file path
            all_sources.append(os.path.abspath(file).split('\\')[-1])
            # looping through each element of all_source
            for source in all_sources:
                # logical check to see if file in the source folder exists
                # in the destination folder
                if source not in all_dest_clean:
                    # src is used to get the path of the source file this
                    # will be needed to move the file in shutil.move
                    src =  os.path.abspath(os.path.join(source_root, source))
                    # the two variables used below are to get the creation
                    # time of the files
                    metadata = os.stat(src)
                    creation_time = metadata.st_ctime
                    # logical check to see if the file is older than the cutoff
                    if creation_time < cutoff:
                        logging.info(f'File has been succesfully moved: {source}')
                        print(f'File has been succesfully moved: {source}')
                        shutil.move(src,dest)
                        # removing the already checked source files for the
                        # list this is also used in other spots within the loop
                        all_sources.remove(source)
                    else:
                        logging.info(f'File is not older than 14 days: {source}')
                        print(f'File is not older than 14 days: {source}')
                        all_sources.remove(source)
                else:
                    all_sources.remove(source)
                    logging.info(f'File: {source} already exists in the destination')
                    print(f'File: {source} already exists in the destination')

if __name__ == '__main__':
    main()
</code>```

Title: Python Repo Cleanup

Body:
I have a script that I have almost 100% complete however there is just one more step that I can not figure out. My script currently checks the destination to see if the file already exists and if it does then the file from the source location is not moved over. The problem I am running into is that the code doesn't check all of the subdirectories as well just the root directory.

I am using os.walk to go through all of the files in the source folder but am not sure how to os.walk the destination folder and the source folder in conjunction with each other.

import time
import sys
import logging
import logging.config

def main():
    purge_files

def move_files(src_file):

    try:
        #Attempt to move files to dest
        shutil.move(src_file, dest)
        #making use of the OSError exception instead of FileExistsError due to older version of python not contaning that exception
    except OSError as e:
        #Log the files that have not been moved to the console
        logging.info(f'Files File already exists: {src_file}')
        print(f'File already exists: {src_file}')
        #os.remove to delete files that are already in dest repo
        os.remove(src_file)
        logging.warning(f'Deleting: {src_file}')

def file_loop(files, root):

    for file in files:
        #src_file is used to get the full path of everyfile
        src_file = os.path.join(root,file)

        #The two variables below are used to get the files creation date
        t = os.stat(src_file)
        c = t.st_ctime
        #If the file is older then cutoff code within the if statement executes

        if c<cutoff:

            move_files(src_file)
        #Log the file names that are not older then the cutoff and continue loop
        else:
            logging.info(f'File is not older than 14 days: {src_file}')
            continue

def purge_files():

    logging.info('invoke purge_files method')
    #Walk through root directory and all subdirectories
       for root, subdirs, files in os.walk(source):
          dst_dir = root.replace(source, dest)

           #Loop through files to grab every file
           file_loop(files, root)

       return files, root, subdirs

files, root, subdirs = purge_files()

I expected the output to move all files from source to dest. Before the files are moved I expected to check all files in the dest location including subdir of dest if any of them are the same file as the source then they wont be moved to the dest. I do not want the folders that are in source. I just want all the files to be moved to the root directory.

Body:
You might want to clean up your code, it is full of bugs. E.g. 'purge_files' instead of 'purge_files()' in main, indentation errors inside purge_files etc. Also the seemingly random newlines between the code makes it a bit awkward to read (for me at least) :)

EDIT: I quickly went over your code and changed a few things. Mainly variable names. I noticed that you had a few variables with undescriptive names ('i', 't', etc.) together with a comment describing what that variable meant. If you just change the variable name to something more descriptive, you don't need the comments and your code is even easier to rad. Note that I didn't test this code and tbh it probably does not even run (since that was not my goal but rather to show some of the style changes that I would suggest) :)

import os
import shutil
import time
import errno
import time
import sys
import logging
import logging.config

# NOTE: It is a convention to write constants in all caps
SOURCE = r'C:\Users\Desktop\BetaSource'
DEST = r'C:\Users\Desktop\BetaDest'
#Gets the current time from the time module
now = time.time()
#Timer of when to purge files
cutoff = now - (14 * 86400)
all_sources = []
all_dest_dirty = []
logging.basicConfig(level = logging.INFO,
                    filename = time.strftime("main-%Y-%m-%d.log"))

def main():
    # NOTE: Why is this function called / does it exist? It only sets a global
    # 'dest_files' which is never used...
    dest_files()
    purge_files()

# I used the dess_files function to get all of the destination files
def dest_files():
    for root, subdirs, files in os.walk(DEST):
        for file in files:
            # NOTE: Is it really necessary to use a global here?
            global all_dirty
            all_dirty.append(files)

def purge_files():
    logging.info('invoke purge_files method')
    # I removed all duplicates from dest because cleaning up duplicates in
    # dest is out of the scope
    # NOTE: This is the perfect usecase for a set
    all_dest_clean = set(all_dest_dirty)
    # os.walk used to get all files in the source location
    for source_root, source_subdirs, source_files in os.walk(SOURCE):
        # looped through every file in source_files
        for file in source_files:
            # appending all_sources to get the application name from the
            # file path
            all_sources.append(os.path.abspath(file).split('\\')[-1])
            # looping through each element of all_source
            for source in all_sources:
                # logical check to see if file in the source folder exists
                # in the destination folder
                if source not in all_dest_clean:
                    # src is used to get the path of the source file this
                    # will be needed to move the file in shutil.move
                    src =  os.path.abspath(os.path.join(source_root, source))
                    # the two variables used below are to get the creation
                    # time of the files
                    metadata = os.stat(src)
                    creation_time = metadata.st_ctime
                    # logical check to see if the file is older than the cutoff
                    if creation_time < cutoff:
                        logging.info(f'File has been succesfully moved: {source}')
                        print(f'File has been succesfully moved: {source}')
                        shutil.move(src,dest)
                        # removing the already checked source files for the
                        # list this is also used in other spots within the loop
                        all_sources.remove(source)
                    else:
                        logging.info(f'File is not older than 14 days: {source}')
                        print(f'File is not older than 14 days: {source}')
                        all_sources.remove(source)
                else:
                    all_sources.remove(source)
                    logging.info(f'File: {source} already exists in the destination')
                    print(f'File: {source} already exists in the destination')

if __name__ == '__main__':
    main()


问:
2D R2C FFTW: Order of Fourier coefficients
I've used the 1D c2c transform several times, without any problems. The order of the Fourier coefficients for a transform with N grid points is: f_0, f_1, f_2, ..., f_N/2,  f_-N/2+1, ...., f_-1.

I just can't figure out the order of the coefficients for the 2D R2C FFTW.
I am using the following code. Using 2D_r2c, normalizing and then using 2D_c2r yields the original input so there should be no error.

```<code>void mFFTW2D(double INPUT[][STEPS], fftw_complex OUTPUT[][STEPS]){
    fftw_plan my_PLAN = fftw_plan_dft_r2c_2d(STEPS,
                        STEPS,
                        *INPUT,
                        *OUTPUT,
                        FFTW_ESTIMATE);
    fftw_execute(my_PLAN);
    fftw_destroy_plan(my_PLAN);
}

void mIFFTW2D(fftw_complex INPUT[][STEPS], double OUTPUT[][STEPS]){
    fftw_plan my_PLAN = fftw_plan_dft_c2r_2d(STEPS,
                        STEPS,
                        *INPUT,
                        *OUTPUT,
                        FFTW_ESTIMATE);
    fftw_execute(my_PLAN);
    fftw_destroy_plan(my_PLAN);
    D2Norm(OUTPUT); //properly normalized: STEPS^-2
}

double INN[STEPS][STEPS];
fftw_complex OUTT[STEPS][STEPS];

// read in signal in INN
mFFTW2D(INN, OUTT);
// what is the order of the fourier coefficients in OUTT?
mIFFTW2D(OUTT, INN);
</code>```

I used f(x,y)=sin(ax)*sin(ay) as a test input signal. 'a' was chosen in a manner, that the signal would be an integral multiple of one period of the sine(no leakage-effect). I was especially surprised that there was no symmetry of the Fourier coefficients for x and y.

答: The OUT array gets modified in when it is used in the inverse transform routine, so you have to check it before doing that. The wavenumbers are as the documentation then. </p>

Body:
I've used the 1D c2c transform several times, without any problems. The order of the Fourier coefficients for a transform with N grid points is: f_0, f_1, f_2, ..., f_N/2,  f_-N/2+1, ...., f_-1.

I just can't figure out the order of the coefficients for the 2D R2C FFTW.
I am using the following code. Using 2D_r2c, normalizing and then using 2D_c2r yields the original input so there should be no error.

void mFFTW2D(double INPUT[][STEPS], fftw_complex OUTPUT[][STEPS]){
    fftw_plan my_PLAN = fftw_plan_dft_r2c_2d(STEPS,
                        STEPS,
                        *INPUT,
                        *OUTPUT,
                        FFTW_ESTIMATE);
    fftw_execute(my_PLAN);
    fftw_destroy_plan(my_PLAN);
}

void mIFFTW2D(fftw_complex INPUT[][STEPS], double OUTPUT[][STEPS]){
    fftw_plan my_PLAN = fftw_plan_dft_c2r_2d(STEPS,
                        STEPS,
                        *INPUT,
                        *OUTPUT,
                        FFTW_ESTIMATE);
    fftw_execute(my_PLAN);
    fftw_destroy_plan(my_PLAN);
    D2Norm(OUTPUT); //properly normalized: STEPS^-2
}

double INN[STEPS][STEPS];
fftw_complex OUTT[STEPS][STEPS];

// read in signal in INN
mFFTW2D(INN, OUTT);
// what is the order of the fourier coefficients in OUTT?
mIFFTW2D(OUTT, INN);

I used f(x,y)=sin(ax)*sin(ay) as a test input signal. 'a' was chosen in a manner, that the signal would be an integral multiple of one period of the sine(no leakage-effect). I was especially surprised that there was no symmetry of the Fourier coefficients for x and y.