问:
Can not Navigate to Master Detail Page
i have axamarin app with login page that leads to modules launcher landing page
one of those modules is a master  details page

every thing is working fine from VS (debug / release) ether emulator or real device

however out of VS, from emulator or device itself if i run the app everything work fine except the navigation to master detail page (without any response)

i tried to navigate to a detailed page directly (without the master page) it works
i tried to put a "/" at the start  or remove it , i tried "/NavigationPage" or without it

still not working from the app outside VS.

i did the latest update (7.2.0.1422)

here is my xml codes :

navigation button from landing page

```<code>        <ImageButton Grid.Row="1"
                     Grid.Column="2"
                     HeightRequest="80"
                     BackgroundColor="WhiteSmoke"
                     Source="homescreenbtn12.png"
                     Command="{Binding NavigationCommand}"
                     CommandParameter="NavigationPage/MwaslaMasterDetailPage"
                     IsVisible="{Binding CurrentUser.IsTPEmplyess}"/>
</code>```

2.master details page it self

```<code><?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
              xmlns:prism="http://prismlibrary.com"
              prism:ViewModelLocator.AutowireViewModel="True"
              x:Class="TPS.Modules.Mwasla.Views.MwaslaMasterDetailPage"
              xmlns:views="clr-namespace:TPS.Modules.Mwasla.Views;assembly=TPS.Modules.Mwasla">

<MasterDetailPage.Master>
    <views:MwaslaMasterPageMenu/>
</MasterDetailPage.Master>

<MasterDetailPage.Detail>
    <NavigationPage>

        <x:Arguments>
            <views:MwaslaContactUsPage/>
        </x:Arguments>
    </NavigationPage>
</MasterDetailPage.Detail>
</code>```

the normally navigation command
   async void ExecuteCommandName(string parameter)
        {
            await NavigationService.NavigateAsync(parameter);
        }

kindly help

答:
There are a few issues I want to address here...

<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
              xmlns:prism="http://prismlibrary.com"
              prism:ViewModelLocator.AutowireViewModel="True"
              x:Class="TPS.Modules.Mwasla.Views.MwaslaMasterDetailPage"
              xmlns:views="clr-namespace:TPS.Modules.Mwasla.Views;assembly=TPS.Modules.Mwasla">

<MasterDetailPage.Master>
    <views:MwaslaMasterPageMenu/>
</MasterDetailPage.Master>

<MasterDetailPage.Detail>
    <NavigationPage>
        <x:Arguments>
            <views:MwaslaContactUsPage/>
        </x:Arguments>
    </NavigationPage>
</MasterDetailPage.Detail>
```

Core Concepts

In this sample there are essentially 3 pages that need to be understood...

The Master Page (MwaslaMasterPageMenu)... it's fine if you want to separate the View for the Master into another XAML page but remember that this should NOT have it's own ViewModel nor should you attempt to set AutowireViewModel on that page.

The MasterDetailPage... this is the actual root navigation context that you are navigating from. This is the page that requires the ViewModel which you have explicitly set AutowireViewModel on

The Detail Page (MwaslaContactUsPage in a NavigationPage)... while this is technically correct for a Xamarin.Forms app and would allow you navigate to /MwaslaMasterDetailPage, it's not recommended that you do this. You should instead be explicit in setting the Detail /MwaslaMasterDetailPage/NavigationPage/MwaslaContactUsPage

Issues with Navigation

Navigation in Prism.Forms is based on the Page which you want to Navigate from in context. This is why in the past there requirements that the Navigation service was a named parameter. Before Prism resolves the ViewModel, it first constructs a new instance of the NavigationService and provides it the navigation context (the Xamarin.Forms.Page aka the View) that the ViewModel will be attached to.

Fixes

First you'll want to move all of the logic from the MwaslaMasterPageMenuViewModel and move it to the MwaslaMasterDetailPageViewModel

Get rid of the MwaslaMasterPageMenuViewModel and remove the AutowireProperty from the MwaslaMasterPageMenu.xaml

Remember that a MasterDetailPage is meant to be the NavigationRoot. This means that if you look at the MasterDetailPage's Parent, it should be your App.

Remember that in order to get the classic "Hamburger" look that people typically want with the MasterDetailPage your Detail needs to be a NavigationPage. In order to achieve this correctly you should refrain from explicitly setting the Detail Page so that you properly navigate to any detail page within the MasterDetailPage, ie /MyMasterDetailPage/NavigationPage/ViewA

When considering the previous comment remove references like /MyMasterDetailPage or /NavigationPage/MyMasterDetailPage

Navigating from the Master aka "Menu"

Remember that when you're navigating from the Master Page aka the Menu, you're navigating not from the Master Page at all but from the MasterDetailPage. As such you will simply do a relative navigation like NavigationPage/ViewA or NavigationPage/ViewB for anything that will change out the Detail Page.

Title: Can not Navigate to Master Detail Page

Body:
i have axamarin app with login page that leads to modules launcher landing page
one of those modules is a master  details page

every thing is working fine from VS (debug / release) ether emulator or real device

however out of VS, from emulator or device itself if i run the app everything work fine except the navigation to master detail page (without any response)

i tried to navigate to a detailed page directly (without the master page) it works
i tried to put a "/" at the start  or remove it , i tried "/NavigationPage" or without it

still not working from the app outside VS.

i did the latest update (7.2.0.1422)

here is my xml codes :

navigation button from landing page

        <ImageButton Grid.Row="1"
                     Grid.Column="2"
                     HeightRequest="80"
                     BackgroundColor="WhiteSmoke"
                     Source="homescreenbtn12.png"
                     Command="{Binding NavigationCommand}"
                     CommandParameter="NavigationPage/MwaslaMasterDetailPage"
                     IsVisible="{Binding CurrentUser.IsTPEmplyess}"/>

2.master details page it self

<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
              xmlns:prism="http://prismlibrary.com"
              prism:ViewModelLocator.AutowireViewModel="True"
              x:Class="TPS.Modules.Mwasla.Views.MwaslaMasterDetailPage"
              xmlns:views="clr-namespace:TPS.Modules.Mwasla.Views;assembly=TPS.Modules.Mwasla">

<MasterDetailPage.Master>
    <views:MwaslaMasterPageMenu/>
</MasterDetailPage.Master>

<MasterDetailPage.Detail>
    <NavigationPage>

        <x:Arguments>
            <views:MwaslaContactUsPage/>
        </x:Arguments>
    </NavigationPage>
</MasterDetailPage.Detail>

the normally navigation command
   async void ExecuteCommandName(string parameter)
        {
            await NavigationService.NavigateAsync(parameter);
        }

kindly help

Body:
There are a few issues I want to address here...

<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
              xmlns:prism="http://prismlibrary.com"
              prism:ViewModelLocator.AutowireViewModel="True"
              x:Class="TPS.Modules.Mwasla.Views.MwaslaMasterDetailPage"
              xmlns:views="clr-namespace:TPS.Modules.Mwasla.Views;assembly=TPS.Modules.Mwasla">

<MasterDetailPage.Master>
    <views:MwaslaMasterPageMenu/>
</MasterDetailPage.Master>

<MasterDetailPage.Detail>
    <NavigationPage>
        <x:Arguments>
            <views:MwaslaContactUsPage/>
        </x:Arguments>
    </NavigationPage>
</MasterDetailPage.Detail>

Core Concepts

In this sample there are essentially 3 pages that need to be understood...

The Master Page (MwaslaMasterPageMenu)... it's fine if you want to separate the View for the Master into another XAML page but remember that this should NOT have it's own ViewModel nor should you attempt to set AutowireViewModel on that page.

The MasterDetailPage... this is the actual root navigation context that you are navigating from. This is the page that requires the ViewModel which you have explicitly set AutowireViewModel on

The Detail Page (MwaslaContactUsPage in a NavigationPage)... while this is technically correct for a Xamarin.Forms app and would allow you navigate to /MwaslaMasterDetailPage, it's not recommended that you do this. You should instead be explicit in setting the Detail /MwaslaMasterDetailPage/NavigationPage/MwaslaContactUsPage

Issues with Navigation

Navigation in Prism.Forms is based on the Page which you want to Navigate from in context. This is why in the past there requirements that the Navigation service was a named parameter. Before Prism resolves the ViewModel, it first constructs a new instance of the NavigationService and provides it the navigation context (the Xamarin.Forms.Page aka the View) that the ViewModel will be attached to.

Fixes

First you'll want to move all of the logic from the MwaslaMasterPageMenuViewModel and move it to the MwaslaMasterDetailPageViewModel

Get rid of the MwaslaMasterPageMenuViewModel and remove the AutowireProperty from the MwaslaMasterPageMenu.xaml

Remember that a MasterDetailPage is meant to be the NavigationRoot. This means that if you look at the MasterDetailPage's Parent, it should be your App.

Remember that in order to get the classic "Hamburger" look that people typically want with the MasterDetailPage your Detail needs to be a NavigationPage. In order to achieve this correctly you should refrain from explicitly setting the Detail Page so that you properly navigate to any detail page within the MasterDetailPage, ie /MyMasterDetailPage/NavigationPage/ViewA

When considering the previous comment remove references like /MyMasterDetailPage or /NavigationPage/MyMasterDetailPage

Navigating from the Master aka "Menu"

Remember that when you're navigating from the Master Page aka the Menu, you're navigating not from the Master Page at all but from the MasterDetailPage. As such you will simply do a relative navigation like NavigationPage/ViewA or NavigationPage/ViewB for anything that will change out the Detail Page.


来源: stackexchange

问:
how to define a resolver in appsync to get a range of data between a particular dates in graphQL
```<code>{
  "version": "2018-05-29",
  "operation": "Query",
  "index": "sportLeague",
  "query": {
  "expression": "sportIdLeagueId = :sportIdLeagueId and gsSK = :gsSK",
    "expressionValues": {
    #set( $sportIdLeagueId = $util.dynamodb.toDynamoDBJson("fixture#${ctx.args.input.sportId}#${ctx.args.input.leagueId}") )
    ":sportIdLeagueId": $sportIdLeagueId,
  }
 },
 "filter" : {
    "expression" : "between(#title, :title)",
    "expressionNames" : {
        "#startDateUtc" : "startDateUtc"
    }
    "expressionValues" : {
        ":start" : $util.dynamodb.toDynamoDBJson($ctx.args.input.startDateUtc)
    }
}
}
</code>```

i need a between condition to satisfy the requirement
requirement: get data between two dates i.e start date and end date

答:
You attribute names and values need to match what is in your expression. (:title needs to have a corresponding value in expressionNames and expressionValues)

Also the between operator syntax is BETWEEN :startDateUtc AND :endDateUtc

There is a tutorial for using DynamoDB Query in AppSync:

https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-dynamodb-resolvers.html#setting-up-the-allpostsbyauthor-resolver-ddb-query

DynamoDB expressions:
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html

ContentLicense: CC BY-SA 4.0

Body:
{
  "version": "2018-05-29",
  "operation": "Query",
  "index": "sportLeague",
  "query": {
  "expression": "sportIdLeagueId = :sportIdLeagueId and gsSK = :gsSK",
    "expressionValues": {
    #set( $sportIdLeagueId = $util.dynamodb.toDynamoDBJson("fixture#${ctx.args.input.sportId}#${ctx.args.input.leagueId}") )
    ":sportIdLeagueId": $sportIdLeagueId,
  }
 },
 "filter" : {
    "expression" : "between(#title, :title)",
    "expressionNames" : {
        "#startDateUtc" : "startDateUtc"
    }
    "expressionValues" : {
        ":start" : $util.dynamodb.toDynamoDBJson($ctx.args.input.startDateUtc)
    }
}
}

i need a between condition to satisfy the requirement
requirement: get data between two dates i.e start date and end date


问:
python strftime without leading 0
It worked in last 20 days where i had two numbers in day

Now :

```<code>time data 'Jun  1 2020 12:00AM' does not match format '%B %d %Y %I:%M%p'
</code>```

So the code which goes like

```<code> #last_run_db = 'Jun  1 2020 12:00AM'
 last_run_date = datetime.strptime(last_run_db, "%B %d %Y %I:%M%p")
</code>```

I tried with

```<code>  %-d
  %e
  %#d
</code>```

答:
It worked in last 20 days where i had two numbers in day

Another interesting thing about the last 20 days is that they were in May, where the full name of the month fits in three letters. %B is for the full name of the month; you want %b for this three-letter abbreviation. See the documentation.

Title: python strftime without leading 0

Body:
It worked in last 20 days where i had two numbers in day

Now :

time data 'Jun  1 2020 12:00AM' does not match format '%B %d %Y %I:%M%p'

So the code which goes like

 #last_run_db = 'Jun  1 2020 12:00AM'
 last_run_date = datetime.strptime(last_run_db, "%B %d %Y %I:%M%p")

I tried with

  %-d
  %e
  %#d


问:
Count which cycle of the alphabet this letter is in [python]
I have this alphabetic cycle A B C D which represent the phase an item is in. An item can cycle through the phase more than once, so I need to find out if an item is in its first phase A, or its second phase A.

Letters can be missing which makes this a bit tricky. See correct outputs:

```<code>test_1 = ['A','B','C','D','A','B']
output_1 = [1,1,1,1,2,2]

test_2 = ['A','B','D','A','B','C']
output_2 = [1,1,1,2,2,2]

test_3 = ['B','A','B','C']
output_3 = [1,2,2,2]
</code>```

Note that in test_2 we accurately note the first occurrence of phase C is in the 2nd cycle.

My attempts are below:

```<code>import itertools

test_1 = ['A','B','C','D','A','B']
output_1 = [1,1,1,1,2,2]

test_2 = ['A','B','D','A','B','C']
output_2 = [1,1,1,2,2,2]

test_3 = ['B','A','B','C']
output_3 = [1,2,2,2]

valid_phase_seq=['A','B','C','D']

def count_phases(phase_list):
    '''
    We will see whether this is the 1st phase A, or the 2nd phase A.
    :param phase_list:
    :return: int list
    '''
    phase_counts = []
    valid_iter = itertools.cycle(valid_phase_seq)
    count = 1

    # failed approach #2
    while len(phase_counts) != len(phase_list):
        for valid_phase in valid_iter:
            for curr_phase in phase_list:
                if valid_phase == curr_phase:
                    phase_counts.append(count)
            count += 1

    # failed approach #1
    # for curr_phase in phase_list:
    #     # Look at a phase
    #     curr_valid = next(valid_iter)
    #
    #     # We are in another cycle
    #     if curr_valid == 'A' and len(phase_counts) > 1:
    #         count += 1
    #         valid_iter = itertools.cycle(valid_phase_seq)
    #         curr_valid = next(valid_iter)
    #
    #     # We are in the same cycle
    #     #if curr_phase == curr_valid:
    #     phase_counts.append(count)

    return phase_counts

</code>```

答:
Well, Karl beat me to it with a super simple solution. I on the other hand got it a little more complicated but will post anyway as I already put the time to it...

My idea was to use a cyclic counter with a mapping between each letter to an index. This way we loop on the letters and add one to each index up to that letter, cyclicly. Goes something like:

from itertools import count

def phase_count(phases):
    letters_index = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
    counts = [0 for _ in letters_index]
    size = len(counts)

    res = []
    last_index = 0
    for letter in test_2:
        for index in count(last_index):
            counts[index%size] += 1
            if index % size == letters_index[letter]:
                res.append(counts[index%size])
                last_index = index + 1
                break
    return res
```

Body:
I have this alphabetic cycle A B C D which represent the phase an item is in. An item can cycle through the phase more than once, so I need to find out if an item is in its first phase A, or its second phase A.

Letters can be missing which makes this a bit tricky. See correct outputs:

test_1 = ['A','B','C','D','A','B']
output_1 = [1,1,1,1,2,2]

test_2 = ['A','B','D','A','B','C']
output_2 = [1,1,1,2,2,2]

test_3 = ['B','A','B','C']
output_3 = [1,2,2,2]

Note that in test_2 we accurately note the first occurrence of phase C is in the 2nd cycle.

My attempts are below:

import itertools

test_1 = ['A','B','C','D','A','B']
output_1 = [1,1,1,1,2,2]

test_2 = ['A','B','D','A','B','C']
output_2 = [1,1,1,2,2,2]

test_3 = ['B','A','B','C']
output_3 = [1,2,2,2]

valid_phase_seq=['A','B','C','D']

def count_phases(phase_list):
    '''
    We will see whether this is the 1st phase A, or the 2nd phase A.
    :param phase_list:
    :return: int list
    '''
    phase_counts = []
    valid_iter = itertools.cycle(valid_phase_seq)
    count = 1

    # failed approach #2
    while len(phase_counts) != len(phase_list):
        for valid_phase in valid_iter:
            for curr_phase in phase_list:
                if valid_phase == curr_phase:
                    phase_counts.append(count)
            count += 1

    # failed approach #1
    # for curr_phase in phase_list:
    #     # Look at a phase
    #     curr_valid = next(valid_iter)
    #
    #     # We are in another cycle
    #     if curr_valid == 'A' and len(phase_counts) > 1:
    #         count += 1
    #         valid_iter = itertools.cycle(valid_phase_seq)
    #         curr_valid = next(valid_iter)
    #
    #     # We are in the same cycle
    #     #if curr_phase == curr_valid:
    #     phase_counts.append(count)

    return phase_counts


问:
Add a blog to an existing webpage
How can I insert a blog (not created yet) into an already existing 'static' webpage? The webpage is written mostly in PHP. I'm considering using something like WordPress.org (host install version) and using it to update the website's news page.

From what I've read, its sounds like I would need to do a lot of theme tweaking to get WordPress to display correctly with our website's template. This sounds a bit daunting to me.

答:
I did the exact same thing on my site. I had about 20 static pages, wanted to add a blog and wanted to add content from the WP pages to the static pages. It was not hard to find a theme that (almost) matched my static pages. Everything outside of /tech/ is a static page.

You can also get a very minimalistic theme and then make it match your design. It's one big heaping cut and paste of CSS, re-labling elements to match what WP wants then a little tweaking. I've done it in under 8 hours on other sites.

Read up on using the Wordpress loop. This is so much easier than you think it's going to be, especially if your stuff is already done in PHP.

Edit:

Here's a snippet of the code that I use in my static pages, which allows me to then use all of the other WP functions in the existing code:

```<code><?php
    if ( empty( $wp ) )
       require_once( "tech/wp-config.php" );
    wp();
?>
</code>```

Then, getting a list of recent posts is as easy as:

```<code><?php get_archives( 'postbypost', 8 ); ?>
</code>```

Just look out for using deprecated functions, I've got a few still left to clean out from when I integrated WP 2 years ago.

OwnerDisplayName: djbender

Title: Add a blog to an existing webpage

LastEditorDisplayName: tinkertim

Body:
I did the exact same thing on my site. I had about 20 static pages, wanted to add a blog and wanted to add content from the WP pages to the static pages. It was not hard to find a theme that (almost) matched my static pages. Everything outside of /tech/ is a static page.

You can also get a very minimalistic theme and then make it match your design. It's one big heaping cut and paste of CSS, re-labling elements to match what WP wants then a little tweaking. I've done it in under 8 hours on other sites.

Read up on using the Wordpress loop. This is so much easier than you think it's going to be, especially if your stuff is already done in PHP.

Edit:

Here's a snippet of the code that I use in my static pages, which allows me to then use all of the other WP functions in the existing code:

<?php
    if ( empty( $wp ) )
       require_once( "tech/wp-config.php" );
    wp();
?>

Then, getting a list of recent posts is as easy as:

<?php get_archives( 'postbypost', 8 ); ?>

Just look out for using deprecated functions, I've got a few still left to clean out from when I integrated WP 2 years ago.

OwnerDisplayName: tinkertim


问:
Optimizing queries for content popularity by hits

I've done some searching for this but haven't come up with anything, maybe someone could point me in the right direction.

I have a website with lots of content in a MySQL database and a PHP script that loads the most popular content by hits. It does this by logging each content hit in a table along with the access time. Then a select query is run to find the most popular content in the past 24 hours, 7 day or maximum 30 days. A cronjob deletes anything older than 30 days in the log table.

The problem I'm facing now is as the website grows the log table has 1m+ hit records and it is really slowing down my select query (10-20s). At first I though the problem was a join I had in the query to get the content title, url, etc. But now I'm not sure as in test removing the join does not speed the query as much as I though it would.

So my question is what is best practise of doing this kind of popularity storing/selecting? Are they any good open source scripts for this? Or what would you suggest?

Table scheme

"popularity" hit log table

  nid | insert_time | tid

  nid: Node ID of the content

  insert_time: timestamp (2011-06-02 04:08:45)

  tid: Term/category ID

"node" content table

  nid | title | status | (there are more but these are the important ones)

  nid: Node ID

  title: content title

  status: is the content published (0=false, 1=true)

SQL

```<code>SELECT node.nid, node.title, COUNT(popularity.nid) AS count
FROM `node` INNER JOIN `popularity` USING (nid)
WHERE node.status = 1
  AND  popularity.insert_time >= DATE_SUB(CURDATE(),INTERVAL 7 DAY)
GROUP BY popularity.nid
ORDER BY count DESC
LIMIT 10;
</code>```

答:
You actually have two problems to solve further down the road.

One, which you've yet to run into but which you might earlier than you want, is going to be insert throughput within your stats table.

The other, which you've outlined in your question, is actually using the stats.

Let's start with input throughput.

Firstly, in case you're doing so, don't track statistics on pages that could use caching. Use a php script that advertises itself as an empty javascript, or as a one-pixel image, and include the latter on pages you're tracking. Doing so allows to readily cache the remaining content of your site.

In a telco business, rather than doing an actual inserts related to billing on phone calls, things are placed in memory and periodically sync'ed with the disk. Doing so allows to manage gigantic throughputs while keeping the hard-drives happy.

To proceed similarly on your end, you'll need an atomic operation and some in-memory storage. Here's some memcache-based pseudo-code for doing the first part...

For each page, you need a Memcache variable. In Memcache, increment() is atomic, but add(), set(), and so forth aren't. So you need to be wary of not miss-counting hits when concurrent processes add the same page at the same time:

```<code>$ns = $memcache->get('stats-namespace');
while (!$memcache->increment("stats-$ns-$page_id")) {
  $memcache->add("stats-$ns-$page_id", 0, 1800); // garbage collect in 30 minutes
  $db->upsert('needs_stats_refresh', array($ns, $page_id)); // engine = memory
}
</code>```

Periodically, say every 5 minutes (configure the timeout accordingly), you'll want to sync all of this to the database, without any possibility of concurrent processes affecting each other or existing hit counts. For this, you increment the namespace before doing anything (this gives you a lock on existing data for all intents and purposes), and sleep a bit so that existing processes that reference the prior namespace finish up if needed:

```<code>$ns = $memcache->get('stats-namespace');
$memcache->increment('stats-namespace');
sleep(60); // allow concurrent page loads to finish
</code>```

Once that is done, you can safely loop through your page ids, update stats accordingly, and clean up the needs_stats_refresh table. The latter only needs two fields: page_id int pkey, ns_id int). There's a bit more to it than simple select, insert, update and delete statements run from your scripts, however, so continuing...

As another replier suggested, it's quite appropriate to maintain intermediate stats for your purpose: store batches of hits rather than individual hits. At the very most, I'm assuming you want hourly stats or quarter-hourly stats, so it's fine to deal with subtotals that are batch-loaded every 15 minute.

Even more importantly for your sake, since you're ordering posts using these totals, you want to store the aggregated totals and have an index on the latter. (We'll get to where further down.)

One way to maintain the totals is to add a trigger which, on insert or update to the stats table, will adjust the stats total as needed.

When doing so, be especially wary about dead-locks. While no two $ns runs will be mixing their respective stats, there is still a (however slim) possibility that two or more processes fire up the "increment $ns" step described above concurrently, and subsequently issue statements that seek to update the counts concurrently. Obtaining an advisory lock is the simplest, safest, and fastest way to avoid problems related to this.

Assuming you use an advisory lock, it's perfectly OK to use: total = total + subtotal in the update the statement.

While on the topic of locks, note that updating the totals will require an exclusive lock on each affected row. Since you're ordering by them, you don't want them processed all in one go because it might mean keeping an exclusive lock for an extended duration. The simplest here is to process the inserts into stats in smaller batches (say, 1000), each followed by a commit.

For intermediary stats (monthly, weekly), add a few boolean fields (bit or tinyint in MySQL) to your stats table. Have each of these store whether they're to be counted for with monthly, weekly, daily stats, etc. Place a trigger on them as well, in such a way that they increase or decrease the applicable totals in your stat_totals table.

As a closing note, give some thoughts on where you want the actual count to be stored. It needs to be an indexed field, and the latter is going to be heavily updated. Typically, you'll want it stored in its own table, rather than in the pages table, in order to avoid cluttering your pages table with (much larger) dead rows.

Assuming you did all the above your final query becomes:

```<code>select p.*
from pages p join stat_totals s using (page_id)
order by s.weekly_total desc limit 10
</code>```

It should be plenty fast with the index on weekly_total.

Lastly, let's not forget the most obvious of all: if you're running these same total/monthly/weekly/etc queries over and over, their result should be placed in memcache too.

ContentLicense: CC BY-SA 3.0

Body:
I've done some searching for this but haven't come up with anything, maybe someone could point me in the right direction.

I have a website with lots of content in a MySQL database and a PHP script that loads the most popular content by hits. It does this by logging each content hit in a table along with the access time. Then a select query is run to find the most popular content in the past 24 hours, 7 day or maximum 30 days. A cronjob deletes anything older than 30 days in the log table.

The problem I'm facing now is as the website grows the log table has 1m+ hit records and it is really slowing down my select query (10-20s). At first I though the problem was a join I had in the query to get the content title, url, etc. But now I'm not sure as in test removing the join does not speed the query as much as I though it would.

So my question is what is best practise of doing this kind of popularity storing/selecting? Are they any good open source scripts for this? Or what would you suggest?

Table scheme

"popularity" hit log table

  nid | insert_time | tid

  nid: Node ID of the content

  insert_time: timestamp (2011-06-02 04:08:45)

  tid: Term/category ID

"node" content table

  nid | title | status | (there are more but these are the important ones)

  nid: Node ID

  title: content title

  status: is the content published (0=false, 1=true)

SQL

SELECT node.nid, node.title, COUNT(popularity.nid) AS count
FROM `node` INNER JOIN `popularity` USING (nid)
WHERE node.status = 1
  AND  popularity.insert_time >= DATE_SUB(CURDATE(),INTERVAL 7 DAY)
GROUP BY popularity.nid
ORDER BY count DESC
LIMIT 10;

Body:
You actually have two problems to solve further down the road.

One, which you've yet to run into but which you might earlier than you want, is going to be insert throughput within your stats table.

The other, which you've outlined in your question, is actually using the stats.

Let's start with input throughput.

Firstly, in case you're doing so, don't track statistics on pages that could use caching. Use a php script that advertises itself as an empty javascript, or as a one-pixel image, and include the latter on pages you're tracking. Doing so allows to readily cache the remaining content of your site.

In a telco business, rather than doing an actual inserts related to billing on phone calls, things are placed in memory and periodically sync'ed with the disk. Doing so allows to manage gigantic throughputs while keeping the hard-drives happy.

To proceed similarly on your end, you'll need an atomic operation and some in-memory storage. Here's some memcache-based pseudo-code for doing the first part...

For each page, you need a Memcache variable. In Memcache, increment() is atomic, but add(), set(), and so forth aren't. So you need to be wary of not miss-counting hits when concurrent processes add the same page at the same time:

$ns = $memcache->get('stats-namespace');
while (!$memcache->increment("stats-$ns-$page_id")) {
  $memcache->add("stats-$ns-$page_id", 0, 1800); // garbage collect in 30 minutes
  $db->upsert('needs_stats_refresh', array($ns, $page_id)); // engine = memory
}

Periodically, say every 5 minutes (configure the timeout accordingly), you'll want to sync all of this to the database, without any possibility of concurrent processes affecting each other or existing hit counts. For this, you increment the namespace before doing anything (this gives you a lock on existing data for all intents and purposes), and sleep a bit so that existing processes that reference the prior namespace finish up if needed:

$ns = $memcache->get('stats-namespace');
$memcache->increment('stats-namespace');
sleep(60); // allow concurrent page loads to finish

Once that is done, you can safely loop through your page ids, update stats accordingly, and clean up the needs_stats_refresh table. The latter only needs two fields: page_id int pkey, ns_id int). There's a bit more to it than simple select, insert, update and delete statements run from your scripts, however, so continuing...

As another replier suggested, it's quite appropriate to maintain intermediate stats for your purpose: store batches of hits rather than individual hits. At the very most, I'm assuming you want hourly stats or quarter-hourly stats, so it's fine to deal with subtotals that are batch-loaded every 15 minute.

Even more importantly for your sake, since you're ordering posts using these totals, you want to store the aggregated totals and have an index on the latter. (We'll get to where further down.)

One way to maintain the totals is to add a trigger which, on insert or update to the stats table, will adjust the stats total as needed.

When doing so, be especially wary about dead-locks. While no two $ns runs will be mixing their respective stats, there is still a (however slim) possibility that two or more processes fire up the "increment $ns" step described above concurrently, and subsequently issue statements that seek to update the counts concurrently. Obtaining an advisory lock is the simplest, safest, and fastest way to avoid problems related to this.

Assuming you use an advisory lock, it's perfectly OK to use: total = total + subtotal in the update the statement.

While on the topic of locks, note that updating the totals will require an exclusive lock on each affected row. Since you're ordering by them, you don't want them processed all in one go because it might mean keeping an exclusive lock for an extended duration. The simplest here is to process the inserts into stats in smaller batches (say, 1000), each followed by a commit.

For intermediary stats (monthly, weekly), add a few boolean fields (bit or tinyint in MySQL) to your stats table. Have each of these store whether they're to be counted for with monthly, weekly, daily stats, etc. Place a trigger on them as well, in such a way that they increase or decrease the applicable totals in your stat_totals table.

As a closing note, give some thoughts on where you want the actual count to be stored. It needs to be an indexed field, and the latter is going to be heavily updated. Typically, you'll want it stored in its own table, rather than in the pages table, in order to avoid cluttering your pages table with (much larger) dead rows.

Assuming you did all the above your final query becomes:

select p.*
from pages p join stat_totals s using (page_id)
order by s.weekly_total desc limit 10

It should be plenty fast with the index on weekly_total.

Lastly, let's not forget the most obvious of all: if you're running these same total/monthly/weekly/etc queries over and over, their result should be placed in memcache too.


问:
How to access the internal functions of an R package using rpy2?
I am working with the GMCM package of R in Python using rpy2. There are a few internal functions of GMCM package which can be accessed only using the ::: operator. For example the function qgmm.marginal cannot be accessed using rpy2 in the usual way.

Here is my Python code:

```<code>import rpy2

import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
gmcm_r = importr('GMCM')
data_r = gmcm_r.SimulateGMCMData(n = 100, m =3, d=2)

print(gmcm_r.Uhat(data_r.rx2('z'))) # works
print(gmcm_r.qgmm.marginal(gmcm_r.Uhat(data_r.rx2('z')))) # does not work
# AttributeError: module 'GMCM' has no attribute 'qgmm'
</code>```

The corresponding R code is

```<code>library(GMCM)
data = SimulateGMCMData(n = 100, m =3, d=2)
u = Uhat(data$z) #works
GMCM:::qgmm.marginal(u, theta)#works
</code>```

How do we access these internal functions using rpy2?

答:
You had two mistakes:

You retained an R syntax dot (.) that you should have converted to a python syntax underscore (_). That's what caused the error you observed.

Once you fix that error, though, you'd find a new one: You didn't specify the theta argument to the function you're trying to call.

Here's a working solution:

import rpy2

import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
gmcm_r = importr('GMCM')
data_r = gmcm_r.SimulateGMCMData(n = 100, m =3, d=2)

print(gmcm_r.Uhat(data_r.rx2('z'))) # works
## [Output omitted]

u = gmcm_r.Uhat(data_r.rx2('z'))
theta = data_r.rx2('theta') ## Need to specify theta
# print(gmcm_r.qgmm.marginal(u, theta)) ## Need to change the dot after qgmm
print(gmcm_r.qgmm_marginal(u, theta))   ## to an underscore

             [,1]        [,2]
  [1,]   8.660195  0.26664200
  [2,]   7.626162  7.86828143
  [3,]   7.862762  8.75474254
## [output truncated]
```

Body:
I am working with the GMCM package of R in Python using rpy2. There are a few internal functions of GMCM package which can be accessed only using the ::: operator. For example the function qgmm.marginal cannot be accessed using rpy2 in the usual way.

Here is my Python code:

import rpy2

import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
gmcm_r = importr('GMCM')
data_r = gmcm_r.SimulateGMCMData(n = 100, m =3, d=2)

print(gmcm_r.Uhat(data_r.rx2('z'))) # works
print(gmcm_r.qgmm.marginal(gmcm_r.Uhat(data_r.rx2('z')))) # does not work
# AttributeError: module 'GMCM' has no attribute 'qgmm'

The corresponding R code is

library(GMCM)
data = SimulateGMCMData(n = 100, m =3, d=2)
u = Uhat(data$z) #works
GMCM:::qgmm.marginal(u, theta)#works

How do we access these internal functions using rpy2?


答:
Here you go:

import pandas as pd
from datetime import datetime

d = {'Name': ['bob', 'george'], 'date1': ['2014/05/12:12:00:00 AM', '2014/05/15:12:00:00 AM'], 'date2': ['2014/08/31:11:59:59 PM', '2014/08/12:11:59:59 AM']}
df = pd.DataFrame(data=d)
date_extractor = lambda dts : datetime.strptime(dts, '%Y/%m/%d:%I:%M:%S %p').date()
df['date1'] = df['date1'].apply(date_extractor)
df['date2'] = df['date2'].apply(date_extractor)
print(df)
```

<p>Output:</p>

```     Name       date1       date2
0     bob  2014-05-12  2014-08-31
1  george  2014-05-15  2014-08-12
```

Title: Pandas: Extract date from unconventional timestamp -- YYY/MM/DD:HH:MM:SS AM

Body:
I have data in the following format:

d = {'Name': ['bob', 'george'], 'date1': ['2014/05/12:12:00:00 AM', '2014/05/15:12:00:00 AM'], 'date2': ['2014/08/31:11:59:59 PM', '2014/08/12:11:59:59 PM']}
df = pd.DataFrame(data=d)

   Name                   date1                   date2
0     bob  2014/05/12:12:00:00 AM  2014/08/31:11:59:59 PM
1  george  2014/05/15:12:00:00 AM  2014/08/12:11:59:59 PM

How do I manipute the two date columns to get the following format?

Expected output:

     Name       date1       date2
0     bob  2014-05-12  2014-08-31
1  george  2014-05-15  2014-08-12

Body:
Here you go:

import pandas as pd
from datetime import datetime

d = {'Name': ['bob', 'george'], 'date1': ['2014/05/12:12:00:00 AM', '2014/05/15:12:00:00 AM'], 'date2': ['2014/08/31:11:59:59 PM', '2014/08/12:11:59:59 AM']}
df = pd.DataFrame(data=d)
date_extractor = lambda dts : datetime.strptime(dts, '%Y/%m/%d:%I:%M:%S %p').date()
df['date1'] = df['date1'].apply(date_extractor)
df['date2'] = df['date2'].apply(date_extractor)
print(df)

Output:

     Name       date1       date2
0     bob  2014-05-12  2014-08-31
1  george  2014-05-15  2014-08-12


问:
Sieve Of Eratosthenes in O(n)
I recently came across an article that claimed that it can find all primes less than n in O(n) using an efficient Sieve Of Eratosthenes. However I am unable to see how it is O(n).

https://www.geeksforgeeks.org/sieve-eratosthenes-0n-time-complexity/

Could anyone please help with that?

答:
The normal Sieve of Eratosthenes is O(n log log n).

Paul Pritchard has done some work on sieves similar to the Sieve of Eratosthenes that run in O(n) and even in O(n / log log n). They are tricky to implement, and despite improved theoretical time complexity, the bookkeeping involved in running the sieves makes them slower than the normal Sieve of Eratosthenes.

I discuss a simple version of Pritchard's sieve at my blog.

Title: Sieve Of Eratosthenes in O(n)


问:
How to compress of reduce the size of an image before uploading to Parse as PFFile? (Swift)
I was trying to upload an image file to Parse after taking photo directly on phone. But it throws an exception:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'PFFile cannot be larger than 10485760 bytes'

Here is my code:

In first view controller:

```<code>override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "getImage")
    {
        var svc = segue.destinationViewController as! ClothesDetail
        svc.imagePassed = imageView.image
    }
}
</code>```

In view controller that uploads image:

```<code>let imageData = UIImagePNGRepresentation(imagePassed)
let imageFile = PFFile(name: "\(picName).png", data: imageData)

var userpic = PFObject(className:"UserPic")
userpic["picImage"] = imageFile`
</code>```

But I still need to upload that photo to Parse. Is there any way to reduce the size or resolution of the image?

答:
In Swift 5 as @Thiago Arreguy answer:

```<code>extension UIImage {

    var highestQualityJPEGNSData: Data { return self.jpegData(compressionQuality: 1.0)! }
    var highQualityJPEGNSData: Data    { return self.jpegData(compressionQuality: 0.75)!}
    var mediumQualityJPEGNSData: Data  { return self.jpegData(compressionQuality: 0.5)! }
    var lowQualityJPEGNSData: Data     { return self.jpegData(compressionQuality: 0.25)!}
    var lowestQualityJPEGNSData: Data  { return self.jpegData(compressionQuality: 0.0)! }

}
</code>```

And you can call like this:

```<code>let imageData = imagePassed.lowestQualityJPEGNSData
</code>```

Body:
I was trying to upload an image file to Parse after taking photo directly on phone. But it throws an exception:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'PFFile cannot be larger than 10485760 bytes'

Here is my code:

In first view controller:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "getImage")
    {
        var svc = segue.destinationViewController as! ClothesDetail
        svc.imagePassed = imageView.image
    }
}

In view controller that uploads image:

let imageData = UIImagePNGRepresentation(imagePassed)
let imageFile = PFFile(name: "\(picName).png", data: imageData)

var userpic = PFObject(className:"UserPic")
userpic["picImage"] = imageFile`

But I still need to upload that photo to Parse. Is there any way to reduce the size or resolution of the image?

Body:
In Swift 5 as @Thiago Arreguy answer:

extension UIImage {

    var highestQualityJPEGNSData: Data { return self.jpegData(compressionQuality: 1.0)! }
    var highQualityJPEGNSData: Data    { return self.jpegData(compressionQuality: 0.75)!}
    var mediumQualityJPEGNSData: Data  { return self.jpegData(compressionQuality: 0.5)! }
    var lowQualityJPEGNSData: Data     { return self.jpegData(compressionQuality: 0.25)!}
    var lowestQualityJPEGNSData: Data  { return self.jpegData(compressionQuality: 0.0)! }

}

And you can call like this:

let imageData = imagePassed.lowestQualityJPEGNSData


问:
Select one value from XML Document
I just want ONE value from an XML file using VB. The XML file is this

```<code><?xml version="1.0" encoding="utf-8"?>
<Books>
    <Book ID="12345">
        <Name>One Flew Over The Cuckoo's Nest</Name>
        <ISBN>Some cataloging ID</ISBN>
        <Author>Ken Kesey</Author>
        <More>Something here</More>
    </Book>
</Books>
</code>```

In this example, I just want to get the ISBN number of the book with the Author "Ken Kesey." I tried this;

```<code>        Dim xl As XElement = XElement.Load(AppDomain.CurrentDomain.BaseDirectory + "\Books.xml")
        Dim Auth As String = From elem In xl.Elements("Books").Elements("Book")
                             Where elem.Element("ISBN").Value = "Some cataloging ID"
                             Select elem.Element("Author").Value
</code>```

And many variations of the same, to no effect.

Thank you for looking.

答:
Here is how to query XML and find ISBN of a book based on the Author element.

I used .Parse() method because I didn't want to create a file.

VB.NET

```<code>Sub Main
    Dim xelem As XElement = XElement.Parse("<Books>
    <Book ID='12345'>
        <Name>One Flew Over The Cuckoo's Nest</Name>
        <ISBN>Some cataloging ID</ISBN>
        <Author>Ken Kesey</Author>
        <More>Something here</More>
    </Book>
</Books>")

    Dim ISBN As String = xelem.Elements("Book") _
        .Where(Function(x) x.Element("Author").Value.Equals("Ken Kesey")) _
        .[Select](Function(x) CStr(x.Element("ISBN").Value)).FirstOrDefault()

    Console.WriteLine(ISBN)
End Sub
</code>```

Title: Select one value from XML Document

Body:
I just want ONE value from an XML file using VB. The XML file is this

<?xml version="1.0" encoding="utf-8"?>
<Books>
    <Book ID="12345">
        <Name>One Flew Over The Cuckoo's Nest</Name>
        <ISBN>Some cataloging ID</ISBN>
        <Author>Ken Kesey</Author>
        <More>Something here</More>
    </Book>
</Books>

In this example, I just want to get the ISBN number of the book with the Author "Ken Kesey." I tried this;

        Dim xl As XElement = XElement.Load(AppDomain.CurrentDomain.BaseDirectory + "\Books.xml")
        Dim Auth As String = From elem In xl.Elements("Books").Elements("Book")
                             Where elem.Element("ISBN").Value = "Some cataloging ID"
                             Select elem.Element("Author").Value

And many variations of the same, to no effect.

Thank you for looking.

Body:
Here is how to query XML and find ISBN of a book based on the Author element.

I used .Parse() method because I didn't want to create a file.

VB.NET

Sub Main
    Dim xelem As XElement = XElement.Parse("<Books>
    <Book ID='12345'>
        <Name>One Flew Over The Cuckoo's Nest</Name>
        <ISBN>Some cataloging ID</ISBN>
        <Author>Ken Kesey</Author>
        <More>Something here</More>
    </Book>
</Books>")

    Dim ISBN As String = xelem.Elements("Book") _
        .Where(Function(x) x.Element("Author").Value.Equals("Ken Kesey")) _
        .[Select](Function(x) CStr(x.Element("ISBN").Value)).FirstOrDefault()

    Console.WriteLine(ISBN)
End Sub


问:
How send Email using Gmail api in swift
The Gmail Api has no clear documentation on how to do this, I have been trying with this but there are many things that are in the air.

I have sought external sources such. Source 1 and Source 2. The first seems to use the potential of the api, using the function queryForUsersMessagesSendWithUploadParameters.

While the second is about a little more. Although this in Objective-C is not a problem, except for the GTMMIMEDocument object, which do not know where or if it is obtained or a library.

My question is if someone has a somewhat cleaner and / or code easier to understand, or a better guide in which to send an email

答:
Here is the final solution I have finally make it work :

Podfile :

```<code>pod 'GoogleAPIClient/Gmail'
</code>```

Sample Swift 5 code:

```<code>import Foundation
import GoogleAPIClient

class GMailManager {

    let service = GTLServiceGmail()

    func sendEmail() {

        guard let query = GTLQueryGmail.queryForUsersMessagesSend(with: nil) else {
            return
        }

        let gtlMessage = GTLGmailMessage()
        gtlMessage.raw = self.generateRawString()

        query.message = gtlMessage

        self.service.executeQuery(query, completionHandler: { (ticket, response, error) -> Void in
            print("ticket \(String(describing: ticket))")
            print("response \(String(describing: response))")
            print("error \(String(describing: error))")
        })
    }

    func generateRawString() -> String {

        let dateFormatter:DateFormatter = DateFormatter()
        dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"; //RFC2822-Format
        let todayString:String = dateFormatter.string(from: NSDate() as Date)

        let rawMessage = "" +
            "Date: \(todayString)\r\n" +
            "From: <mail>\r\n" +
            "To: username <mail>\r\n" +
            "Subject: Test send email\r\n\r\n" +
            "Test body"

        print("message \(rawMessage)")

        return GTLEncodeWebSafeBase64(rawMessage.data(using: String.Encoding.utf8))
    }
}
</code>```

Title: How send Email using Gmail api in swift

Body:
Here is the final solution I have finally make it work :

Podfile :

pod 'GoogleAPIClient/Gmail'

Sample Swift 5 code:

import Foundation
import GoogleAPIClient

class GMailManager {

    let service = GTLServiceGmail()

    func sendEmail() {

        guard let query = GTLQueryGmail.queryForUsersMessagesSend(with: nil) else {
            return
        }

        let gtlMessage = GTLGmailMessage()
        gtlMessage.raw = self.generateRawString()

        query.message = gtlMessage

        self.service.executeQuery(query, completionHandler: { (ticket, response, error) -> Void in
            print("ticket \(String(describing: ticket))")
            print("response \(String(describing: response))")
            print("error \(String(describing: error))")
        })
    }

    func generateRawString() -> String {

        let dateFormatter:DateFormatter = DateFormatter()
        dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"; //RFC2822-Format
        let todayString:String = dateFormatter.string(from: NSDate() as Date)

        let rawMessage = "" +
            "Date: \(todayString)\r\n" +
            "From: <mail>\r\n" +
            "To: username <mail>\r\n" +
            "Subject: Test send email\r\n\r\n" +
            "Test body"

        print("message \(rawMessage)")

        return GTLEncodeWebSafeBase64(rawMessage.data(using: String.Encoding.utf8))
    }
}


问:
"Missing client token" when authenticating with login/pass on Hashicorp Vault
I'm trying to get login/pass authentication working on Vault.
When I try the method given in the API documentation here: https://www.vaultproject.io/api/auth/userpass/index.html#login

I get this error:

```<code>$ curl --request POST --data @payload.json https://<myurl>:8200/v1/auth/userpass/login/<mylogin> -k
{"errors":["missing client token"]}
</code>```

And I can't find information on this error. It makes me wonder what happens, because I want to authenticate with login/pass to get the token, so that's just normal to not have it.

Here is the content of the payload.json:

```<code>{
  "password": "foo"
}
</code>```

Is there any way to login with username/password? This is the only fallback method I have when the user does not know its token.

Thanks!

答:
In my case, i was not setting the vault token to the right environment variable.
you have to set the value to VAULT_TOKEN so that it uses it in subsequent request my env variable was Vault_Token and due to this it was always saying missing client token.

By default, Vault checks for this environment variable to find the token.

vault kv get --field "ACCESS_KEY_ID" secret/my-secret

Body:
I'm trying to get login/pass authentication working on Vault.
When I try the method given in the API documentation here: https://www.vaultproject.io/api/auth/userpass/index.html#login

I get this error:

$ curl --request POST --data @payload.json https://<myurl>:8200/v1/auth/userpass/login/<mylogin> -k
{"errors":["missing client token"]}

And I can't find information on this error. It makes me wonder what happens, because I want to authenticate with login/pass to get the token, so that's just normal to not have it.

Here is the content of the payload.json:

{
  "password": "foo"
}

Is there any way to login with username/password? This is the only fallback method I have when the user does not know its token.

Thanks!


问:
Clip or threshold a tensor using condition and zero pad the result in PyTorch
let's say I have a tensor like this

```<code>w = [[0.1, 0.7, 0.7, 0.8, 0.3],
    [0.3, 0.2, 0.9, 0.1, 0.5],
    [0.1, 0.4, 0.8, 0.3, 0.4]]
</code>```

Now I want to eliminate certain values base on some condition (for example greater than 0.5 or not)

```<code>w = [[0.1, 0.3],
     [0.3, 0.2, 0.1],
     [0.1, 0.4, 0.3, 0.4]]
</code>```

Then pad it to equal length:

```<code>w = [[0.1, 0.3, 0, 0],
     [0.3, 0.2, 0.1, 0],
     [0.1, 0.4, 0.3, 0.4]]
</code>```

and this is how I implemented it in pytorch:

```<code>w = torch.rand(3, 5)
condition = w <= 0.5
w = [w[i][condition[i]] for i in range(3)]
w = torch.nn.utils.rnn.pad_sequence(w)
</code>```

But apparently this is going to be extremely slow, mainly because of the list comprehension.
is there any better way to do it?

答:
Here's one straightforward way using boolean masking, tensor splitting, and then eventually padding the splitted tensors using torch.nn.utils.rnn.pad_sequence(...).

```<code># input tensor to work with
In [213]: w
Out[213]:
tensor([[0.1000, 0.7000, 0.7000, 0.8000, 0.3000],
        [0.3000, 0.2000, 0.9000, 0.1000, 0.5000],
        [0.1000, 0.4000, 0.8000, 0.3000, 0.4000]])

# values above this should be clipped from the input tensor
In [214]: clip_value = 0.5

# generate a boolean mask that satisfies the condition
In [215]: boolean_mask = (w <= clip_value)

# we need to sum the mask along axis 1 (needed for splitting)
In [216]: summed_mask = boolean_mask.sum(dim=1)

# a sequence of splitted tensors
In [217]: splitted_tensors = torch.split(w[boolean_mask], summed_mask.tolist())

# finally pad them along dimension 1 (or axis 1)
In [219]: torch.nn.utils.rnn.pad_sequence(splitted_tensors, 1)
Out[219]:
tensor([[0.1000, 0.3000, 0.0000, 0.0000],
        [0.3000, 0.2000, 0.1000, 0.5000],
        [0.1000, 0.4000, 0.3000, 0.4000]])
</code>```

A short note on efficiency: Using torch.split() is super efficient since it returns the splitted tensors as a view of the original tensor (i.e. no copy is made).

Body:
let's say I have a tensor like this

w = [[0.1, 0.7, 0.7, 0.8, 0.3],
    [0.3, 0.2, 0.9, 0.1, 0.5],
    [0.1, 0.4, 0.8, 0.3, 0.4]]

Now I want to eliminate certain values base on some condition (for example greater than 0.5 or not)

w = [[0.1, 0.3],
     [0.3, 0.2, 0.1],
     [0.1, 0.4, 0.3, 0.4]]

Then pad it to equal length:

w = [[0.1, 0.3, 0, 0],
     [0.3, 0.2, 0.1, 0],
     [0.1, 0.4, 0.3, 0.4]]

and this is how I implemented it in pytorch:

w = torch.rand(3, 5)
condition = w <= 0.5
w = [w[i][condition[i]] for i in range(3)]
w = torch.nn.utils.rnn.pad_sequence(w)

But apparently this is going to be extremely slow, mainly because of the list comprehension.
is there any better way to do it?

Body:
Here's one straightforward way using boolean masking, tensor splitting, and then eventually padding the splitted tensors using torch.nn.utils.rnn.pad_sequence(...).

# input tensor to work with
In [213]: w
Out[213]:
tensor([[0.1000, 0.7000, 0.7000, 0.8000, 0.3000],
        [0.3000, 0.2000, 0.9000, 0.1000, 0.5000],
        [0.1000, 0.4000, 0.8000, 0.3000, 0.4000]])

# values above this should be clipped from the input tensor
In [214]: clip_value = 0.5

# generate a boolean mask that satisfies the condition
In [215]: boolean_mask = (w <= clip_value)

# we need to sum the mask along axis 1 (needed for splitting)
In [216]: summed_mask = boolean_mask.sum(dim=1)

# a sequence of splitted tensors
In [217]: splitted_tensors = torch.split(w[boolean_mask], summed_mask.tolist())

# finally pad them along dimension 1 (or axis 1)
In [219]: torch.nn.utils.rnn.pad_sequence(splitted_tensors, 1)
Out[219]:
tensor([[0.1000, 0.3000, 0.0000, 0.0000],
        [0.3000, 0.2000, 0.1000, 0.5000],
        [0.1000, 0.4000, 0.3000, 0.4000]])

A short note on efficiency: Using torch.split() is super efficient since it returns the splitted tensors as a view of the original tensor (i.e. no copy is made).


问:
Azure Machine Learning (preview) to Customer Insights
I am trying to integrate MS Dynamics Customer Insights (CI) with the model I have built within the new Azure Machine Learning (designer). Currently, I see there is only an integration between CI and Azure Machine Learning studio (classic).

I have deployed my model behind a web service (REST) within new Azure Machine Learning however it is not getting picked up in CI. However, I am able to score/generate predictions from the API using a Python script.

Please recommend a way to integrate these two MS services or suggest an architecture where CI can pick up the results.

答:
I totally agree that there's a real opportunity for a more seamless integration between Azure ML and D365 (including CI). For me, I'm thinking about how cool would it be to have an ML Dataset be automatically created with D365 data that could be used in the ML designer. After which the winning model could be registered, then made available inside D365 as a field that would score things in real time.

If you an "idea" on the forum below. My team and I will upvote it!

https://experience.dynamics.com/ideas/


问:
How to delete part of a nested collection in Firebase?
I have not succeeded in deleting part of a nested collection in Firebase. Here's a photo of the collection:

And this is what I am trying to do, to delete, for e.g., 0A7vtcos... inside of offeredServices

```<code>async function deleteOfferedServiceFromDatabase() {
   const businessRef = await db.collection("businessesPendingAdminApproval")
      .doc(businessId)
      .collection('offeredServices')
      .doc(props.id) //props.id is equivalent to '0A7vtcos...'
      .get()

   businessRef.delete() //won't work
}

deleteOfferedServiceFromDatabase()
</code>```

答:
Your document doesn't actually have any nested subcollections.  It has a nested field in a document field called "offeredServices".

If you want to remove a nested field, you will have to update the document by specifying the nested field name (using field value dot notation), and telling Firestore to remove the field using FieldValue.delete():

```<code>async function deleteOfferedServiceFromDatabase() {
  const businessRef = db
    .collection("businessesPendingAdminApproval")
    .doc(businessId)

   await businessRef.update(`offeredServices.${props.id}`, FieldValue.delete())
}
</code>```

Body:
I have not succeeded in deleting part of a nested collection in Firebase. Here's a photo of the collection:

And this is what I am trying to do, to delete, for e.g., 0A7vtcos... inside of offeredServices

async function deleteOfferedServiceFromDatabase() {
   const businessRef = await db.collection("businessesPendingAdminApproval")
      .doc(businessId)
      .collection('offeredServices')
      .doc(props.id) //props.id is equivalent to '0A7vtcos...'
      .get()

   businessRef.delete() //won't work
}

deleteOfferedServiceFromDatabase()

Body:
Your document doesn't actually have any nested subcollections.  It has a nested field in a document field called "offeredServices".

If you want to remove a nested field, you will have to update the document by specifying the nested field name (using field value dot notation), and telling Firestore to remove the field using FieldValue.delete():

async function deleteOfferedServiceFromDatabase() {
  const businessRef = db
    .collection("businessesPendingAdminApproval")
    .doc(businessId)

   await businessRef.update(`offeredServices.${props.id}`, FieldValue.delete())
}


问:
Whats the issue in reset button of JS counter?
This is the script, it work fine as you can see but this reset functionality have some issue, it turns the value to 0 but when again increase the value it starts from the last stored value, whats the issue?

This is the CSS of the counter application this we help you to run this file.

Ans this is the html file is pretty much good but just in issue with script

    var counter = 0;
    $("#box").text(counter);

    function reset() {
        counter = 0;
        $("#box").text(counter);
    }

    function inc() {
        counter = counter + 1;
        $("#box").text(counter);

    }

    function dec() {
        counter = counter - 1;
        $("#box").text(counter);

    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}

body {
    height: 100vh;
}

.main {
    background: #efefef;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    padding: 30px;
}

.main h1 {
    margin-bottom: 50px;
}

#box {
    height: 50px;
    line-height: 50px;
    background: #efefef;
    text-align: center;
    margin-top: 40px;
    box-shadow: 1px 1px 5px #000;
    font-size: 30px;
}

.btn {
    display: flex;
}

.inc,
.dec {
    margin: 10px;
    padding: 10px;
    background: #fcfbfc;
    margin-top: 30px;
    text-transform: uppercase;
    cursor: pointer;
}

.reset {
    background: orange;
    padding: 5px;
    margin-top: 10px;
    cursor: pointer;
}</code>```

<!DOCTYPE html>

    <link rel="stylesheet" href="counter.css" type="text/css">

    <title>Counter</title>

Counter App

                Increase

                Decrease

            RESET

```

答:
Added reset counter variable to 0 in reset() function.

var counter = 0;
    $("#box").text(counter);

    function reset() {
    counter = 0;
        $("#box").text(0);
    }

    function inc() {
        counter = counter + 1;
        $("#box").text(counter);

    }

    function dec() {
        counter = counter - 1;
        $("#box").text(counter);

    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}

body {
    height: 100vh;
}

.main {
    background: #efefef;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    padding: 30px;
}

.main h1 {
    margin-bottom: 50px;
}

#box {
    /* width: 50px; */
    height: 50px;
    line-height: 50px;
    background: #efefef;
    text-align: center;
    margin-top: 40px;
    box-shadow: 1px 1px 5px #000;
    font-size: 30px;
}

.btn {
    display: flex;
}

.inc,
.dec {
    margin: 10px;
    padding: 10px;
    background: #fcfbfc;
    margin-top: 30px;
    text-transform: uppercase;
    cursor: pointer;
}

.reset {
    background: orange;
    padding: 5px;
    margin-top: 10px;
    cursor: pointer;
}</code>```

<!DOCTYPE html>

    <link rel="stylesheet" href="counter.css" type="text/css">

    <title>Counter</title>

Counter App

                Increase

                Decrease

            RESET

```

Body:
This is the script, it work fine as you can see but this reset functionality have some issue, it turns the value to 0 but when again increase the value it starts from the last stored value, whats the issue?

This is the CSS of the counter application this we help you to run this file.

Ans this is the html file is pretty much good but just in issue with script

    var counter = 0;
    $("#box").text(counter);

    function reset() {
        counter = 0;
        $("#box").text(counter);
    }

    function inc() {
        counter = counter + 1;
        $("#box").text(counter);

    }

    function dec() {
        counter = counter - 1;
        $("#box").text(counter);

    }

* {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}

body {
    height: 100vh;
}

.main {
    background: #efefef;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    padding: 30px;
}

.main h1 {
    margin-bottom: 50px;
}

#box {
    height: 50px;
    line-height: 50px;
    background: #efefef;
    text-align: center;
    margin-top: 40px;
    box-shadow: 1px 1px 5px #000;
    font-size: 30px;
}

.btn {
    display: flex;
}

.inc,
.dec {
    margin: 10px;
    padding: 10px;
    background: #fcfbfc;
    margin-top: 30px;
    text-transform: uppercase;
    cursor: pointer;
}

.reset {
    background: orange;
    padding: 5px;
    margin-top: 10px;
    cursor: pointer;
}

<!DOCTYPE html>

    <link rel="stylesheet" href="counter.css" type="text/css">

    <title>Counter</title>

Counter App

                Increase

                Decrease

            RESET

Body:
Added reset counter variable to 0 in reset() function.

var counter = 0;
    $("#box").text(counter);

    function reset() {
    counter = 0;
        $("#box").text(0);
    }

    function inc() {
        counter = counter + 1;
        $("#box").text(counter);

    }

    function dec() {
        counter = counter - 1;
        $("#box").text(counter);

    }

* {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}

body {
    height: 100vh;
}

.main {
    background: #efefef;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    padding: 30px;
}

.main h1 {
    margin-bottom: 50px;
}

#box {
    /* width: 50px; */
    height: 50px;
    line-height: 50px;
    background: #efefef;
    text-align: center;
    margin-top: 40px;
    box-shadow: 1px 1px 5px #000;
    font-size: 30px;
}

.btn {
    display: flex;
}

.inc,
.dec {
    margin: 10px;
    padding: 10px;
    background: #fcfbfc;
    margin-top: 30px;
    text-transform: uppercase;
    cursor: pointer;
}

.reset {
    background: orange;
    padding: 5px;
    margin-top: 10px;
    cursor: pointer;
}

<!DOCTYPE html>
<html lang="en">

<head>
    <link rel="stylesheet" href="counter.css" type="text/css">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <title>Counter</title>
</head>

<body>
    <div class="main">
        <h1 style="font-family: sans-serif;">Counter App</h1>

        <div id="box">

        </div>
        <div class="btn">
            <div class="inc" id="inc" onclick="inc();">
                Increase
            </div>
            <div class="dec" id="dec" onclick="dec();">
                Decrease
            </div>
        </div>

        <div class="reset" onclick="reset();">
            RESET
        </div>
    </div>

</body>
</html>


问:
Sharing a landing page in LinkedIn: wrong image
I am having some issues sharing this link on LinkedIn but not in other Social Media platforms: https://formscloud.iese.edu/landings-open-day-pamplona-sept-2017 . I have implemented correctly the Script for the Open Graph but it seems to be fetching another image than the one i told it to. The script is taken from a previous landing page and it is working on that one, but doesn't seem to be working on this one. I've seen LinkedIn actually has a buffer for shared content of 7 days.

I would need it now, I wanted to know if you can give me a hand on this and may be able to re-crawl my page.

Code

```<code><meta property="og:title" content="IESE Business School" />
<meta property="og:url" content="formscloud.iese.edu/landings-executive-open-day-sept-palma-2017/…;
<meta property="og:type" content="website" />
<meta property="og:image" content="iese.edu/Aplicaciones/upload/FTranking171222x649.png " />
<meta property="og:image:width" content="400" />
<meta property="og:image:height" content="300" />
<meta property="og:description" content="MBA - IESE Business School" />
</code>```

It's on

答:
If you have absolutely no idea how LinkedIn is choosing the thumbnail for sharing your webpage, insert your URL into the LinkedIn Post Inspector.

So, thanks to the magic of Archive.org, I am able to see a copy of the HTML on your page. .  So, here's the problem for your page most likely...

```<code><meta property="og:image"
content="https://web.archive.org/web/20170720150955im_/http://www.iese.edu/Aplicaciones/upload/FTranking171222x649.png

"/>
</code>```

You need to close properties like this: <meta location="someurl">.  What you have is: <meta location="someurl (linebreak) ">.

Also, it appears that your image never existed or was uploaded: OG: Image Tag 404.

Body:
I am having some issues sharing this link on LinkedIn but not in other Social Media platforms: https://formscloud.iese.edu/landings-open-day-pamplona-sept-2017 . I have implemented correctly the Script for the Open Graph but it seems to be fetching another image than the one i told it to. The script is taken from a previous landing page and it is working on that one, but doesn't seem to be working on this one. I've seen LinkedIn actually has a buffer for shared content of 7 days.

I would need it now, I wanted to know if you can give me a hand on this and may be able to re-crawl my page.

Code

<meta property="og:title" content="IESE Business School" />
<meta property="og:url" content="formscloud.iese.edu/landings-executive-open-day-sept-palma-2017/…;
<meta property="og:type" content="website" />
<meta property="og:image" content="iese.edu/Aplicaciones/upload/FTranking171222x649.png " />
<meta property="og:image:width" content="400" />
<meta property="og:image:height" content="300" />
<meta property="og:description" content="MBA - IESE Business School" />

It's on

Body:
If you have absolutely no idea how LinkedIn is choosing the thumbnail for sharing your webpage, insert your URL into the LinkedIn Post Inspector.

So, thanks to the magic of Archive.org, I am able to see a copy of the HTML on your page. .  So, here's the problem for your page most likely...

<meta property="og:image"
content="https://web.archive.org/web/20170720150955im_/http://www.iese.edu/Aplicaciones/upload/FTranking171222x649.png

"/>

You need to close properties like this: <meta location="someurl">.  What you have is: <meta location="someurl (linebreak) ">.

Also, it appears that your image never existed or was uploaded: OG: Image Tag 404.


问:
Python prime list
```<code>integer = int(input("Enter an integer: "))
if integer >= 2:
    print(2)
for i in range(2, integer + 1): # range 2,3,...,integer (excludes 1)
    for j in range(2, i): # we are going to try dividing by these
        if i % j == 0: # not prime
            break
        else: # is prime
            print(i)
</code>```

input:

7
```

<p>output:</p>

<pre class="lang-none prettyprint-override"><code>2
3
5
5
5
7
7
7
7
7
</code>```

output I want:

2
3
5
7
```

adding more detail to get past error:

It looks like your post is mostly code; please add some more details.

答:
You're printing i for every value of j that doesn't divide it, until you get a value that does divide it and you execute break.

You should only print i when you don't break out of the loop. Put the else: statement on the for loop, not if. This else: statement is executed when the loop finishes normally instead of breaking.

```<code>for i in range(2, integer + 1): # range 2,3,...,integer (excludes 1)
    for j in range(2, i): # we are going to try dividing by these
        if i % j == 0: # not prime
            break
    else: # is prime
        print(i)
</code>```

Title: Python prime list

Body:
integer = int(input("Enter an integer: "))
if integer >= 2:
    print(2)
for i in range(2, integer + 1): # range 2,3,...,integer (excludes 1)
    for j in range(2, i): # we are going to try dividing by these
        if i % j == 0: # not prime
            break
        else: # is prime
            print(i)

input:

7

output:

2
3
5
5
5
7
7
7
7
7

output I want:

2
3
5
7

adding more detail to get past error:

It looks like your post is mostly code; please add some more details.

Body:
You're printing i for every value of j that doesn't divide it, until you get a value that does divide it and you execute break.

You should only print i when you don't break out of the loop. Put the else: statement on the for loop, not if. This else: statement is executed when the loop finishes normally instead of breaking.

for i in range(2, integer + 1): # range 2,3,...,integer (excludes 1)
    for j in range(2, i): # we are going to try dividing by these
        if i % j == 0: # not prime
            break
    else: # is prime
        print(i)


答:
Using your posted data.  This should approximate the desired design.

First step, Transform the data from a wide format to a long format using the pivot_longer function from tidyr.

Then plot the data using "depth" as the independent variable and the parameters' values as the dependent variables.

Then use facet_wrap() to separate the plots.  coord_flip() will make the independent variable (Depth) appear on the y-axis.

```<code>#fixed 1 column of data.
originaldata$ZrRb <- as.numeric(as.character(originaldata$ZrRb))
library(tidyr)
#Make wide
wapITRAX<-pivot_longer(originaldata, -1, names_to="parameter", values_to = "value")

library(ggplot2)
ggplot(wapITRAX, aes(x = Depth , y = value))+
   labs(x = "Depth (cm)")+
   geom_line() +
   theme_classic() +
   coord_flip() +
   scale_x_reverse() +
   facet_wrap(vars(parameter), nrow=1, scales = "free_x")
</code>```

Title: Stratigraphic plot of geochemical data using ggplot2 and tidypaleo

Body:
I am trying to create a stratigraphic plot of geochemical element data which should be possible using package tidypaleo.

I want multiple plots of the different element data with Depth (cm) downcore set as the y axis. The data look as follows.

Image of data

I am using this code:

ggplot(wapITRAX, aes(x =BrTi , y = wapITRAX$Depth))+
labs(y = "Depth (cm)")+
geom_lineh()+
theme_classic()+
scale_y_reverse()

However, this only plots one element and I am trying to achieve a plot like this Image of plot

> dput(head(wapITRAX))
structure(list(Depth = 0:5, IncCoh = c(6.049230907, 5.975282432,
5.736199822, 5.658584418, 5.659008377, 5.597103404), BrTi =
c(50.50197628,
22.09236453, 23.48370927, 18.62638581, 14.36924414, 17.48777896
), AlIncCOh = c(16.69633736, 8.200449193, 23.70907643, 20.32310407,
28.62692352, 26.44224866), BrCl = c(8.04090623, 4.306048968,
3.417836951, 3.156895904, 2.787628518, 2.059316731), FeTi =
c(332.715415,
235.9371921, 372.726817, 390.7871397, 396.986099, 495.2624867
), CaTi = c(4.071146245, 3.27955665, 4.395989975, 3.677383592,
3.028670721, 4.523910733), ZrRb = structure(c(363L, 447L, 407L,
395L, 450L, 410L), .Label = c("#DIV/0!", "0.447638604",
"0.478169284",
"0.54554134", "0.548501778", "0.561420163", "0.579454254",
"0.579498861",
"0.580801291", "0.589758019", "0.590194076", "0.590277778",
"0.591357754",
"0.592870544", "0.593851133", "0.598519653", "0.599931082",
"0.600979737",
"0.601426307", "0.611710677", "0.617065868", "0.618499405",
"0.621310093",
"0.627720871", "0.63775246", "0.64005168", "0.643958869",
"0.644371941",
"0.645605974", "0.645661658", "0.646672915", "0.647348952",
"0.651578947",
"0.652401176", "0.656186383", "0.657906264", "0.658835905",
"0.662074554",
"0.662361624", "0.669589393", "0.67103429", "0.671371769",
"0.674335863",
"0.674781688", "0.676097561", "0.676639083", "0.677849462",
"0.680497925",
"0.680610514", "0.680725971", "0.683906537", "0.68855859",
"0.689067202",
"0.692353115", "0.692732291", "0.695411392", "0.696067091",
"0.696794872",
"0.699376436", "0.701762744", "0.702015197", "0.702432938",
"0.70361991",
"0.705235754", "0.705426357", "0.708084164", "0.708258528",
"0.708925221",
"0.715226656", "0.715263314", "0.717828827", "0.718975706",
"0.719799305",
"0.720363636", "0.72476489", "0.725426857", "0.725461098",
"0.726030739",
"0.7267645", "0.726998188", "0.727170554", "0.727533265",
"0.730362368",
"0.731182796", "0.735042735", "0.735849057", "0.736184046",
"0.737214792",
"0.738692342", "0.742223591", "0.742639327", "0.742714724",
"0.744126167",
"0.745790081", "0.746207701", "0.746606335", "0.747041077",
"0.749019608",
"0.751204307", "0.751326495", "0.752443737", "0.752994012",
"0.753398969",
"0.754587869", "0.755151515", "0.755466053", "0.756316411",
"0.757107679",
"0.759175941", "0.76070965", "0.761635833", "0.763760166",
"0.763861189",
"0.764076577", "0.765001936", "0.765509391", "0.765795207",
"0.76598579",
"0.767080745", "0.767225748", "0.767262192", "0.770291777",
"0.771194699",
"0.772540984", "0.774533358", "0.77486376", "0.777252364",
"0.778319123",
"0.778445883", "0.779076739", "0.779310345", "0.782186577",
"0.78238342",
"0.782541093", "0.785497178", "0.787594824", "0.788230584",
"0.788916736",
"0.789033068", "0.789052737", "0.789177605", "0.789596048",
"0.790439133",
"0.791078234", "0.792993631", "0.794899978", "0.795265235",
"0.795432921",
"0.798130469", "0.79861957", "0.798894446", "0.799410029",
"0.799679487",
"0.800096223", "0.800119868", "0.800280899", "0.800947004",
"0.80293448",
"0.804118993", "0.804120112", "0.805092452", "0.806161301",
"0.81631016",
"0.816337149", "0.81638756", "0.81827622", "0.818899466",
"0.81993865",
"0.821925431", "0.825329202", "0.825608077", "0.826135414",
"0.826325411",
"0.827108292", "0.829798658", "0.832460733", "0.832814584",
"0.833845295",
"0.833908046", "0.833980583", "0.83741705", "0.837604457",
"0.838292367",
"0.838860231", "0.839741935", "0.846485664", "0.846740374",
"0.84679304
 1",
"0.84734599", "0.850027518", "0.850077882", "0.854863613",
"0.85565883",
"0.85591192", "0.857095047", "0.858967536", "0.85897779",
"0.859192457",
"0.859239235", "0.860408412", "0.860505166", "0.8609918",
"0.862821134",
"0.867779204", "0.872207328", "0.872918493", "0.873888706",
"0.874140666",
"0.877452229", "0.879856851", "0.88003663", "0.880155093",
"0.881013197",
"0.882190156", "0.882319978", "0.883029342", "0.883316008",
"0.884908053",
"0.885431692", "0.885849846", "0.889082969", "0.89763062",
"0.898384089",
"0.898527865", "0.9", "0.900719424", "0.904636261", "0.904913848",
"0.905223479", "0.908485273", "0.911212059", "0.916470588",
"0.917162698",
"0.917470525", "0.917952884", "0.918054256", "0.918781726",
"0.922268448",
"0.925987182", "0.926287744", "0.933958724", "0.939701616",
"0.940987438",
"0.941196465", "0.943041526", "0.946832078", "0.947419907",
"0.948080043",
"0.949085366", "0.950099404", "0.950502912", "0.950704225",
"0.953596288",
"0.954868709", "0.95505992", "0.955361596", "0.956422018",
"0.95671509",
"0.959064327", "0.96165309", "0.964232489", "0.965528048",
"0.965874467",
"0.968717195", "0.970270821", "0.971573209", "0.973415133",
"0.974608081",
"0.974986972", "0.978223496", "0.97935022", "0.980142566",
"0.981730052",
"0.982819606", "0.987483236", "0.989587207", "0.991002571",
"0.991932655",
"0.995306859", "0.997555012", "1.001706485", "1.002357873",
"1.005146199",
"1.010493827", "1.011544012", "1.013038906", "1.013469577",
"1.015357613",
"1.01541976", "1.015544041", "1.015937059", "1.016162826",
"1.019393939",
"1.019529957", "1.019994873", "1.028932491", "1.029518072",
"1.030101225",
"1.032310705", "1.03344968", "1.036769138", "1.037322515",
"1.041150092",
"1.041459782", "1.041961577", "1.042347697", "1.047411444",
"1.048390581",
"1.057811121", "1.060218978", "1.065395654", "1.06921167",
"1.071509648",
"1.073730469", "1.076014602", "1.077266637", "1.079983072",
"1.083003953",
"1.086196504", "1.086445657", "1.0867266", "1.0905", "1.092152628",
"1.094730942", "1.095692666", "1.1074142", "1.109534807",
"1.111154446",
"1.111188325", "1.113985094", "1.114045618", "1.128810226",
"1.129375525",
"1.132705479", "1.154833837", "1.155201819", "1.158940397",
"1.161348047",
"1.162953533", "1.175788329", "1.178036097", "1.179280397",
"1.18116463",
"1.198506534", "1.203134068", "1.207592892", "1.208610568",
"1.212525667",
"1.212841855", "1.214403157", "1.216756112", "1.228462377",
"1.23305986",
"1.241758242", "1.258212878", "1.265571914", "1.265707797",
"1.272666444",
"1.279325988", "1.289559543", "1.291191103", "1.296541003",
"1.305111821",
"1.315201411", "1.342263532", "1.344827586", "1.347944377",
"1.352831595",
"1.377717391", "1.37771934", "1.385440181", "1.403358682",
"1.411889597",
"1.412269549", "1.412544902", "1.433843384", "1.444088526",
"1.473706353",
"1.50172117", "1.508521601", "1.53030303", "1.532658694",
"1.537642783",
"1.54340949", "1.558746736", "1.595342983", "1.596774194",
"1.596969697",
"1.630653266", "1.702558635", "1.70468948", "1.718568102",
"1.740819711",
"1.760157274", "1.775510204", "1.804859813", "1.814081408",
"1.816513761",
"1.849050827", "1.870188679", "1.880195599", "1.887061404",
"1.91858679",
"1.929152149", "1.944140197", "1.946996466", "1.986547085",
"2.007683864",
"2.070983811", "2.099778271", "2.156359393", "2.159613059",
"2.163963964",      "2.25951087", "2.261603376", "2.329896907",
"2.402555911", "2.414500684",
"2.444075305", "2.450268817", "2.484520124", "2.51119403",
"2.515064562",
"2.526086957", "2.554", "2.609715243", "2.61965812", "2.643854749",
"2.704166667", "2.883275261", "3.013186813", "3.02739726",
"3.206896552",
"3.320930233", "3.411627907", "3.688931298", "3.709677419",
"3.748267898",
"3.878865979", "3.936440678", "3.994230769", "33.15909091",
"4.095854922",
"4.29330254", "4.390957447", "4.514634146", "4.6367713",
"4.847665848",
"5.284023669", "5.387755102", "6.171339564", "6.183908046",
"6.36121673",
"6.847826087", "7.003496503", "7.193220339", "8.160550459",
"8.751879699"
), class = "factor"), MnFe = c(0.012176723, 0.010329834,
0.009460859,
0.004488071, 0.0033725, 0.003435313), MnIncCoh = c(169.4430276,
331.1977339, 490.5686845, 279.5752228, 272.3091921, 286.0408118
), CuRb = c(0.392971246, 1.484304933, 0.735426009, 0.491651206,
1.142857143, 0.4345898)), row.names = c(NA, 6L), class =
"data.frame")

Body:
Using your posted data.  This should approximate the desired design.

First step, Transform the data from a wide format to a long format using the pivot_longer function from tidyr.

Then plot the data using "depth" as the independent variable and the parameters' values as the dependent variables.

Then use facet_wrap() to separate the plots.  coord_flip() will make the independent variable (Depth) appear on the y-axis.

#fixed 1 column of data.
originaldata$ZrRb <- as.numeric(as.character(originaldata$ZrRb))
library(tidyr)
#Make wide
wapITRAX<-pivot_longer(originaldata, -1, names_to="parameter", values_to = "value")

library(ggplot2)
ggplot(wapITRAX, aes(x = Depth , y = value))+
   labs(x = "Depth (cm)")+
   geom_line() +
   theme_classic() +
   coord_flip() +
   scale_x_reverse() +
   facet_wrap(vars(parameter), nrow=1, scales = "free_x")


问:
Get DataRow if column names in a string array have matching values in a string array
I'm trying to get a DataRow from a dtResult datatable if column name in [colName] list has a matching value as [grbByValue] list. my goal in the below code is to get [test1] and [test2] return datarow from dtResult and  should be the same as [update] (which is hard coded). but have issue in both test1 & test2. test1 has error and don't know how fix and test2 is returning null.

rule is a DataTable that looks like this:

All the below logic is run for each row of rule.

dtResult is also a DataTable that looks like this:

EDITED CODE

```<code>string[] grpby = { "ageband","gender","code"};
List<string> grbByValue = new List<string>() { "1","85+","1","1010"};

        DataTable dtResult = new DataTable();
        DataColumn dc = dtResult.Columns.Add("id", typeof(int));
        dc.AutoIncrement = true;
        dc.AutoIncrementSeed = 1;
        dc.AutoIncrementStep = 1;

        dtResult.Columns.Add("DataSourceID");
        dtResult.Columns["DataSourceID"].DefaultValue = "1";
        dtResult.Columns.Add("RuleID");
        dtResult.Columns.Add("GroupBy0");
        dtResult.Columns.Add("GroupBy1");
        dtResult.Columns.Add("GroupBy2");
        dtResult.Columns.Add("GroupBy3");
        dtResult.Columns.Add("GroupBy4");
        dtResult.Columns.Add("GroupBy5");
        dtResult.Columns.Add("Result", typeof(decimal));
        dtResult.Columns["Result"].DefaultValue = 0.00;

        var colName = (from a in dtResult.Columns.Cast<DataColumn>()
                       where a.ColumnName.ToString().StartsWith("GroupBy")
                       select a.ColumnName).OrderBy(x => x).ToList();
        colName.Insert(0, "RuleID");
        colName = colName.GetRange(0, grbByValue.Count);

        //comment/UNCOMMENT below to test [test1]
        //DataRow z = dtResult.NewRow();
        //for (int i = 0; i < grbByValue.Count; i++)
        //{
        //    z[colName[i]] = grbByValue[i];
        //}
        //dtResult.Rows.Add(z.ItemArray);

        var distDtResult = dtResult.DefaultView.ToTable(true, colName.ToArray());
        bool exist = false;
        DataRow update = null;

        foreach (DataRow dr in distDtResult.Rows)
        {
            var row = dr.ItemArray.ToList();
            exist = row.SequenceEqual(grbByValue);
            if (exist == true)
            {
                //var test1 = (from t1 in distDtResult.AsEnumerable().Where(r => r.ItemArray == dr.ItemArray)
                //             join t2 in (from m in dtResult.AsEnumerable()
                //                         select new
                //                         {
                //                             //ideally the below column list will be derived from [colName] dynamically
                //                             RuleID = m.Field<string>("RuleID"),
                //                             GroupBy0 = m.Field<string>("GroupBy0"),
                //                             GroupBy1 = m.Field<string>("GroupBy1"),
                //                             GroupBy2 = m.Field<string>("GroupBy2")
                //                         }) on t1.ItemArray equals t2.ItemArray
                //             select new
                //             {
                //                 t2
                //             }).FirstOrDefault();

                update = dtResult.AsEnumerable().Where(r =>
                                                r.Field<int>("id") == 1 &&
                                                r.Field<string>("DataSourceID") == "1" &&
                                                r.Field<string>("RuleID") == "1" &&
                                                r.Field<string>("GroupBy0") == "85+" &&
                                                r.Field<string>("GroupBy1") == "1" &&
                                                r.Field<string>("GroupBy2") == "1010").FirstOrDefault();

                break;
            }
        }

        if (exist == false)
        {
            DataRow a = dtResult.NewRow();
            for (int i = 0; i < grbByValue.Count; i++)
            {
                a[colName[i]] = grbByValue[i];
            }
            dtResult.Rows.Add(a.ItemArray);

            var test2 = dtResult.AsEnumerable().Where(r => r.ItemArray.Equals(a.ItemArray)).FirstOrDefault();
            update = dtResult.AsEnumerable().Where(r =>
                                               r.Field<int>("id") == 1 &&
                                               r.Field<string>("DataSourceID") == "1" &&
                                               r.Field<string>("RuleID") == "1" &&
                                               r.Field<string>("GroupBy0") == "85+" &&
                                               r.Field<string>("GroupBy1") == "1" &&
                                               r.Field<string>("GroupBy2") == "1010").FirstOrDefault();

        }
</code>```

答:
This might be a good starting point, at least to better ask questions and move towards an answer.</p>

```<code>string[] colName = { "RuleID", "GroupBy0", "GroupBy1", "GroupBy2" };

// "All the below logic is run for each row of rule"
// this goes through each row of the rule DataTable
foreach (DataRow rule in ruleTable.Rows)
{
    // This is going to be equivalent to the grpby variable you specified
    var groupRules = rule.Field<string>("GroupBy").ToString().Split("|");

    // Some sort of mapping may need to go here to go from "ageband" to "GroupBy0", "gender" to "GroupBy1", etc.

    foreach(DataRow row in dtResult.Rows)
    {
        DataTable distDtResult = dtResult.DefaultView.ToTable(true, colName);

        var updateTEST = from dr in distDtResult.AsEnumerable()
                         where dr.Field<string>("RuleID") == rule["RuleID"].ToString()
                         && dr.Field<string>("GroupBy0") == row["GroupBy0"].ToString() // ageband
                         && dr.Field<string>("GroupBy1") == row["GroupBy1"].ToString() // gender
                         && dr.Field<string>("GroupBy2") == row["GroupBy2"].ToString() // code
                         // more
                         select dr;
    }
}
</code>```

Body:
I'm trying to get a DataRow from a dtResult datatable if column name in [colName] list has a matching value as [grbByValue] list. my goal in the below code is to get [test1] and [test2] return datarow from dtResult and  should be the same as [update] (which is hard coded). but have issue in both test1 & test2. test1 has error and don't know how fix and test2 is returning null.

rule is a DataTable that looks like this:

All the below logic is run for each row of rule.

dtResult is also a DataTable that looks like this:

EDITED CODE

string[] grpby = { "ageband","gender","code"};
List<string> grbByValue = new List<string>() { "1","85+","1","1010"};

        DataTable dtResult = new DataTable();
        DataColumn dc = dtResult.Columns.Add("id", typeof(int));
        dc.AutoIncrement = true;
        dc.AutoIncrementSeed = 1;
        dc.AutoIncrementStep = 1;

        dtResult.Columns.Add("DataSourceID");
        dtResult.Columns["DataSourceID"].DefaultValue = "1";
        dtResult.Columns.Add("RuleID");
        dtResult.Columns.Add("GroupBy0");
        dtResult.Columns.Add("GroupBy1");
        dtResult.Columns.Add("GroupBy2");
        dtResult.Columns.Add("GroupBy3");
        dtResult.Columns.Add("GroupBy4");
        dtResult.Columns.Add("GroupBy5");
        dtResult.Columns.Add("Result", typeof(decimal));
        dtResult.Columns["Result"].DefaultValue = 0.00;

        var colName = (from a in dtResult.Columns.Cast<DataColumn>()
                       where a.ColumnName.ToString().StartsWith("GroupBy")
                       select a.ColumnName).OrderBy(x => x).ToList();
        colName.Insert(0, "RuleID");
        colName = colName.GetRange(0, grbByValue.Count);

        //comment/UNCOMMENT below to test [test1]
        //DataRow z = dtResult.NewRow();
        //for (int i = 0; i < grbByValue.Count; i++)
        //{
        //    z[colName[i]] = grbByValue[i];
        //}
        //dtResult.Rows.Add(z.ItemArray);

        var distDtResult = dtResult.DefaultView.ToTable(true, colName.ToArray());
        bool exist = false;
        DataRow update = null;

        foreach (DataRow dr in distDtResult.Rows)
        {
            var row = dr.ItemArray.ToList();
            exist = row.SequenceEqual(grbByValue);
            if (exist == true)
            {
                //var test1 = (from t1 in distDtResult.AsEnumerable().Where(r => r.ItemArray == dr.ItemArray)
                //             join t2 in (from m in dtResult.AsEnumerable()
                //                         select new
                //                         {
                //                             //ideally the below column list will be derived from [colName] dynamically
                //                             RuleID = m.Field<string>("RuleID"),
                //                             GroupBy0 = m.Field<string>("GroupBy0"),
                //                             GroupBy1 = m.Field<string>("GroupBy1"),
                //                             GroupBy2 = m.Field<string>("GroupBy2")
                //                         }) on t1.ItemArray equals t2.ItemArray
                //             select new
                //             {
                //                 t2
                //             }).FirstOrDefault();

                update = dtResult.AsEnumerable().Where(r =>
                                                r.Field<int>("id") == 1 &&
                                                r.Field<string>("DataSourceID") == "1" &&
                                                r.Field<string>("RuleID") == "1" &&
                                                r.Field<string>("GroupBy0") == "85+" &&
                                                r.Field<string>("GroupBy1") == "1" &&
                                                r.Field<string>("GroupBy2") == "1010").FirstOrDefault();

                break;
            }
        }

        if (exist == false)
        {
            DataRow a = dtResult.NewRow();
            for (int i = 0; i < grbByValue.Count; i++)
            {
                a[colName[i]] = grbByValue[i];
            }
            dtResult.Rows.Add(a.ItemArray);

            var test2 = dtResult.AsEnumerable().Where(r => r.ItemArray.Equals(a.ItemArray)).FirstOrDefault();
            update = dtResult.AsEnumerable().Where(r =>
                                               r.Field<int>("id") == 1 &&
                                               r.Field<string>("DataSourceID") == "1" &&
                                               r.Field<string>("RuleID") == "1" &&
                                               r.Field<string>("GroupBy0") == "85+" &&
                                               r.Field<string>("GroupBy1") == "1" &&
                                               r.Field<string>("GroupBy2") == "1010").FirstOrDefault();

        }

Body:
This might be a good starting point, at least to better ask questions and move towards an answer.

string[] colName = { "RuleID", "GroupBy0", "GroupBy1", "GroupBy2" };

// "All the below logic is run for each row of rule"
// this goes through each row of the rule DataTable
foreach (DataRow rule in ruleTable.Rows)
{
    // This is going to be equivalent to the grpby variable you specified
    var groupRules = rule.Field<string>("GroupBy").ToString().Split("|");

    // Some sort of mapping may need to go here to go from "ageband" to "GroupBy0", "gender" to "GroupBy1", etc.

    foreach(DataRow row in dtResult.Rows)
    {
        DataTable distDtResult = dtResult.DefaultView.ToTable(true, colName);

        var updateTEST = from dr in distDtResult.AsEnumerable()
                         where dr.Field<string>("RuleID") == rule["RuleID"].ToString()
                         && dr.Field<string>("GroupBy0") == row["GroupBy0"].ToString() // ageband
                         && dr.Field<string>("GroupBy1") == row["GroupBy1"].ToString() // gender
                         && dr.Field<string>("GroupBy2") == row["GroupBy2"].ToString() // code
                         // more
                         select dr;
    }
}


问:
SQL Get current month
I have table1 with data

```<code>file  Startdate
A     2020-05-01
B     2020-06-01
</code>```

We have today is 2020-06-01 and I could use Select and where startdate ='2020-06-01'

But I try this query and not get 2020-06-01

```<code>select file from table1
where
 startdate >= dateadd(month, -1, datefromparts(year(getdate()), month(getdate()), 1))
         and startdate < datefromparts(year(getdate()), month(getdate()), 1)
</code>```

Please correct me. Thank you

答:
```<code>select * from table1
where StartDate= cast(getdate() as date)
</code>```

Title: SQL Get current month

Body:
I have table1 with data

file  Startdate
A     2020-05-01
B     2020-06-01

We have today is 2020-06-01 and I could use Select and where startdate ='2020-06-01'

But I try this query and not get 2020-06-01

select file from table1
where
 startdate >= dateadd(month, -1, datefromparts(year(getdate()), month(getdate()), 1))
         and startdate < datefromparts(year(getdate()), month(getdate()), 1)

Please correct me. Thank you