问:
SQL generate group number
I try to generate a group number based on the O_Diagnosis operation. I would like to group the operations between the current and the next O_Diagnosis operation.

The problem is that this data doesn't have any grouping capable columns. So I need to generate this column almost from scratch. What I would like to achieve is the following:

```<code>Site SFC    Date Time           Operation          Times_processed  Diagnosis_group_nr
P500 B218YW 2017-03-21 10:16:23 O_SF_WRAP          1                1
P500 B218YW 2017-03-23 06:07:53 O_SF_WRAP_CURE     1                1
P500 B218YW 2017-03-23 14:23:41 O_DIAGNOSIS        1                2
P500 B218YW 2017-03-28 10:07:55 O_SF_WRAP          2                2
P500 B218YW 2017-03-28 15:02:21 O_SF_WRAP_CURE     2                2
P500 B218YW 2017-03-29 20:38:06 O_DIAGNOSIS        2                3
P500 B218YW 2017-03-29 20:39:15 O_DIAGNOSIS        3                4
P500 B218YW 2017-04-27 08:43:53 O_SF_WRAP          3                4
P500 B218YW 2017-04-27 12:43:25 O_SF_WRAP_CURE     3                4
P500 B218YW 2017-04-27 13:05:16 O_SF_PCA_ASSEMBLY  1                4
P500 B218YW 2017-04-27 13:19:15 O_DIAGNOSIS        4                5
P500 B218YW 2017-04-27 15:23:09 O_SF_PCA_ASSEMBLY  2                5
P500 B218YW 2017-04-27 16:10:32 O_SF_ELEC_INT_TEST 1                1
P500 B218YW 2017-04-27 22:16:23 O_RECORD_REVIEW    1                1
</code>```

The Times processed column counts how often the SFC went through the operation. That is why you see the 1 for example for O_SF_WRAP and this will change to a 2 when the SFC is sent back from O_Diagnosis the next time.

Is it possible to make a function or maybe SQL view to achieve this? I am using SQL server 2012.

What I have so far is this, for the same SFC:

```<code>Site SFC    Date Time           Operation          Times_processed  Diagnosis_group_nr
P500 B218YW 2017-03-21 10:16:23 O_SF_WRAP          1                1
P500 B218YW 2017-03-23 06:07:53 O_SF_WRAP_CURE     1                1
P500 B218YW 2017-03-23 14:23:41 O_DIAGNOSIS        1                2
P500 B218YW 2017-03-28 10:07:55 O_SF_WRAP          2                2
P500 B218YW 2017-03-28 15:02:21 O_SF_WRAP_CURE     2                2
P500 B218YW 2017-03-29 20:38:06 O_DIAGNOSIS        2                3
P500 B218YW 2017-03-29 20:39:15 O_DIAGNOSIS        3                3
P500 B218YW 2017-04-27 08:43:53 O_SF_WRAP          3                3
P500 B218YW 2017-04-27 12:43:25 O_SF_WRAP_CURE     3                3
P500 B218YW 2017-04-27 13:05:16 O_SF_PCA_ASSEMBLY  1                4
P500 B218YW 2017-04-27 13:19:15 O_DIAGNOSIS        4                4
P500 B218YW 2017-04-27 15:23:09 O_SF_PCA_ASSEMBLY  2                2
P500 B218YW 2017-04-27 16:10:32 O_SF_ELEC_INT_TEST 1                1
P500 B218YW 2017-04-27 22:16:23 O_RECORD_REVIEW    1                1
</code>```

This is my code so far:

```<code>WITH
  cteNextRow
  AS
  (
    SELECT
        opl.[PL SITE]
      , opl.[PL SFC]
      , opl.[Pl End Time Local]
      , opl.[PL OPERATION]
      , LEAD(opl.[PL OPERATION], 1) OVER (PARTITION BY opl.[PL SFC] ORDER BY  opl.[Pl End Time Local])  AS NEXT_OPERATION
      , LEAD(opl.[Pl Times Processed], 1) OVER (PARTITION BY opl.[PL SFC] ORDER BY  opl.[Pl End Time Local])  AS NEXT_TIMES_PROCESSED
      , max(opl.[Pl Times Processed]) OVER (PARTITION BY opl.[PL SFC] ORDER BY opl.[PL SFC], opl.[Pl End Time Local]
        ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) TOTAL_TIMES_PROCESSED
        ,LAST_VALUE(opl.[PL OPERATION]) OVER (PARTITION BY opl.[PL SFC] ORDER BY opl.[PL SFC], opl.[Pl End Time Local]
        ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
        ) as LAST_OPERATION
        ,case when LAST_VALUE(opl.[PL OPERATION]) OVER (PARTITION BY opl.[PL SFC] ORDER BY opl.[PL SFC], opl.[Pl End Time Local]
        ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) not like '%review%'
        then 0
        when LAST_VALUE(opl.[PL OPERATION]) OVER (PARTITION BY opl.[PL SFC] ORDER BY opl.[PL SFC], opl.[Pl End Time Local]
        ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) like '%review%' and max(opl.[Pl Times Processed]) OVER (PARTITION BY opl.[PL SFC] ORDER BY opl.[PL SFC], opl.[Pl End Time Local]
        ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) = 1
        then 1
        else 9999
        end as REVIEW_IND
    FROM Report1 opl
    where [pl sfc] = 'B218YW'
)
select
    opl.[pl Site]  AS PROCESS_SITE
      , opl.[PL SFC] AS  PROCESS_SFC
      , opl.[Pl End Time Local] PROCESS_DATE_TIME
      , opl.[PL OPERATION] AS PROCESS_OPERATION
      , cte.NEXT_OPERATION AS PROCESS_NEXT_OPERATION
      , opl.[Pl Times Processed] AS PROCESS_TIMES_PROCESSED
          , CASE
            when cte.REVIEW_IND = 9999 and cte.NEXT_TIMES_PROCESSED = opl.[Pl Times Processed] and cte.NEXT_OPERATION like '%DIAG%'
              then LEAD(opl.[Pl Times Processed], 1) OVER (PARTITION BY opl.[PL SFC] ORDER BY  opl.[Pl End Time Local])
            when cte.REVIEW_IND = 9999 and cte.NEXT_TIMES_PROCESSED < opl.[Pl Times Processed]
                then opl.[Pl Times Processed]
            when cte.REVIEW_IND = 9999 and NEXT_TIMES_PROCESSED is null
                then opl.[Pl Times Processed]
            when cte.REVIEW_IND = 9999 and cte.NEXT_TIMES_PROCESSED is not null
                then cte.NEXT_TIMES_PROCESSED
            else REVIEW_IND
        END  AS Diagnosis_group_nr
FROM Report1 opl
join cteNextRow cte on cte.[PL SITE] = opl.[pl Site] and cte.[PL sfc] = opl.[PL SFC] and cte.[pl operation] = opl.[pl OPERATION] and  opl.[Pl End Time Local] = cte.[Pl End Time Local]
</code>```

Title: SQL generate group number

Body:
I try to generate a group number based on the O_Diagnosis operation. I would like to group the operations between the current and the next O_Diagnosis operation.

The problem is that this data doesn't have any grouping capable columns. So I need to generate this column almost from scratch. What I would like to achieve is the following:

Site SFC    Date Time           Operation          Times_processed  Diagnosis_group_nr
P500 B218YW 2017-03-21 10:16:23 O_SF_WRAP          1                1
P500 B218YW 2017-03-23 06:07:53 O_SF_WRAP_CURE     1                1
P500 B218YW 2017-03-23 14:23:41 O_DIAGNOSIS        1                2
P500 B218YW 2017-03-28 10:07:55 O_SF_WRAP          2                2
P500 B218YW 2017-03-28 15:02:21 O_SF_WRAP_CURE     2                2
P500 B218YW 2017-03-29 20:38:06 O_DIAGNOSIS        2                3
P500 B218YW 2017-03-29 20:39:15 O_DIAGNOSIS        3                4
P500 B218YW 2017-04-27 08:43:53 O_SF_WRAP          3                4
P500 B218YW 2017-04-27 12:43:25 O_SF_WRAP_CURE     3                4
P500 B218YW 2017-04-27 13:05:16 O_SF_PCA_ASSEMBLY  1                4
P500 B218YW 2017-04-27 13:19:15 O_DIAGNOSIS        4                5
P500 B218YW 2017-04-27 15:23:09 O_SF_PCA_ASSEMBLY  2                5
P500 B218YW 2017-04-27 16:10:32 O_SF_ELEC_INT_TEST 1                1
P500 B218YW 2017-04-27 22:16:23 O_RECORD_REVIEW    1                1

The Times processed column counts how often the SFC went through the operation. That is why you see the 1 for example for O_SF_WRAP and this will change to a 2 when the SFC is sent back from O_Diagnosis the next time.

Is it possible to make a function or maybe SQL view to achieve this? I am using SQL server 2012.

What I have so far is this, for the same SFC:

Site SFC    Date Time           Operation          Times_processed  Diagnosis_group_nr
P500 B218YW 2017-03-21 10:16:23 O_SF_WRAP          1                1
P500 B218YW 2017-03-23 06:07:53 O_SF_WRAP_CURE     1                1
P500 B218YW 2017-03-23 14:23:41 O_DIAGNOSIS        1                2
P500 B218YW 2017-03-28 10:07:55 O_SF_WRAP          2                2
P500 B218YW 2017-03-28 15:02:21 O_SF_WRAP_CURE     2                2
P500 B218YW 2017-03-29 20:38:06 O_DIAGNOSIS        2                3
P500 B218YW 2017-03-29 20:39:15 O_DIAGNOSIS        3                3
P500 B218YW 2017-04-27 08:43:53 O_SF_WRAP          3                3
P500 B218YW 2017-04-27 12:43:25 O_SF_WRAP_CURE     3                3
P500 B218YW 2017-04-27 13:05:16 O_SF_PCA_ASSEMBLY  1                4
P500 B218YW 2017-04-27 13:19:15 O_DIAGNOSIS        4                4
P500 B218YW 2017-04-27 15:23:09 O_SF_PCA_ASSEMBLY  2                2
P500 B218YW 2017-04-27 16:10:32 O_SF_ELEC_INT_TEST 1                1
P500 B218YW 2017-04-27 22:16:23 O_RECORD_REVIEW    1                1

This is my code so far:

WITH
  cteNextRow
  AS
  (
    SELECT
        opl.[PL SITE]
      , opl.[PL SFC]
      , opl.[Pl End Time Local]
      , opl.[PL OPERATION]
      , LEAD(opl.[PL OPERATION], 1) OVER (PARTITION BY opl.[PL SFC] ORDER BY  opl.[Pl End Time Local])  AS NEXT_OPERATION
      , LEAD(opl.[Pl Times Processed], 1) OVER (PARTITION BY opl.[PL SFC] ORDER BY  opl.[Pl End Time Local])  AS NEXT_TIMES_PROCESSED
      , max(opl.[Pl Times Processed]) OVER (PARTITION BY opl.[PL SFC] ORDER BY opl.[PL SFC], opl.[Pl End Time Local]
        ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) TOTAL_TIMES_PROCESSED
        ,LAST_VALUE(opl.[PL OPERATION]) OVER (PARTITION BY opl.[PL SFC] ORDER BY opl.[PL SFC], opl.[Pl End Time Local]
        ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
        ) as LAST_OPERATION
        ,case when LAST_VALUE(opl.[PL OPERATION]) OVER (PARTITION BY opl.[PL SFC] ORDER BY opl.[PL SFC], opl.[Pl End Time Local]
        ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) not like '%review%'
        then 0
        when LAST_VALUE(opl.[PL OPERATION]) OVER (PARTITION BY opl.[PL SFC] ORDER BY opl.[PL SFC], opl.[Pl End Time Local]
        ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) like '%review%' and max(opl.[Pl Times Processed]) OVER (PARTITION BY opl.[PL SFC] ORDER BY opl.[PL SFC], opl.[Pl End Time Local]
        ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) = 1
        then 1
        else 9999
        end as REVIEW_IND
    FROM Report1 opl
    where [pl sfc] = 'B218YW'
)
select
    opl.[pl Site]  AS PROCESS_SITE
      , opl.[PL SFC] AS  PROCESS_SFC
      , opl.[Pl End Time Local] PROCESS_DATE_TIME
      , opl.[PL OPERATION] AS PROCESS_OPERATION
      , cte.NEXT_OPERATION AS PROCESS_NEXT_OPERATION
      , opl.[Pl Times Processed] AS PROCESS_TIMES_PROCESSED
          , CASE
            when cte.REVIEW_IND = 9999 and cte.NEXT_TIMES_PROCESSED = opl.[Pl Times Processed] and cte.NEXT_OPERATION like '%DIAG%'
              then LEAD(opl.[Pl Times Processed], 1) OVER (PARTITION BY opl.[PL SFC] ORDER BY  opl.[Pl End Time Local])
            when cte.REVIEW_IND = 9999 and cte.NEXT_TIMES_PROCESSED < opl.[Pl Times Processed]
                then opl.[Pl Times Processed]
            when cte.REVIEW_IND = 9999 and NEXT_TIMES_PROCESSED is null
                then opl.[Pl Times Processed]
            when cte.REVIEW_IND = 9999 and cte.NEXT_TIMES_PROCESSED is not null
                then cte.NEXT_TIMES_PROCESSED
            else REVIEW_IND
        END  AS Diagnosis_group_nr
FROM Report1 opl
join cteNextRow cte on cte.[PL SITE] = opl.[pl Site] and cte.[PL sfc] = opl.[PL SFC] and cte.[pl operation] = opl.[pl OPERATION] and  opl.[Pl End Time Local] = cte.[Pl End Time Local]

Body:
I am not sure why your grouping number resets to 1 at the end of your desired output, but if that is a typo you can use a simple windowed conditional row_number and sum to get the number of Times_processed and the `Diagnosis_group_nr' you require respectively:

declare @t table(Site nvarchar(50),SFC nvarchar(50),DateValue datetime,Operation nvarchar(50));
insert into @t values
 ('P500','B218YW','2017-03-21 10:16:23','O_SF_WRAP')
,('P500','B218YW','2017-03-23 06:07:53','O_SF_WRAP_CURE')
,('P500','B218YW','2017-03-23 14:23:41','O_DIAGNOSIS')
,('P500','B218YW','2017-03-28 10:07:55','O_SF_WRAP')
,('P500','B218YW','2017-03-28 15:02:21','O_SF_WRAP_CURE')
,('P500','B218YW','2017-03-29 20:38:06','O_DIAGNOSIS')
,('P500','B218YW','2017-03-29 20:39:15','O_DIAGNOSIS')
,('P500','B218YW','2017-04-27 08:43:53','O_SF_WRAP')
,('P500','B218YW','2017-04-27 12:43:25','O_SF_WRAP_CURE')
,('P500','B218YW','2017-04-27 13:05:16','O_SF_PCA_ASSEMBLY')
,('P500','B218YW','2017-04-27 13:19:15','O_DIAGNOSIS')
,('P500','B218YW','2017-04-27 15:23:09','O_SF_PCA_ASSEMBLY')
,('P500','B218YW','2017-04-27 16:10:32','O_SF_ELEC_INT_TEST')
,('P500','B218YW','2017-04-27 22:16:23','O_RECORD_REVIEW');

select *
    ,row_number() over (partition by Operation order by DateValue) as Times_processed
    ,sum(case when Operation = 'O_DIAGNOSIS' then 1 else 0 end) over (order by DateValue)+1 as Diagnosis_group_nr
from @t
order by DateValue;

Output:

+------+--------+-------------------------+--------------------+-----------------+--------------------+
| Site |  SFC   |        DateValue        |     Operation      | Times_processed | Diagnosis_group_nr |
+------+--------+-------------------------+--------------------+-----------------+--------------------+
| P500 | B218YW | 2017-03-21 10:16:23.000 | O_SF_WRAP          |               1 |                  1 |
| P500 | B218YW | 2017-03-23 06:07:53.000 | O_SF_WRAP_CURE     |               1 |                  1 |
| P500 | B218YW | 2017-03-23 14:23:41.000 | O_DIAGNOSIS        |               1 |                  2 |
| P500 | B218YW | 2017-03-28 10:07:55.000 | O_SF_WRAP          |               2 |                  2 |
| P500 | B218YW | 2017-03-28 15:02:21.000 | O_SF_WRAP_CURE     |               2 |                  2 |
| P500 | B218YW | 2017-03-29 20:38:06.000 | O_DIAGNOSIS        |               2 |                  3 |
| P500 | B218YW | 2017-03-29 20:39:15.000 | O_DIAGNOSIS        |               3 |                  4 |
| P500 | B218YW | 2017-04-27 08:43:53.000 | O_SF_WRAP          |               3 |                  4 |
| P500 | B218YW | 2017-04-27 12:43:25.000 | O_SF_WRAP_CURE     |               3 |                  4 |
| P500 | B218YW | 2017-04-27 13:05:16.000 | O_SF_PCA_ASSEMBLY  |               1 |                  4 |
| P500 | B218YW | 2017-04-27 13:19:15.000 | O_DIAGNOSIS        |               4 |                  5 |
| P500 | B218YW | 2017-04-27 15:23:09.000 | O_SF_PCA_ASSEMBLY  |               2 |                  5 |
| P500 | B218YW | 2017-04-27 16:10:32.000 | O_SF_ELEC_INT_TEST |               1 |                  5 |
| P500 | B218YW | 2017-04-27 22:16:23.000 | O_RECORD_REVIEW    |               1 |                  5 |
+------+--------+-------------------------+--------------------+-----------------+--------------------+

If you want to run the above script across more than one Site and SFC, simply add in those columns to the partition by on both window functions and they will correctly calculate across your entire dataset in one go.


来源: stackexchange

问:
help with inport csv file to my C# program
i try to inport csv file to my database in my C# winform program.

for example the csv file:

```<code>code  ,name    ,price
101010,computer,200$
</code>```

and i done this:

```<code>char[] BI = { ',' };
string[] WI = TEMP.Split(BI);
A = WI[0].Trim().ToString();
B = WI[1].Trim().ToString();
C = WI[2].Trim().ToString();
</code>```

but what i can do if the name contain (,) ?

for example

```<code>code  ,name              ,price
101010,computer 12,200.00,200$
</code>```

if i get this type of csv:

```<code>code    ,name                ,price
"101010","computer 12,200.00","200$"
</code>```

how to deal with this ?

答:
The best thing to do is not roll your own csv and use a existing free library. I recommend FileHelpers.

EDIT:

Here is a fun little read, I bet you are on step 2 or step 3.

ContentLicense: CC BY-SA 2.5

Body:
i try to inport csv file to my database in my C# winform program.

for example the csv file:

code  ,name    ,price
101010,computer,200$

and i done this:

char[] BI = { ',' };
string[] WI = TEMP.Split(BI);
A = WI[0].Trim().ToString();
B = WI[1].Trim().ToString();
C = WI[2].Trim().ToString();

but what i can do if the name contain (,) ?

for example

code  ,name              ,price
101010,computer 12,200.00,200$

if i get this type of csv:

code    ,name                ,price
"101010","computer 12,200.00","200$"

how to deal with this ?


问:
Create DLL file in VB.NET and use in Excel VBA
I have created a DLL file in VB.NET and I want use it in Excel VBA. When I use it like a function it is working perfect but when I use sub with a ByRef variable it does not work and Excel restarts with an error.

The code in VB.NET is:

```<code>Public Function distinctArr(ByVal arr As String()) As String()
        Return arr.ToList.Distinct.ToArray
End Function

Public Sub sortArr(ByVal arr As String(), ByRef a As String())
    Dim tolist As List(Of String) = arr.ToList
    tolist.Sort()
    a = tolist.ToArray
End Sub
</code>```

This is the code in VBA:

```<code>Dim objMda As Excelcode.mda
Set objMda = New Excelcode.mda
Dim distinc_Item() As String
Dim all_Items() As String
all_Items = rng_to_string(rng_rizmetre)
distinc_Item = objMda.distinctArr(all_Items) '''This line is working perfect
Dim Sorted_Item() As String
objMda.sortArr distinc_Item, Sorted_Item
</code>```

What is wrong with the code?

答:
Finally i can find my answer.
code in vb.net

```<code>Public Class MainClass
    Sub sortArr(ByVal arr As String(), ByRef sortedarr As String())
        sortedarr = arr
        Array.Sort(sortedarr)

    End Sub
End Class
</code>```

and code in excel vba:

```<code>Sub aaa()
Dim Mycode As excelcode.MainClass
Set Mycode = New excelcode.MainClass
Dim arr(2) As String
arr(0) = "m"
arr(1) = "a"
arr(2) = "d"
Dim sortedArr() As String
ReDim sortedArr(0)
  Mycode.sortArr arr, sortedArr
End Sub
</code>```

by this code i can pass array byval to vb.net dll then vb.net pass sorted array.

ContentLicense: CC BY-SA 3.0

Body:
I have created a DLL file in VB.NET and I want use it in Excel VBA. When I use it like a function it is working perfect but when I use sub with a ByRef variable it does not work and Excel restarts with an error.

The code in VB.NET is:

Public Function distinctArr(ByVal arr As String()) As String()
        Return arr.ToList.Distinct.ToArray
End Function

Public Sub sortArr(ByVal arr As String(), ByRef a As String())
    Dim tolist As List(Of String) = arr.ToList
    tolist.Sort()
    a = tolist.ToArray
End Sub

This is the code in VBA:

Dim objMda As Excelcode.mda
Set objMda = New Excelcode.mda
Dim distinc_Item() As String
Dim all_Items() As String
all_Items = rng_to_string(rng_rizmetre)
distinc_Item = objMda.distinctArr(all_Items) '''This line is working perfect
Dim Sorted_Item() As String
objMda.sortArr distinc_Item, Sorted_Item

What is wrong with the code?

Body:
Finally i can find my answer.
code in vb.net

Public Class MainClass
    Sub sortArr(ByVal arr As String(), ByRef sortedarr As String())
        sortedarr = arr
        Array.Sort(sortedarr)

    End Sub
End Class

and code in excel vba:

Sub aaa()
Dim Mycode As excelcode.MainClass
Set Mycode = New excelcode.MainClass
Dim arr(2) As String
arr(0) = "m"
arr(1) = "a"
arr(2) = "d"
Dim sortedArr() As String
ReDim sortedArr(0)
  Mycode.sortArr arr, sortedArr
End Sub

by this code i can pass array byval to vb.net dll then vb.net pass sorted array.


问:
How McCarthy 91 function works
I have following function based on McCarthy 91 principle:

```<code>mc91 :: Integer -> Integer
mc91 n
    | n > 100 = n - 10
    | otherwise = mc91 (mc91 (n + 11))
</code>```

when I type in the prelude mc91 85 I've got 91.

I could not configure it out, how it is expanded and why do I've got 91.

答:
Lets expand your code:

```<code>mc91 85
mc91 (mc91 96)
mc91 (mc91 (mc91 107))
mc91 (mc91 97)
mc91 (mc91 (mc91 108))
mc91 (mc91 98)
mc91 (mc91 (mc91 109))
mc91 (mc91 99)
mc91 (mc91 (mc91 110))
mc91 (mc91 100)
mc91 (mc91 (mc91 111))
mc91 (mc91 101)
mc91 91... --It is a pattern here
...
mc91 101
91
</code>```

If you see the recrusive calls, you will realize that it will reduce it once it achieves 100 or higher, ending in a (mc91 101) call that will bring us the last 91 result.

Title: How McCarthy 91 function works

Body:
I have following function based on McCarthy 91 principle:

mc91 :: Integer -> Integer
mc91 n
    | n > 100 = n - 10
    | otherwise = mc91 (mc91 (n + 11))

when I type in the prelude mc91 85 I've got 91.

I could not configure it out, how it is expanded and why do I've got 91.

Body:
Lets expand your code:

mc91 85
mc91 (mc91 96)
mc91 (mc91 (mc91 107))
mc91 (mc91 97)
mc91 (mc91 (mc91 108))
mc91 (mc91 98)
mc91 (mc91 (mc91 109))
mc91 (mc91 99)
mc91 (mc91 (mc91 110))
mc91 (mc91 100)
mc91 (mc91 (mc91 111))
mc91 (mc91 101)
mc91 91... --It is a pattern here
...
mc91 101
91

If you see the recrusive calls, you will realize that it will reduce it once it achieves 100 or higher, ending in a (mc91 101) call that will bring us the last 91 result.


问:
Django: Right way of using URL patterns: maximum recursion depth exceeded
Im new to Django and im trying to display Hello world from my app.

Im stuck in giving the right URL pattern in urls.py

** UPDATED: Working **

My folder structure is as:

var\www\html\Python_PS\DjangoDemo\boardgames\urls.py

```<code>from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^boardgames/', include('boardgames.urls'))
]
</code>```

var\www\html\Python_PS\DjangoDemo\boardgames\boardgames\views.py

```<code>from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.

def home(request):
    return HttpResponse("Hello!")
</code>```

\var\www\html\Python_PS\DjangoDemo\boardgames\boardgames\urls.py

```<code>from django.conf.urls import url, include
from django.contrib import admin
from . import views

urlpatterns = [
    url(r'^$', views.home),
]
</code>```

After importing the include library in urls.py :

I got maximum depth exceeded error.

Or otherwise unable to display the Hello!.

I need to know the proper way of using the the url patters.

My Django version is 1.11 with Python 3.5.2

答:
You are not correctly importing it, your function name is "home" and you are trying to import views, which is not a best practice, The correct way to import is,

```<code>from boardgames.views import *
</code>```

OR

```<code>from boardgames.views import home
</code>```

Body:
Im new to Django and im trying to display Hello world from my app.

Im stuck in giving the right URL pattern in urls.py

** UPDATED: Working **

My folder structure is as:

var\www\html\Python_PS\DjangoDemo\boardgames\urls.py

from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^boardgames/', include('boardgames.urls'))
]

var\www\html\Python_PS\DjangoDemo\boardgames\boardgames\views.py

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.

def home(request):
    return HttpResponse("Hello!")

\var\www\html\Python_PS\DjangoDemo\boardgames\boardgames\urls.py

from django.conf.urls import url, include
from django.contrib import admin
from . import views

urlpatterns = [
    url(r'^$', views.home),
]

After importing the include library in urls.py :

I got maximum depth exceeded error.

Or otherwise unable to display the Hello!.

I need to know the proper way of using the the url patters.

My Django version is 1.11 with Python 3.5.2

Body:
You are not correctly importing it, your function name is "home" and you are trying to import views, which is not a best practice, The correct way to import is,

from boardgames.views import *

OR

from boardgames.views import home


问:
jQuery :contains selector isn't working as expected
I'm trying to select calendar event titles that have a specific word and use this to change the background colour of the event.

Please see my code below. This changes all events to have the background colour of red even if event title doesn't contain the word 'Test'. I've even changed 'Test' to 'uhrguqhergoieqhrgeurgherogih' but it still changes everything.

Unfortunately I can't see anything similar on SO so hopefully one of you could help me out please! :)

Thanks in advance!

```<code>$(window).on('load', function() {
    if($(".fc-event-title:contains('Test')"))
    {
      $('.fc-event').css('background-color', 'red');
    }
});
</code>```

答:
No need of if condition.Do it directly like below:-

```<code>$(window).on('load', function() {
  $(".fc-event-title:contains('Test')").css('background-color', 'red');
});
</code>```

If above not worked then try with closest() like below:-

```<code>$(window).on('load', function() {
  $(".fc-event-title:contains('Test')").closest('.fc-event').css('background-color', 'red');
});
</code>```

Body:
I'm trying to select calendar event titles that have a specific word and use this to change the background colour of the event.

Please see my code below. This changes all events to have the background colour of red even if event title doesn't contain the word 'Test'. I've even changed 'Test' to 'uhrguqhergoieqhrgeurgherogih' but it still changes everything.

Unfortunately I can't see anything similar on SO so hopefully one of you could help me out please! :)

Thanks in advance!

$(window).on('load', function() {
    if($(".fc-event-title:contains('Test')"))
    {
      $('.fc-event').css('background-color', 'red');
    }
});

Body:
No need of if condition.Do it directly like below:-

$(window).on('load', function() {
  $(".fc-event-title:contains('Test')").css('background-color', 'red');
});

If above not worked then try with closest() like below:-

$(window).on('load', function() {
  $(".fc-event-title:contains('Test')").closest('.fc-event').css('background-color', 'red');
});


问:
Flex 4 - Select & Deselect same item in <s:List> with a mousedown
In Flex 4, I have a Spark List component with item renderers.
I would like to select an item in the List by clicking on it, and deselect it also, by clicking on the same selected item. Like an on/off switch.

My item renderer has the following states:

```<code><s:states>
<s:State name="normal"/>
<s:State name="hovered"/>
<s:State name="selected"/>
</s:states>
</code>```

so I tried to add a click event listener to the item renderer with:

```<code>private function selectUnSelect():void {
if (currentState == 'selected') currentState = 'normal';
else currentState = 'selected';
</code>```

}

with an awkward behaviour... where the item stay selected even after clicking it again in the selected state.

Think of using the List component without the Command (on mac) or the Control button on windows.

答: Rather than have the item renderer set its state, I would operate on the List itself.  Have your item renderer dispatch an event when it is clicked that includes the data of the item renderer, then add a listener for that event (either in a component that extends List, or in the component that contains your list).  You can then check if the data matches any of your List's selectedItems.  If not, append the item to the selectedItems.  If so, remove it from the selectedItems. Hope that helps.</p>

Body:
In Flex 4, I have a Spark List component with item renderers.
I would like to select an item in the List by clicking on it, and deselect it also, by clicking on the same selected item. Like an on/off switch.

My item renderer has the following states:

<s:states>
<s:State name="normal"/>
<s:State name="hovered"/>
<s:State name="selected"/>
</s:states>

so I tried to add a click event listener to the item renderer with:

private function selectUnSelect():void {
if (currentState == 'selected') currentState = 'normal';
else currentState = 'selected';

}

with an awkward behaviour... where the item stay selected even after clicking it again in the selected state.

Think of using the List component without the Command (on mac) or the Control button on windows.


问:
display:flex with text and tag inside removes spaces
I am developing an advertisement management solution of certain CMS. I provide admin with few locations in the style to position ads in. Admin will input ad code (in HTML: adsense script, banner, or simple text). To make things as easy for admin as possible, I try to center the content automatically by wrapping ad code with this:

```<code><div style="display: flex; justify-content: center;">
</div>
</code>```

It works perfectly in all cases except for this one:

```<code><div style="display: flex; justify-content: center;">
    Hosting provided by <a href="http://foobar">FooBar Hosting</a> and me
</div>
</code>```

Produces this:

Note missing spaces between "by FooBar" and "Hosting and". Why is that? Is there any way to fix this with CSS only but retain centering feature for other cases?

答:
Does it need to be flex for any reason?

  Hosting provided by FooBar Hosting and me

```

Body:
I am developing an advertisement management solution of certain CMS. I provide admin with few locations in the style to position ads in. Admin will input ad code (in HTML: adsense script, banner, or simple text). To make things as easy for admin as possible, I try to center the content automatically by wrapping ad code with this:

It works perfectly in all cases except for this one:

    Hosting provided by FooBar Hosting and me

Produces this:

Note missing spaces between "by FooBar" and "Hosting and". Why is that? Is there any way to fix this with CSS only but retain centering feature for other cases?

Body:
Does it need to be flex for any reason?

<div style="text-align: center;">
  Hosting provided by <a href="http://foobar">FooBar Hosting</a> and me
</div>


问:
Python: Checking if a key is part of a dictionary
I'm trying to make my own irc bot (for twitch) in Python. I have a dictionary with my commands:

```<code>commands = {

    '!ping': {
        'cooldown': 30,
        'return': '!pong'
    },

    '!random': {
        'cooldown': 30,
        'return': 'command',
        'argc': 2,
        'arg_username': True,
        'usage': '!random <min> <max>'
    }

} # End of commands
</code>```

Then I have a function to check if the message that was send is indeed a command:

```<code>import string

def is_valid_command(command):
    return True if command in commands.keys() else False
</code>```

So when i test this function out, it don't seems to work, and I don't know what I am doiing wrong:

```<code>message = "!ping"
print(str(is_valid_command(message)))
>>> False
</code>```

I tried to change '!ping' inside the dictionary to "!ping", and virsa versa with the message, even deleted the '!' and it always says it's False.

Thanks in regards,
Laurens

EDIT:

```<code>def is_valid_command(command):
    for key in commands.keys():
        print(key)
    print("input " + str(command))
    print(command in commands.keys())
    return command in commands.keys()
</code>```

This result in this:

```<code>!ping
!random
input !ping
False
</code>```

EDIT2: @e4c5 wanted me to use try/except, as i quickly try it (inside that methode), it still return False

```<code>try:
    cmd = commands[command]
    print ('Try True')
    return True
except KeyError:
    print('Try False')
    return False
</code>```

EDIT3: u'!ping' before fixed this (message = u'!ping'), but when I read a string from somewhere else, is there a function that does this unicoding?

答:
This pre checking is not needed and unpythonic. Instead of all these ccomplications, just do

```<code>try:
   cmd = commands[message]
   # do whatever with cmd
except KeyError:
   print ('Sorry not a valid command')
</code>```

EAFP

Easier to ask for forgiveness than permission. This common Python
  coding style assumes the existence of valid keys or attributes and
  catches exceptions if the assumption proves false. This clean and fast
  style is characterized by the presence of many try and except
  statements. The technique contrasts with the LBYL style common to many
  other languages such as C.

Body:
I'm trying to make my own irc bot (for twitch) in Python. I have a dictionary with my commands:

commands = {

    '!ping': {
        'cooldown': 30,
        'return': '!pong'
    },

    '!random': {
        'cooldown': 30,
        'return': 'command',
        'argc': 2,
        'arg_username': True,
        'usage': '!random <min> <max>'
    }

} # End of commands

Then I have a function to check if the message that was send is indeed a command:

import string

def is_valid_command(command):
    return True if command in commands.keys() else False

So when i test this function out, it don't seems to work, and I don't know what I am doiing wrong:

message = "!ping"
print(str(is_valid_command(message)))
>>> False

I tried to change '!ping' inside the dictionary to "!ping", and virsa versa with the message, even deleted the '!' and it always says it's False.

Thanks in regards,
Laurens

EDIT:

def is_valid_command(command):
    for key in commands.keys():
        print(key)
    print("input " + str(command))
    print(command in commands.keys())
    return command in commands.keys()

This result in this:

!ping
!random
input !ping
False

EDIT2: @e4c5 wanted me to use try/except, as i quickly try it (inside that methode), it still return False

try:
    cmd = commands[command]
    print ('Try True')
    return True
except KeyError:
    print('Try False')
    return False

EDIT3: u'!ping' before fixed this (message = u'!ping'), but when I read a string from somewhere else, is there a function that does this unicoding?

Body:
This pre checking is not needed and unpythonic. Instead of all these ccomplications, just do

try:
   cmd = commands[message]
   # do whatever with cmd
except KeyError:
   print ('Sorry not a valid command')

EAFP

Easier to ask for forgiveness than permission. This common Python
  coding style assumes the existence of valid keys or attributes and
  catches exceptions if the assumption proves false. This clean and fast
  style is characterized by the presence of many try and except
  statements. The technique contrasts with the LBYL style common to many
  other languages such as C.


问:
Logout from twitter api android
I am trying to integrate my app to twitter and I do it

but my question is: How I can logout from twitter? can I remove RequestToken or OAuth of my app?

I tried to use:

twitter.setOAuthAccessToken(null);

but does not work

callbackUrl = "api.twitter.com/oauth/authorize?force_login=true";

also does not work

please help me

thanks in advance

答:
@Rob answer is working, but this methods was removed in Twitter SDK v3.0.0

According to upgrading guide:

[Removed] TwitterCore#logOut() was removed use
  TwitterCore.getInstance().getSessionManager().clearActiveSession()
  instead.

Title: Logout from twitter api android


问:
Query performance issues when using MATCH and SELECT together OrientDB
I'm facing a problem with a query in OrientDB.

```<code>SELECT FROM (
   MATCH
      {class: article, as: article}.in('authorOf'){as: author}
   RETURN article, author
) ORDER BY createdAt desc SKIP 0 LIMIT 50
</code>```

As you see I want to fetch the last 50 most recent articles with their corresponding author. The problem I'm facing is that the subquery first iterates over all my articles then passes it down to the parent and then it gets filtered. This is obviously not very effective, because all the articles are loaded into memory when I only need 50 of them.

Does anyone know a better approach without having to use multiple queries.

答:
you could try with

```<code>select @rid as article,in('authorOf')[0] as author from article order by createdAt desc SKIP 0 LIMIT 50
</code>```

With this one I'm getting a sligthly better performances, but nothing extreme.

EDIT following Luigi's comment

Create an index on createdAt property:

```<code>CREATE INDEX article.createdAt ON article (createdAt) NOTUNIQUE
</code>```

PS

I'm not sure that the order by in your query is working well

Body:
I'm facing a problem with a query in OrientDB.

SELECT FROM (
   MATCH
      {class: article, as: article}.in('authorOf'){as: author}
   RETURN article, author
) ORDER BY createdAt desc SKIP 0 LIMIT 50

As you see I want to fetch the last 50 most recent articles with their corresponding author. The problem I'm facing is that the subquery first iterates over all my articles then passes it down to the parent and then it gets filtered. This is obviously not very effective, because all the articles are loaded into memory when I only need 50 of them.

Does anyone know a better approach without having to use multiple queries.

Body:
you could try with

select @rid as article,in('authorOf')[0] as author from article order by createdAt desc SKIP 0 LIMIT 50

With this one I'm getting a sligthly better performances, but nothing extreme.

EDIT following Luigi's comment

Create an index on createdAt property:

CREATE INDEX article.createdAt ON article (createdAt) NOTUNIQUE

PS

I'm not sure that the order by in your query is working well


问:
Custom Tabbed Page Renderer Xamarin Android
So know how to set up a custom renderer (only partially apparently) with an OnElementChanged method. I followed this (http://forums.xamarin.com/discussion/17654/tabbedpage-icons-not-visible-android)

```<code>protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
    {
        base.OnElementChanged(e);
        _activity = this.Context as Activity;
    }
</code>```

This gets hit, but it never displays the page afterwards.

Anyone have any ideas?

答:
Here you can find a full TabbedPageRenderer ready to be modified. It comes directly from Xamarin.Forms Android.

Still I'm trying to set a different Font Size...

Body:
So know how to set up a custom renderer (only partially apparently) with an OnElementChanged method. I followed this (http://forums.xamarin.com/discussion/17654/tabbedpage-icons-not-visible-android)

protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
    {
        base.OnElementChanged(e);
        _activity = this.Context as Activity;
    }

This gets hit, but it never displays the page afterwards.

Anyone have any ideas?


问:
Parse push notification with ionic
I am trying to set up a push notification with parse to handle received notifications.

I used phonegap-parse-plugin plugin and was able to set it up correctly.

My problem with it is that I cannot handle the received notifications. I would like to redirect a user to a the page for the notification based on the notification json params.

So, I decided to switch to parse-push-plugin, but my problem with it is that I cannot even get it to show the alert registered box; it cannot even find the ParsePushPlugin method.

I followed the tutorial which is simple enough and added this to my app.js file

```<code>ParsePushPlugin.register(
    { appId:"xxx", clientKey:"xxx", eventKey:"myEventKey" }, //will trigger receivePN[pnObj.myEventKey]
    function() {
        alert('successfully registered device!');
    },
    function(e) {
        alert('error registering device: ' + e);
});

ParsePushPlugin.on('receivePN', function(pn){
    alert('yo i got this push notification:' + JSON.stringify(pn));
});
</code>```

The alert success just failed to show so I guess it is not working or I am not doing the right thing.

答:
Use phonegap-plugin-push.  It is easy to implement and use.

Config :

```<code>    var push = PushNotification.init({
        "android": {
            "senderID": "Your-sender-ID",
            "forceShow": true, // To show notifications on screen as well
            "iconColor": "#403782",
            "badge": "true",
            "clearBadge": "true" // To clear app badge
        },
        "ios": {
            "alert": "true",
            "badge": "true",
            "clearBadge": "true",
            "sound": "true",
            "forceShow": "true"
        },
        "windows": {}
    });
</code>```

Device Registration :

```<code>    push.on('registration', function(data) {
            localStorage.setItem('pushToken', data.registrationId); // Save registration ID
    });
</code>```

Handle Notifications

```<code>    push.on('notification', function(data) {
        console.log(data);
        // Handle all requests here
        if (data.additionalData.$state == "mystate") {
            $state.go('app.conversations');
        }
    })
</code>```

Title: Parse push notification with ionic

Body:
I am trying to set up a push notification with parse to handle received notifications.

I used phonegap-parse-plugin plugin and was able to set it up correctly.

My problem with it is that I cannot handle the received notifications. I would like to redirect a user to a the page for the notification based on the notification json params.

So, I decided to switch to parse-push-plugin, but my problem with it is that I cannot even get it to show the alert registered box; it cannot even find the ParsePushPlugin method.

I followed the tutorial which is simple enough and added this to my app.js file

ParsePushPlugin.register(
    { appId:"xxx", clientKey:"xxx", eventKey:"myEventKey" }, //will trigger receivePN[pnObj.myEventKey]
    function() {
        alert('successfully registered device!');
    },
    function(e) {
        alert('error registering device: ' + e);
});

ParsePushPlugin.on('receivePN', function(pn){
    alert('yo i got this push notification:' + JSON.stringify(pn));
});

The alert success just failed to show so I guess it is not working or I am not doing the right thing.

Body:
Use phonegap-plugin-push.  It is easy to implement and use.

Config :

    var push = PushNotification.init({
        "android": {
            "senderID": "Your-sender-ID",
            "forceShow": true, // To show notifications on screen as well
            "iconColor": "#403782",
            "badge": "true",
            "clearBadge": "true" // To clear app badge
        },
        "ios": {
            "alert": "true",
            "badge": "true",
            "clearBadge": "true",
            "sound": "true",
            "forceShow": "true"
        },
        "windows": {}
    });

Device Registration :

    push.on('registration', function(data) {
            localStorage.setItem('pushToken', data.registrationId); // Save registration ID
    });

Handle Notifications

    push.on('notification', function(data) {
        console.log(data);
        // Handle all requests here
        if (data.additionalData.$state == "mystate") {
            $state.go('app.conversations');
        }
    })


问:
How do I change CodeRush to append the "this" keyword when converting to auto-implemented properties and extract to method refactorings?
I like to use the "this" keyword when referencing auto-implemented properties and when calling methods inside my class. How do I change the CodeRush templates for "Convert to auto-implemented property" and "Extract Method" to append the "this" keyword to the refactored references?</p>

答: This is not possible at the moment. But, most likely, this ability will appear in the near future.</p>


问:
Writing a new column in csv file based on if condition
I want to add a new column which adds two existing columns on basis of if condition that tweet is a Retweet or not.
I have following csv output from my python code : csv image

Now, i want to implement condition that if tweet is a retweet, ie;

```<code>   file1 = open(string.csv, 'rb')
reader = csv.reader(file1)
for r in rows :
   if Tweet[r]!="RT @***" :
        new_col=[col[3],col[4]]
        newcol.append(new_col)
    else :
        new_col=0
file1.close()

file2 = open(file.csv, 'wb')
writer = csv.writer(file2)
writer.writerows(newcol)
file2.close()
</code>```

I'm having trouble implementing it. Kindly help.

答:
You can use the startswith() method which checks whether a string starts with a substring.

```<code>import csv
with open('tweets.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        if row[0].startswith("RT @"):
            // It's a retweet
        else:
            // It's not a retweet
</code>```

Body:
I want to add a new column which adds two existing columns on basis of if condition that tweet is a Retweet or not.
I have following csv output from my python code : csv image

Now, i want to implement condition that if tweet is a retweet, ie;

   file1 = open(string.csv, 'rb')
reader = csv.reader(file1)
for r in rows :
   if Tweet[r]!="RT @***" :
        new_col=[col[3],col[4]]
        newcol.append(new_col)
    else :
        new_col=0
file1.close()

file2 = open(file.csv, 'wb')
writer = csv.writer(file2)
writer.writerows(newcol)
file2.close()

I'm having trouble implementing it. Kindly help.

Body:
You can use the startswith() method which checks whether a string starts with a substring.

import csv
with open('tweets.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        if row[0].startswith("RT @"):
            // It's a retweet
        else:
            // It's not a retweet


问:
Class sent to Post Action is null
I'm working on a view that presents all the records of class (Machine) where some of their properties could be updated.

For this, the view is working with an IEnumerable. These are the Get and Post methods:

Get:

```<code>public async Task<IActionResult> Test()
    {

        PopulateMachineTypeDropDownListStore();
        return View(await _context.Machines.AsNoTracking().ToListAsync());
    }
</code>```

Post:

```<code>[HttpPost, ActionName("Test")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> TestPost(int id, [Bind("Id,StoreID,PUnit,Status")] Machine machine)
    {
        if (id != machine.Id)
        {
            return NotFound();
        }
        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(machine);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!MachineExists(machine.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction("Index");
        }
        return View(machine);}
</code>```

The problem is that the class sent to the Post Action is null (almost all their fields are zero or null except for the Id)

```<code>public async Task<IActionResult> TestPost(int id, [Bind("Id,StoreID,PUnit,Status")] Machine machine)
</code>```

Question: So, I don't know how to correct this. Could there be something missing in the view?

```<code>@model IEnumerable<Application.Models.Machine>
@{
    ViewData["Title"] = "Test";

}
@foreach (var item in Model)
{
    <form asp-action="Test" asp-route-id="@item.Id" method="post">
        <table class="table">
            <tbody>
            <tr>
                <td>
                    <input type="hidden" asp-for="@item.Id" />
                    <div class="form-group">
                        <div class="col-md-10">
                            <input asp-for="@item.MchName" readonly class="form-control" />
                            <span asp-validation-for="@item.MchName" class="text-danger"></span>
                        </div>
                    </div>
                </td>
                <td>
                    <div class="form-group">
                        <div class="col-md-10">
                            <select asp-for="@item.StoreID" class="form-control" asp-items="ViewBag.StoreID">
                            </select>
                            <span asp-validation-for="@item.StoreID" class="text-danger"></span>
                        </div>
                    </div>
                </td>
                <td>
                    <div class="form-group">
                        <div class="col-md-10">
                            <input type="number" max="10" step=".1" asp-for="@item.PUnit" class="form-control" />
                            <span asp-validation-for="@item.PUnit" class="text-danger"></span>
                        </div>
                    </div>
                </td>
                <td>
                    <div class="form-group">
                        <div class="col-md-10">
                            <select name="Status" asp-for="@item.Status" class="form-control">
                                <option value="0">Operativo</option>
                                <option value="1">Nuevo Item</option>
                                <option value="2">Reparación</option>
                            </select>
                            <span asp-validation-for="@item.Status" class="text-danger"></span>
                        </div>
                    </div>
                </td>
                <td>
                    <input id="submit-data" type="submit" value="Update" class="btn btn-default" />
                </td>
            </tr>
        </tbody>
    </table>

</form>}
</code>```

Thanks in advance

答:
Because the ModelBinder uses naming conventions for binding, try renaming the machine parameter of the TestPost() method to item.

```<code> public async Task<IActionResult> TestPost(
            int id, [Bind("Id, StoreID, PUnit,Status")] Machine item)
    {
        //...
    }
</code>```

Alternatively, in your View, you could rename the item variable to machine, so it matches the expected parameter name:

```<code>@foreach (var machine in Model)
{ ...  }
</code>```

The docs describe this summarily:

Model binding looks for the pattern parameter_name.property_name to bind values to properties

Lastly, leave out the name attribute in your Status dropdown, which would impede modelbinding. Just let asp-for do the work:

```<code><select asp-for="@item.Status" class="form-control">
</code>```

I don't really know how you fill the Store dropdown, but you should at least see the PUnit and Status properties being filled up this way.

Title: Class sent to Post Action is null

Body:
I'm working on a view that presents all the records of class (Machine) where some of their properties could be updated.

For this, the view is working with an IEnumerable. These are the Get and Post methods:

Get:

public async Task<IActionResult> Test()
    {

        PopulateMachineTypeDropDownListStore();
        return View(await _context.Machines.AsNoTracking().ToListAsync());
    }

Post:

[HttpPost, ActionName("Test")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> TestPost(int id, [Bind("Id,StoreID,PUnit,Status")] Machine machine)
    {
        if (id != machine.Id)
        {
            return NotFound();
        }
        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(machine);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!MachineExists(machine.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction("Index");
        }
        return View(machine);}

The problem is that the class sent to the Post Action is null (almost all their fields are zero or null except for the Id)

public async Task<IActionResult> TestPost(int id, [Bind("Id,StoreID,PUnit,Status")] Machine machine)

Question: So, I don't know how to correct this. Could there be something missing in the view?

@model IEnumerable<Application.Models.Machine>
@{
    ViewData["Title"] = "Test";

}
@foreach (var item in Model)
{
    <form asp-action="Test" asp-route-id="@item.Id" method="post">

                    <input type="hidden" asp-for="@item.Id" />

                            <input asp-for="@item.MchName" readonly class="form-control" />

                            <select asp-for="@item.StoreID" class="form-control" asp-items="ViewBag.StoreID">
                            </select>

                            <input type="number" max="10" step=".1" asp-for="@item.PUnit" class="form-control" />

                            <select name="Status" asp-for="@item.Status" class="form-control">
                                <option value="0">Operativo</option>
                                <option value="1">Nuevo Item</option>
                                <option value="2">Reparación</option>
                            </select>

                    <input id="submit-data" type="submit" value="Update" class="btn btn-default" />

</form>}

Thanks in advance

Body:
Because the ModelBinder uses naming conventions for binding, try renaming the machine parameter of the TestPost() method to item.

 public async Task<IActionResult> TestPost(
            int id, [Bind("Id, StoreID, PUnit,Status")] Machine item)
    {
        //...
    }

Alternatively, in your View, you could rename the item variable to machine, so it matches the expected parameter name:

@foreach (var machine in Model)
{ ...  }

The docs describe this summarily:

Model binding looks for the pattern parameter_name.property_name to bind values to properties

Lastly, leave out the name attribute in your Status dropdown, which would impede modelbinding. Just let asp-for do the work:

<select asp-for="@item.Status" class="form-control">

I don't really know how you fill the Store dropdown, but you should at least see the PUnit and Status properties being filled up this way.


问:
non standard - use '&' to create pointer to member
Forgive any ignorance, I'm new to c++.

Full error message:

coog.cpp(74): error C3867: 'Manager::start_foo': non-standard syntax; use '&' to create a pointer to member

I'm using boost command line and I'm trying to pass a object member function for the notifier. I've tried a variety of things from different posts on here and google but haven't had any luck. The error message is in the title.

Hopefully this will give you a idea of what I'm trying to do:

```<code>Manager manager;

void coog::handle::start(std::vector<char const*>& args, Manager& m)
{
    po::options_description desc("Start allowed options");
    desc.add_options()
        ("foo,f", po::value<std::vector<std::string>>()
            ->multitoken()->notifier(m.start_foo), "start foo(s)")
        ("example", "display an example of how to use each command")
        ("help", "display this message")
    ;

    po::variables_map vm;
    po::store(po::command_line_parser(args.size(), args.data()).
        options(desc).run(), vm);
    po::notify(vm);

}

coog::handle::start(foos, manager);
</code>```

Any help and explanation would be appreciated.

答:
notifier is function with this signature:

typed_value * notifier(function1< void, const T & > f);

You cannot just put here class-method, cause it's not suitable for this signature, you can use boost::bind, lambda, or something else, that will allow you to construct function1 with signature specified above from your class-method.

Example with bind:

```<code>notifier(boost::bind(&Manager::start_foo, boost::ref(m), _1))
</code>```

Example with lambda:

```<code>notifier([&m](const T& v) { return m.start_foo(v); })
</code>```

That also depends on start_foo signature, you may need to bind more values.

Body:
Forgive any ignorance, I'm new to c++.

Full error message:

coog.cpp(74): error C3867: 'Manager::start_foo': non-standard syntax; use '&' to create a pointer to member

I'm using boost command line and I'm trying to pass a object member function for the notifier. I've tried a variety of things from different posts on here and google but haven't had any luck. The error message is in the title.

Hopefully this will give you a idea of what I'm trying to do:

Manager manager;

void coog::handle::start(std::vector<char const*>& args, Manager& m)
{
    po::options_description desc("Start allowed options");
    desc.add_options()
        ("foo,f", po::value<std::vector<std::string>>()
            ->multitoken()->notifier(m.start_foo), "start foo(s)")
        ("example", "display an example of how to use each command")
        ("help", "display this message")
    ;

    po::variables_map vm;
    po::store(po::command_line_parser(args.size(), args.data()).
        options(desc).run(), vm);
    po::notify(vm);

}

coog::handle::start(foos, manager);

Any help and explanation would be appreciated.

Body:
notifier is function with this signature:

typed_value * notifier(function1< void, const T & > f);

You cannot just put here class-method, cause it's not suitable for this signature, you can use boost::bind, lambda, or something else, that will allow you to construct function1 with signature specified above from your class-method.

Example with bind:

notifier(boost::bind(&Manager::start_foo, boost::ref(m), _1))

Example with lambda:

notifier([&m](const T& v) { return m.start_foo(v); })

That also depends on start_foo signature, you may need to bind more values.


问:
How use Window aggrgates on strongly typed Spark Datasets?
I'm slowely trying to adapt to the new (strongly typed) Dataset[U] from Spark 2.x, but struggling to maintain the type info when using Window functions.

```<code>case class Measurement(nb:Long,x:Double)
</code>```

ds being a Dataset[Measurement], I would like to do something like

```<code>ds.map{m => (m,sum($"x").over(Window.orderBy($"nb"))}
</code>```

But this will not work (as it gives my a Dataset[(Measurement,Column)]) instead of Dataset[(Measurement,Double)]

Using withColumn  gives me a Dataset[Row], so I'm loosing the type info:

```<code>ds.withColumn("cumsum",sum($"x").over(Window.orderBy($"nb")))
</code>```

So, is there a better way to use Window functions on strongly typed Datasets?

答:
As you adding a new column to your dataset, I guess there is no choices but using the dataframe.as[New Type] method

More information can be found here How to add a column to Dataset without converting from a DataFrame and accessing it?

More information on Window functions can be found on this blog article Window Functions in Spark SQL by Databricks

Body:
I'm slowely trying to adapt to the new (strongly typed) Dataset[U] from Spark 2.x, but struggling to maintain the type info when using Window functions.

case class Measurement(nb:Long,x:Double)

ds being a Dataset[Measurement], I would like to do something like

ds.map{m => (m,sum($"x").over(Window.orderBy($"nb"))}

But this will not work (as it gives my a Dataset[(Measurement,Column)]) instead of Dataset[(Measurement,Double)]

Using withColumn  gives me a Dataset[Row], so I'm loosing the type info:

ds.withColumn("cumsum",sum($"x").over(Window.orderBy($"nb")))

So, is there a better way to use Window functions on strongly typed Datasets?


问:
javascript object error
This is my situation:

```<code>

var r = {"id":"test","files":[],"code":""};

var Page = Class.create({

 initialize: function(json) {
  this.id = json.id;
  this.json = json;

 },
        start: function() {
  this.json.files.each(function(x) {
   var cssResource = this.pageResource(x, 'css');
   this.attachCssResource(cssResource);

  }.bind(this));
        },

//etc....

});

var P = new Page(r);
P.start();

</code>```

Hi have this.json.files.each is not a function.. why?

I use prototype 1.7 library.

if i use this

```<code>
var P = new Page({"id":"test","files":[],"code":""});
</code>```

i have NO error??....

答:
You may need to extend the PrototypeJS functions on your array to get the each function to work:

```<code>$A(this.json.files).each(function(x) {
   ...
}
</code>```

http://www.prototypejs.org/api/utility/dollar-a

http://www.prototypejs.org/api/element/extend

Title: javascript object error

Body:
This is my situation:

var r = {"id":"test","files":[],"code":""};

var Page = Class.create({

 initialize: function(json) {
  this.id = json.id;
  this.json = json;

 },
        start: function() {
  this.json.files.each(function(x) {
   var cssResource = this.pageResource(x, 'css');
   this.attachCssResource(cssResource);

  }.bind(this));
        },

//etc....

});

var P = new Page(r);
P.start();

Hi have this.json.files.each is not a function.. why?

I use prototype 1.7 library.

if i use this

var P = new Page({"id":"test","files":[],"code":""});

i have NO error??....

Body:
You may need to extend the PrototypeJS functions on your array to get the each function to work:

$A(this.json.files).each(function(x) {
   ...
}

http://www.prototypejs.org/api/utility/dollar-a

http://www.prototypejs.org/api/element/extend


问:
Javascript: variable is not undefined but while returning, being returned undefined
In the snippet below, before return(res) , I log it, and it's not undefined

but somehow, it's being returned as undefined.

What am I doing wrong?

filterData = (inputData, searchedKey) => {
  inputData.forEach((data, index) => {
    if(data){
      if(data.hasOwnProperty(searchedKey)){
        const res = data[searchedKey]
        console.log(res) /// logs the results
        return(res) /// returns undefined
      }
      var dataToProcess = [];

      var fieldKeys = Object.keys(data)
      fieldKeys = fieldKeys.filter((field, index) => !field.includes("#"))
      fieldKeys.forEach((key, index) => {
        dataToProcess.push(data[key]);
      })
      this.filterData(dataToProcess, searchedKey)
    }
  })
}

console.log(this.filterData([{"#name": "foo", "#type": "bar"}], "#type"))```

答:
Is this what you want to achieve?

filterData = (inputData, searchedKey) => {
  return inputData.map((data, index) => {
    if(data){
      if(data.hasOwnProperty(searchedKey)){
        const res = data[searchedKey]
        console.log(res) /// logs the results
        return(res) /// returns undefined
      }
      var dataToProcess = [];

      var fieldKeys = Object.keys(data)
      fieldKeys = fieldKeys.filter((field, index) => !field.includes("#"))
      fieldKeys.forEach((key, index) => {
        dataToProcess.push(data[key]);
      })
      this.filterData(dataToProcess, searchedKey)
    }
  })
}

console.log(this.filterData([{"#name": "foo", "#type": "bar"}], "#type"))```

Use Array#map(), it's pretty useful in many cases.

Body:
Is this what you want to achieve?

filterData = (inputData, searchedKey) => {
  return inputData.map((data, index) => {
    if(data){
      if(data.hasOwnProperty(searchedKey)){
        const res = data[searchedKey]
        console.log(res) /// logs the results
        return(res) /// returns undefined
      }
      var dataToProcess = [];

      var fieldKeys = Object.keys(data)
      fieldKeys = fieldKeys.filter((field, index) => !field.includes("#"))
      fieldKeys.forEach((key, index) => {
        dataToProcess.push(data[key]);
      })
      this.filterData(dataToProcess, searchedKey)
    }
  })
}

console.log(this.filterData([{"#name": "foo", "#type": "bar"}], "#type"))

Use Array#map(), it's pretty useful in many cases.


答:
Your is_valid_command function can be simplified to:

```<code>def is_valid_command(command):
    return command in commands
</code>```

Title: Python: Checking if a key is part of a dictionary

Body:
I'm trying to make my own irc bot (for twitch) in Python. I have a dictionary with my commands:

commands = {

    '!ping': {
        'cooldown': 30,
        'return': '!pong'
    },

    '!random': {
        'cooldown': 30,
        'return': 'command',
        'argc': 2,
        'arg_username': True,
        'usage': '!random <min> <max>'
    }

} # End of commands

Then I have a function to check if the message that was send is indeed a command:

import string

def is_valid_command(command):
    return True if command in commands.keys() else False

So when i test this function out, it don't seems to work, and I don't know what I am doiing wrong:

message = "!ping"
print(str(is_valid_command(message)))
>>> False

I tried to change '!ping' inside the dictionary to "!ping", and virsa versa with the message, even deleted the '!' and it always says it's False.

Thanks in regards,
Laurens

EDIT:

def is_valid_command(command):
    for key in commands.keys():
        print(key)
    print("input " + str(command))
    print(command in commands.keys())
    return command in commands.keys()

This result in this:

!ping
!random
input !ping
False

EDIT2: @e4c5 wanted me to use try/except, as i quickly try it (inside that methode), it still return False

try:
    cmd = commands[command]
    print ('Try True')
    return True
except KeyError:
    print('Try False')
    return False

EDIT3: u'!ping' before fixed this (message = u'!ping'), but when I read a string from somewhere else, is there a function that does this unicoding?

Body:
Your is_valid_command function can be simplified to:

def is_valid_command(command):
    return command in commands


问:
Why the below code does not compile with gcc but compiles fine with clang
Below code compiles fine with clang but not gcc , any explanation is this a bug in gcc?

Its just a class which contains a vector of unique_ptr and std::function as member and when I create vector of this class , I cant say reserve or resize on this. push_back works fine with std::move, while this only happens with gcc and not clang.

```<code>#include <algorithm>
#include <memory>
#include <utility>
#include <iostream>
#include <vector>
#include <functional>

using namespace std;

class ABC
{
public:
    ABC()
          {}
  private:
    std::vector<std::unique_ptr<int>> up;
    std::function<void (int*)> func;
};

int main()
{
    ABC a;
    std::vector<ABC> vec;
    vec.reserve(1);
}
</code>```

Error message looks like below for gcc

```<code>In file included from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_tempbuf.h:60:0,
                 from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_algo.h:62,
                 from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/algorithm:62,
                 from prog.cc:1:
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_construct.h: In instantiation of 'void std::_Construct(_T1*, _Args&& ...) [with _T1 = std::unique_ptr<int>; _Args = {const std::unique_ptr<int, std::default_delete<int> >&}]':
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:83:18:   required from 'static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::unique_ptr<int>*, std::vector<std::unique_ptr<int> > >; _ForwardIterator = std::unique_ptr<int>*; bool _TrivialValueTypes = false]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:134:15:   required from '_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::unique_ptr<int>*, std::vector<std::unique_ptr<int> > >; _ForwardIterator = std::unique_ptr<int>*]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:289:37:   required from '_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::unique_ptr<int>*, std::vector<std::unique_ptr<int> > >; _ForwardIterator = std::unique_ptr<int>*; _Tp = std::unique_ptr<int>]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_vector.h:331:31:   required from 'std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = std::unique_ptr<int>; _Alloc = std::allocator<std::unique_ptr<int> >]'
prog.cc:10:7:   required from 'void std::_Construct(_T1*, _Args&& ...) [with _T1 = ABC; _Args = {const ABC&}]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:83:18:   required from 'static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = const ABC*; _ForwardIterator = ABC*; bool _TrivialValueTypes = false]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:134:15:   required from '_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = const ABC*; _ForwardIterator = ABC*]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:289:37:   required from '_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = const ABC*; _ForwardIterator = ABC*; _Tp = ABC]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_vector.h:1263:35:   required from 'std::vector<_Tp, _Alloc>::pointer std::vector<_Tp, _Alloc>::_M_allocate_and_copy(std::vector<_Tp, _Alloc>::size_type, _ForwardIterator, _ForwardIterator) [with _ForwardIterator = const ABC*; _Tp = ABC; _Alloc = std::allocator<ABC>; std::vector<_Tp, _Alloc>::pointer = ABC*; std::vector<_Tp, _Alloc>::size_type = long unsigned int]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/vector.tcc:73:40:   required from 'void std::vector<_Tp, _Alloc>::reserve(std::vector<_Tp, _Alloc>::size_type) [with _Tp = ABC; _Alloc = std::allocator<ABC>; std::vector<_Tp, _Alloc>::size_type = long unsigned int]'
prog.cc:24:18:   required from here
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_construct.h:75:7: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]'
     { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/memory:80:0,
                 from prog.cc:2:
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/unique_ptr.h:388:7: note: declared here
       unique_ptr(const unique_ptr&) = delete;
       ^~~~~~~~~~
</code>```

答:
GCC accepted the lack of noexcept on std::function's move ctor as bug

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81017

//  -- C++ --

```<code>  /** 2227        *  @brief %Function move constructor. 2228        *  @param
 __x A %function object rvalue with identical call signature. 2229        * 2230
*  The newly-created %function contains the target of @a __x 2231        *  (if
it has one). 2232        */ 2233
function(function&& __x) : _Function_base()  {     __x.swap(*this); }
</code>```

Body:
Below code compiles fine with clang but not gcc , any explanation is this a bug in gcc?

Its just a class which contains a vector of unique_ptr and std::function as member and when I create vector of this class , I cant say reserve or resize on this. push_back works fine with std::move, while this only happens with gcc and not clang.

#include <algorithm>
#include <memory>
#include <utility>
#include <iostream>
#include <vector>
#include <functional>

using namespace std;

class ABC
{
public:
    ABC()
          {}
  private:
    std::vector<std::unique_ptr<int>> up;
    std::function<void (int*)> func;
};

int main()
{
    ABC a;
    std::vector<ABC> vec;
    vec.reserve(1);
}

Error message looks like below for gcc

In file included from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_tempbuf.h:60:0,
                 from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_algo.h:62,
                 from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/algorithm:62,
                 from prog.cc:1:
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_construct.h: In instantiation of 'void std::_Construct(_T1*, _Args&& ...) [with _T1 = std::unique_ptr<int>; _Args = {const std::unique_ptr<int, std::default_delete<int> >&}]':
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:83:18:   required from 'static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::unique_ptr<int>*, std::vector<std::unique_ptr<int> > >; _ForwardIterator = std::unique_ptr<int>*; bool _TrivialValueTypes = false]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:134:15:   required from '_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::unique_ptr<int>*, std::vector<std::unique_ptr<int> > >; _ForwardIterator = std::unique_ptr<int>*]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:289:37:   required from '_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::unique_ptr<int>*, std::vector<std::unique_ptr<int> > >; _ForwardIterator = std::unique_ptr<int>*; _Tp = std::unique_ptr<int>]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_vector.h:331:31:   required from 'std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = std::unique_ptr<int>; _Alloc = std::allocator<std::unique_ptr<int> >]'
prog.cc:10:7:   required from 'void std::_Construct(_T1*, _Args&& ...) [with _T1 = ABC; _Args = {const ABC&}]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:83:18:   required from 'static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = const ABC*; _ForwardIterator = ABC*; bool _TrivialValueTypes = false]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:134:15:   required from '_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = const ABC*; _ForwardIterator = ABC*]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:289:37:   required from '_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = const ABC*; _ForwardIterator = ABC*; _Tp = ABC]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_vector.h:1263:35:   required from 'std::vector<_Tp, _Alloc>::pointer std::vector<_Tp, _Alloc>::_M_allocate_and_copy(std::vector<_Tp, _Alloc>::size_type, _ForwardIterator, _ForwardIterator) [with _ForwardIterator = const ABC*; _Tp = ABC; _Alloc = std::allocator<ABC>; std::vector<_Tp, _Alloc>::pointer = ABC*; std::vector<_Tp, _Alloc>::size_type = long unsigned int]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/vector.tcc:73:40:   required from 'void std::vector<_Tp, _Alloc>::reserve(std::vector<_Tp, _Alloc>::size_type) [with _Tp = ABC; _Alloc = std::allocator<ABC>; std::vector<_Tp, _Alloc>::size_type = long unsigned int]'
prog.cc:24:18:   required from here
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_construct.h:75:7: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]'
     { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/memory:80:0,
                 from prog.cc:2:
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/unique_ptr.h:388:7: note: declared here
       unique_ptr(const unique_ptr&) = delete;
       ^~~~~~~~~~

Body:
GCC accepted the lack of noexcept on std::function's move ctor as bug

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81017

//  -- C++ --

  /** 2227        *  @brief %Function move constructor. 2228        *  @param
 __x A %function object rvalue with identical call signature. 2229        * 2230
*  The newly-created %function contains the target of @a __x 2231        *  (if
it has one). 2232        */ 2233
function(function&& __x) : _Function_base()  {     __x.swap(*this); }


问:
How do I convert a derived recursive data type to a base data type?
I have a class called nesteddict derived from collections.defaultdict that hold a nested set of dictionaries:

```<code>import collections

class nesteddict(collections.defaultdict):
    """Nested dictionary structure.

    Based on Stack Overflow question 635483
    """
    def __init__(self):
        collections.defaultdict.__init__(self, nesteddict)
        self.locked = False
</code>```

I would like to be able to perform an operation an instance that converts all of the nesteddict objects to python-native dict objects.

One way to do this is to have a method:

```<code>def todict(self):
    for (key,val) in self.iteritems():
        if isinstance(val,nesteddict):
            val.todict()
            self[key] = dict(val)
    self = dict(self)
</code>```

This is successful at replacing all the inner mapping objects with dict types, but the last statement in the method is obviously not going to work.

Here is an example:

```<code>In [93]: a = pyutils.nesteddict()

In [94]: a[1][1] = 'a'

In [95]: a[1][2] = 'b'

In [96]: a[2][1] = 'c'

In [97]: a[2][2] = 'd'

In [98]: print a
defaultdict(<class 'pyutils.nesteddict'>, {1: defaultdict(<class 'pyutils.nesteddict'>, {1: 'a', 2: 'b'}), 2: defaultdict(<class 'pyutils.nesteddict'>, {1: 'c', 2: 'd'})})

In [99]: a.todict()

In [100]: print a
defaultdict(<class 'pyutils.nesteddict'>, {1: {1: 'a', 2: 'b'}, 2: {1: 'c', 2: 'd'}})
</code>```

Is there a way to do this in python?  Have a method that converts its object to another type?  If not, what is a good alternative to this.  Note that the datatype in practice may be large, so it would be preferable not to just make a copy and then return it.

Thanks!

Uri

答:
Do it as a free function, and while you're at it, consider a more functional style approach:</p>

```<code>def undefaulted(x):
  return dict(
    (k, undefaulted(v))
    for (k, v) in x.iteritems()
  ) if isinstance(x, nesteddict) else x

a = undefaulted(a)
</code>```

Body:
I have a class called nesteddict derived from collections.defaultdict that hold a nested set of dictionaries:

import collections

class nesteddict(collections.defaultdict):
    """Nested dictionary structure.

    Based on Stack Overflow question 635483
    """
    def __init__(self):
        collections.defaultdict.__init__(self, nesteddict)
        self.locked = False

I would like to be able to perform an operation an instance that converts all of the nesteddict objects to python-native dict objects.

One way to do this is to have a method:

def todict(self):
    for (key,val) in self.iteritems():
        if isinstance(val,nesteddict):
            val.todict()
            self[key] = dict(val)
    self = dict(self)

This is successful at replacing all the inner mapping objects with dict types, but the last statement in the method is obviously not going to work.

Here is an example:

In [93]: a = pyutils.nesteddict()

In [94]: a[1][1] = 'a'

In [95]: a[1][2] = 'b'

In [96]: a[2][1] = 'c'

In [97]: a[2][2] = 'd'

In [98]: print a
defaultdict(<class 'pyutils.nesteddict'>, {1: defaultdict(<class 'pyutils.nesteddict'>, {1: 'a', 2: 'b'}), 2: defaultdict(<class 'pyutils.nesteddict'>, {1: 'c', 2: 'd'})})

In [99]: a.todict()

In [100]: print a
defaultdict(<class 'pyutils.nesteddict'>, {1: {1: 'a', 2: 'b'}, 2: {1: 'c', 2: 'd'}})

Is there a way to do this in python?  Have a method that converts its object to another type?  If not, what is a good alternative to this.  Note that the datatype in practice may be large, so it would be preferable not to just make a copy and then return it.

Thanks!

Uri

Body:
Do it as a free function, and while you're at it, consider a more functional style approach:

def undefaulted(x):
  return dict(
    (k, undefaulted(v))
    for (k, v) in x.iteritems()
  ) if isinstance(x, nesteddict) else x

a = undefaulted(a)


问:
how to convert folder into Zip file in codeigniter where folder contains some image file
i have some doubts in zipping the folder in codeigniter.Actually i have some image files in the folder and i was trying to zip this folder in codegiter. I have view file where i have written "Download all file" button. On clicking this button i have to take the folder and zip it.
My view file:
I have written the button "Download All Files" inside the anchor tag.

```<code><tr>
    <td align="right">
        <?php  if(isset($AppData) && !empty($AppData)) {
          $applicantNo = $AppData[0]['appid']; ?>
        <a href='<?php echo base_url("admin/downloadAllFileZip/$applicantNo");?>'><input type="submit" name="download" value="Download All Files" /></a>
         <?php } ?>

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

Controller code:
Inside admin.php controller file i have the below method

```<code>public function downloadAllFileZip($appId)
    {

        $path = file_get_contents(base_url().'files/'.$appId);
        $applicant_id = $appId;
        $this->zip->add_data($applicant_id,$path);
        $this->zip->archive('/files/'.$applicant_id);
        $this->zip->download($applicant_id);

    }
</code>```

But when I am clicking the " Download all file " button the popup window for zipping is comming and after downloading its showing 1kb file but there is no image on that file. I can able to zip single image file as a zip file but not able to zip the entire folder. Please help me how to do this.

答:
```<code>$this->load->library('zip');
$path = '/path/to/your_directory/';
$this->zip->read_dir($path);
$this->zip->download('my_backup.zip');
</code>```

Body:
i have some doubts in zipping the folder in codeigniter.Actually i have some image files in the folder and i was trying to zip this folder in codegiter. I have view file where i have written "Download all file" button. On clicking this button i have to take the folder and zip it.
My view file:
I have written the button "Download All Files" inside the anchor tag.

        <?php  if(isset($AppData) && !empty($AppData)) {
          $applicantNo = $AppData[0]['appid']; ?>
        <a href='<?php echo base_url("admin/downloadAllFileZip/$applicantNo");?>'><input type="submit" name="download" value="Download All Files" />
         <?php } ?>

Controller code:
Inside admin.php controller file i have the below method

public function downloadAllFileZip($appId)
    {

        $path = file_get_contents(base_url().'files/'.$appId);
        $applicant_id = $appId;
        $this->zip->add_data($applicant_id,$path);
        $this->zip->archive('/files/'.$applicant_id);
        $this->zip->download($applicant_id);

    }

But when I am clicking the " Download all file " button the popup window for zipping is comming and after downloading its showing 1kb file but there is no image on that file. I can able to zip single image file as a zip file but not able to zip the entire folder. Please help me how to do this.


问:
EF6, Code First. How to set alternative data source for GridControl column using XAML Devexpress
I have two related entities:

```<code>public class Event
{
    public string ID { get; set; }
    public DateTime EventDate { get; set; }
    public string EventData { get; set; }
    public string DocID1 { get; set; }
    public int DocID2 { get; set; }
    public virtual Document Document1 { get; set; }
    public virtual Document Document2 { get; set; }

}

public class Document
{

    public string ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Number { get; set; }

}
</code>```

Also created List to display data in WPF:

```<code>private ObservableCollection<Event> eventList;
public ObservableCollection<Event> EventList
        {
            get { return eventList; }
            set
            {
                if (value != eventList)
                {
                    eventList = value;
                }
                RaisePropertyChanged(nameof(EventList));
            }
        }
</code>```

data for my EventList is taken from entity Event:

```<code>var query = DBContext.Events.Select(x => x).AsQueryable();
EventList = query.ToList();
</code>```

What I need is how to set GridControl Column "colFirstName" value to be equal "Document1.FirstName" if DocID1 is not null and "Document2.FirstName" if DocID2 is not null. My XAML code for GridControl is below, could You help how to do it in Xaml, not in ViewModel, or if there is no way to do it in Xaml, what is the best way to do it in ViewModel.

```<code><dxg:GridControl AutoPopulateColumns="False"
ItemsSource="{Binding EventList, UpdateSourceTrigger=PropertyChanged}">

                        <dxg:GridControl.Columns>
                            <dxg:GridColumn
                                x:Name="colEventData"
                                Width="120"
                                FieldName="EventData"
                                 Header =" Event data"
                                Visible="True" >
                        </dxg:GridColumn>

                        <dxg:GridColumn
                                x:Name="colFirsnName"
                                Width="120"
                                FieldName="Document1.FirstName"
                                Header="First Name"
                                Visible="True"
                                VisibleIndex="1" />
                          </dxg:GridControl.Columns>
                        </dxg:GridControl>
</code>```

答:
This kind of logic should be implemented in the model or view model class. Remember that XAML is only a markup language.

Just create another property that returns the first match and bind to this one. If your entity classes are auto-generated, you could create a new partial class:

```<code>public partial class Event
{
    public string DocName
    {
        get
        {
            if (Document1 != null)
                return Document1.FirstName;

            if (Document2 != null)
                return Document1.LastName;

            return null;
        }
    }
}
</code>```

```<code><dxg:GridColumn
    x:Name="colFirsnName"
    Width="120"
    FieldName="DocName"
    Header="First Name"
    Visible="True"
    VisibleIndex="1" IsReadOnly="true" />
</code>```

Body:
I have two related entities:

public class Event
{
    public string ID { get; set; }
    public DateTime EventDate { get; set; }
    public string EventData { get; set; }
    public string DocID1 { get; set; }
    public int DocID2 { get; set; }
    public virtual Document Document1 { get; set; }
    public virtual Document Document2 { get; set; }

}

public class Document
{

    public string ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Number { get; set; }

}

Also created List to display data in WPF:

private ObservableCollection<Event> eventList;
public ObservableCollection<Event> EventList
        {
            get { return eventList; }
            set
            {
                if (value != eventList)
                {
                    eventList = value;
                }
                RaisePropertyChanged(nameof(EventList));
            }
        }

data for my EventList is taken from entity Event:

var query = DBContext.Events.Select(x => x).AsQueryable();
EventList = query.ToList();

What I need is how to set GridControl Column "colFirstName" value to be equal "Document1.FirstName" if DocID1 is not null and "Document2.FirstName" if DocID2 is not null. My XAML code for GridControl is below, could You help how to do it in Xaml, not in ViewModel, or if there is no way to do it in Xaml, what is the best way to do it in ViewModel.

<dxg:GridControl AutoPopulateColumns="False"
ItemsSource="{Binding EventList, UpdateSourceTrigger=PropertyChanged}">

                        <dxg:GridControl.Columns>
                            <dxg:GridColumn
                                x:Name="colEventData"
                                Width="120"
                                FieldName="EventData"
                                 Header =" Event data"
                                Visible="True" >
                        </dxg:GridColumn>

                        <dxg:GridColumn
                                x:Name="colFirsnName"
                                Width="120"
                                FieldName="Document1.FirstName"
                                Header="First Name"
                                Visible="True"
                                VisibleIndex="1" />
                          </dxg:GridControl.Columns>
                        </dxg:GridControl>

Body:
This kind of logic should be implemented in the model or view model class. Remember that XAML is only a markup language.

Just create another property that returns the first match and bind to this one. If your entity classes are auto-generated, you could create a new partial class:

public partial class Event
{
    public string DocName
    {
        get
        {
            if (Document1 != null)
                return Document1.FirstName;

            if (Document2 != null)
                return Document1.LastName;

            return null;
        }
    }
}

<dxg:GridColumn
    x:Name="colFirsnName"
    Width="120"
    FieldName="DocName"
    Header="First Name"
    Visible="True"
    VisibleIndex="1" IsReadOnly="true" />


问:
Angular2 don't work in IE9
I have one angular2 project, and it is working well for Chrome e IE11.

I tried to run everything on IE9 but did not load the page correctly and I console the following error:

SCRIPT5007: Object expected  polyfills.bundle.js, line 8894 character
  2`

this is the my index.html

```<code><!doctype html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Title</title>
      <base href="/">

      <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" />
      <link rel="icon" type="image/x-icon" href="favicon.ico">
      <script src="assets/js/jquery-1.12.1.min.js"></script>
      <script src="assets/js/jquery-ui.js"></script>
      <script src="node_modules/core-js/client/shim.min.js"></script>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
      <!--[if lte IE 9]>
        <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
        <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
        <script src="/node_modules/zone.js/dist/zone.js"></script>
      <!--<![endif]-->

    </head>
    <body>
       <app-root >Loading...</app-root>
    </body>
    </html>
</code>```

and this the package.json

```<code>{
  "name": "angular-p",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.config.json",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^2.4.0",
    "@angular/compiler": "^2.4.0",
    "@angular/core": "^2.4.0",
    "@angular/forms": "^2.4.0",
    "@angular/http": "^2.4.0",
    "@angular/platform-browser": "^2.4.0",
    "@angular/platform-browser-dynamic": "^2.4.0",
    "@angular/router": "^3.4.0",
    "angular2-modal": "^2.0.3",
    "bootstrap": "3.3.7",
    "classlist.js": "^1.1.20150312",
    "core-js": "^2.4.1",
    "hammerjs": "^2.0.8",
    "intl": "^1.2.5",
    "ng-select": "^1.0.0-beta.4",
    "ng2-validation": "^4.0.0",
    "ngx-mydatepicker": "^0.1.5",
    "rxjs": "^5.1.0",
    "web-animations-js": "^2.2.2",
    "zone.js": "^0.7.6"
  },
  "devDependencies": {
    "@angular/cli": "1.0.0",
    "@angular/compiler-cli": "^2.4.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "~6.0.60",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.0.0",
    "karma-cli": "~1.0.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.5.0",
    "typescript": "~2.0.0"
  }
}
</code>```

I don't know how to fix it. Please help me!!

答:
My suggestion is to include Babel as well:

```<code>"babel-cli": "^6.16.0",
"babel-preset-angular2": "^0.0.2",
"babel-preset-es2015": "^6.16.0",
"babel-polyfill":"6.23.0",
</code>```

Make sure you include them in your bundle.js as well

Title: Angular2 don't work in IE9

Body:
I have one angular2 project, and it is working well for Chrome e IE11.

I tried to run everything on IE9 but did not load the page correctly and I console the following error:

SCRIPT5007: Object expected  polyfills.bundle.js, line 8894 character
  2`

this is the my index.html

<!doctype html>

      <meta charset="utf-8">
      <title>Title</title>
      <base href="/">

      <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" />
      <link rel="icon" type="image/x-icon" href="favicon.ico">

      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

       <app-root >Loading...</app-root>

and this the package.json

{
  "name": "angular-p",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.config.json",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^2.4.0",
    "@angular/compiler": "^2.4.0",
    "@angular/core": "^2.4.0",
    "@angular/forms": "^2.4.0",
    "@angular/http": "^2.4.0",
    "@angular/platform-browser": "^2.4.0",
    "@angular/platform-browser-dynamic": "^2.4.0",
    "@angular/router": "^3.4.0",
    "angular2-modal": "^2.0.3",
    "bootstrap": "3.3.7",
    "classlist.js": "^1.1.20150312",
    "core-js": "^2.4.1",
    "hammerjs": "^2.0.8",
    "intl": "^1.2.5",
    "ng-select": "^1.0.0-beta.4",
    "ng2-validation": "^4.0.0",
    "ngx-mydatepicker": "^0.1.5",
    "rxjs": "^5.1.0",
    "web-animations-js": "^2.2.2",
    "zone.js": "^0.7.6"
  },
  "devDependencies": {
    "@angular/cli": "1.0.0",
    "@angular/compiler-cli": "^2.4.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "~6.0.60",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.0.0",
    "karma-cli": "~1.0.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.5.0",
    "typescript": "~2.0.0"
  }
}

I don't know how to fix it. Please help me!!

Body:
My suggestion is to include Babel as well:

"babel-cli": "^6.16.0",
"babel-preset-angular2": "^0.0.2",
"babel-preset-es2015": "^6.16.0",
"babel-polyfill":"6.23.0",

Make sure you include them in your bundle.js as well


问:
How do I initiate a fancybox 3 slideshow by clicking on a single image or button
How do I initiate a fancybox 3 slideshow by clicking on a single image or button. There appears to be a good example on the Fancyapps site with the Custom Demo but no coding example specific to this case.</p>

答:
If you are looking for a way to start gallery with one preview image, then simply create your links and make only first one visible, see this demo - https://codepen.io/fancyapps/pen/WjVXyx?editors=1000</p>

```<code><p>
    <a href="https://c1.staticflickr.com/1/357/31876784275_12286240d4_h.jpg" data-fancybox="images-single">
      <img src="https://c1.staticflickr.com/1/357/31876784275_fbc9696913_m.jpg" />
    </a>
</p>

<div style="display: none;">

  <a href="https://farm3.staticflickr.com/2947/33594572585_b48eba935b_k_d.jpg" data-fancybox="images-single"
     data-thumb="https://farm3.staticflickr.com/2947/33594572585_46ca00f3a5_m_d.jpg"></a>

  <a href="https://farm3.staticflickr.com/2859/33395734202_522f9d8efd_k_d.jpg" data-fancybox="images-single"
     data-thumb="https://farm3.staticflickr.com/2859/33395734202_15a81c4ef3_m_d.jpg"></a>

</div>
</code>```

Body:
If you are looking for a way to start gallery with one preview image, then simply create your links and make only first one visible, see this demo - https://codepen.io/fancyapps/pen/WjVXyx?editors=1000

<p>
    <a href="https://c1.staticflickr.com/1/357/31876784275_12286240d4_h.jpg" data-fancybox="images-single">
      <img src="https://c1.staticflickr.com/1/357/31876784275_fbc9696913_m.jpg" />
    </a>
</p>

<div style="display: none;">

  <a href="https://farm3.staticflickr.com/2947/33594572585_b48eba935b_k_d.jpg" data-fancybox="images-single"
     data-thumb="https://farm3.staticflickr.com/2947/33594572585_46ca00f3a5_m_d.jpg"></a>

  <a href="https://farm3.staticflickr.com/2859/33395734202_522f9d8efd_k_d.jpg" data-fancybox="images-single"
     data-thumb="https://farm3.staticflickr.com/2859/33395734202_15a81c4ef3_m_d.jpg"></a>

</div>


问:
"Module name is invalid" when exporting an existing eclipse project to a war file
I am trying to export an existing Eclipse project to a war file. But whatever I typed in the "WAR Export" dialog page, the system always returned "Module name is invalid". I do not know how to fix this issue. Thanks for the help.</p>

答: I am not sure about the exact cause. But this gets resolved most of the times if you give the exporting project war file name just same as the project name in the IDE</p>


问:
Creating path-names with variables in Python 2.7
I'd like to create some folders to store results of some simulations in a logical way with a naming system.

My code has 4 main parameters that I'm investigating and I'd like to dynamically create paths with these parameters in the pathnames, example below:

```<code>a = 'test'
b = 2
c = 3
d = 4

os.chdir('./results/test_b_c_d/outputs')
</code>```

I'll manually change the values of a-d for now as these are just a few test results. A needs to be a string but b-d are just integers.

I've seen I can do

```<code>os.path.join('./results/', test, '/outputs/'))
</code>```

Where the 'join' command will add a folder of that name in that path directory, but can I use this or a similar command to change the actual folder name with changing variables?

Thanks

答:
You can use a mix between str.format to build a string using variables values and os.path.join to build intelligently a path with the right separator (depending on platform).

Example:

```<code>a = 'test'
b = 2
c = 3
d = 4

my_path = os.path.join(os.getcwd(), 'results', '{}_{}_{}_{}'.format(a,b,c,d), 'outputs')

os.chdir(my_path)
</code>```

Not that os.getcwd is one solution to get the current working directory

Body:
I'd like to create some folders to store results of some simulations in a logical way with a naming system.

My code has 4 main parameters that I'm investigating and I'd like to dynamically create paths with these parameters in the pathnames, example below:

a = 'test'
b = 2
c = 3
d = 4

os.chdir('./results/test_b_c_d/outputs')

I'll manually change the values of a-d for now as these are just a few test results. A needs to be a string but b-d are just integers.

I've seen I can do

os.path.join('./results/', test, '/outputs/'))

Where the 'join' command will add a folder of that name in that path directory, but can I use this or a similar command to change the actual folder name with changing variables?

Thanks

Body:
You can use a mix between str.format to build a string using variables values and os.path.join to build intelligently a path with the right separator (depending on platform).

Example:

a = 'test'
b = 2
c = 3
d = 4

my_path = os.path.join(os.getcwd(), 'results', '{}_{}_{}_{}'.format(a,b,c,d), 'outputs')

os.chdir(my_path)

Not that os.getcwd is one solution to get the current working directory