问:
How to compare same column in the same table in SQL?
Let's say I have a table with following records

```<code>Name             Seq                  Join                     Resign
---------------- ---------------------------------------- ----------------------------
Joe              1                    2001-11-04 00:00:00.000  2005-03-31 00:00:00.000
Joe              2                    2005-04-01 00:00:00.000  NULL
Jane             1                    2011-12-04 00:00:00.000  2013-02-01 00:00:00.000
Jane             2                    2015-05-01 00:00:00.000  NULL
Jack             1                    2001-01-01 00:00:00.000  2002-01-01 00:00:00.000
Jack             2                    2002-01-02 00:00:00.000  2003-01-01 00:00:00.000
Jack             3                    2005-01-01 00:00:00.000  2006-01-01 00:00:00.000
Jack             4                    2006-01-02 00:00:00.000  NULL
</code>```

So I'm trying to find out Employee Join Date, Seq represents hire number, so if an Employee resign and later rejoin the company, the Seq will increase. But the problem is Seq will also increase when Employee get a promotion or move to another department.

In my case, Joe has 2 Seq but he never resigned because his 2nd Join Date = Resign Date + 1. So my final expected result is

Joe, 2001-11-04

Jane, 2015-05-01

Jack, 2005-01-01 (because he resigned after 2nd hire)

Any idea how to get this result without looping?

Note: Seq can be 1,2,3,4 and so on depends on how many promotion or resign/rejoin on each employee

Jack expected result is 2005-01-01 because from 1st hire to 2nd is not an actual resignation because 2nd hire JoinDate = 1st hire ResignDate + 1 2002-01-01 = 2002-01-02 + 1. But from 2nd hire to 3rd hire is an actually resignation because 2003-01-01 != 2005-01-01 + 1. I hope that make sense.

答:
This is more easy to understand </p>

```<code>;WITH cte AS (
    SELECT  res.*,
       --df = 0 if join and resign dates have difference greater than 1 else df = 1
                DATEDIFF(Day, IsNull(jn.Resign, res.JoinDate), res.JoinDate) df,
                ROW_NUMBER() OVER (PARTITION BY res.Name ORDER BY res.Name DESC) AS rn
    FROM    [dbo].[tblWarheat1990] res
        LEFT JOIN [dbo].[tblWarheat1990] jn ON res.JoinDate = DATEADD(day, 1, jn.Resign)
    )
    , gte as (
    SELECT  *,
            ROW_NUMBER() OVER (partition by name ORDER BY rn DESC) AS minimum
    FROM    cte
    WHERE   df = 0)

    SELECT * FROM gte WHERE minimum = 1
    ORDER BY rn DESC
</code>```

Body:
Let's say I have a table with following records

Name             Seq                  Join                     Resign
---------------- ---------------------------------------- ----------------------------
Joe              1                    2001-11-04 00:00:00.000  2005-03-31 00:00:00.000
Joe              2                    2005-04-01 00:00:00.000  NULL
Jane             1                    2011-12-04 00:00:00.000  2013-02-01 00:00:00.000
Jane             2                    2015-05-01 00:00:00.000  NULL
Jack             1                    2001-01-01 00:00:00.000  2002-01-01 00:00:00.000
Jack             2                    2002-01-02 00:00:00.000  2003-01-01 00:00:00.000
Jack             3                    2005-01-01 00:00:00.000  2006-01-01 00:00:00.000
Jack             4                    2006-01-02 00:00:00.000  NULL

So I'm trying to find out Employee Join Date, Seq represents hire number, so if an Employee resign and later rejoin the company, the Seq will increase. But the problem is Seq will also increase when Employee get a promotion or move to another department.

In my case, Joe has 2 Seq but he never resigned because his 2nd Join Date = Resign Date + 1. So my final expected result is

Joe, 2001-11-04

Jane, 2015-05-01

Jack, 2005-01-01 (because he resigned after 2nd hire)

Any idea how to get this result without looping?

Note: Seq can be 1,2,3,4 and so on depends on how many promotion or resign/rejoin on each employee

Jack expected result is 2005-01-01 because from 1st hire to 2nd is not an actual resignation because 2nd hire JoinDate = 1st hire ResignDate + 1 2002-01-01 = 2002-01-02 + 1. But from 2nd hire to 3rd hire is an actually resignation because 2003-01-01 != 2005-01-01 + 1. I hope that make sense.

Body:
This is more easy to understand

;WITH cte AS (
    SELECT  res.*,
       --df = 0 if join and resign dates have difference greater than 1 else df = 1
                DATEDIFF(Day, IsNull(jn.Resign, res.JoinDate), res.JoinDate) df,
                ROW_NUMBER() OVER (PARTITION BY res.Name ORDER BY res.Name DESC) AS rn
    FROM    [dbo].[tblWarheat1990] res
        LEFT JOIN [dbo].[tblWarheat1990] jn ON res.JoinDate = DATEADD(day, 1, jn.Resign)
    )
    , gte as (
    SELECT  *,
            ROW_NUMBER() OVER (partition by name ORDER BY rn DESC) AS minimum
    FROM    cte
    WHERE   df = 0)

    SELECT * FROM gte WHERE minimum = 1
    ORDER BY rn DESC


来源: stackexchange

问:
Multiple text insertion in Linux
Can someone help me how to write a piece of command that will insert some text in multiple places (given column and row) of a given file that already contains data. For example: old_data is a file that contains:

```<code>A
</code>```

And I wish to get new_data that will contain:

```<code>A 1
</code>```

I read something about awk and sed commands, but I don't believe to understand how to incorporate these, to get what I want.

I would like to add up, that this command I would like to use as a part of script

```<code>for b in ./*/ ; do (cd "$b" && command); done
</code>```

If we imagine content of old_data as a matrix of elements {An*m} where n corresponds to number of row and m to number of column of this matrix, I wish to manipulate with matrix so that I could add new elements. A in old-data has coordinates (1,1). In new_data therefore, I wish to assign 1 to a matrix element that has coordinates (1,3).
If we compare content of old_data and new_data we see that (1,2) element corresponds to space (it is empty).

答:
It's not at all clear to me what you are asking for, but I suspect you are saying that you would like a way to insert some given text in to a particular row and column.  Perhaps:</p>

```<code>$ cat input
A
B
C
D
$ row=2 column=2 text="This is some new data"
$ awk 'NR==row {$column = new_data " " $column}1' row=$row column=$column new_data="$text" input
A
B  This is some new data
C
D
</code>```

ContentLicense: CC BY-SA 3.0

Title: Multiple text insertion in Linux

Body:
Can someone help me how to write a piece of command that will insert some text in multiple places (given column and row) of a given file that already contains data. For example: old_data is a file that contains:

A

And I wish to get new_data that will contain:

A 1

I read something about awk and sed commands, but I don't believe to understand how to incorporate these, to get what I want.

I would like to add up, that this command I would like to use as a part of script

for b in ./*/ ; do (cd "$b" && command); done

If we imagine content of old_data as a matrix of elements {An*m} where n corresponds to number of row and m to number of column of this matrix, I wish to manipulate with matrix so that I could add new elements. A in old-data has coordinates (1,1). In new_data therefore, I wish to assign 1 to a matrix element that has coordinates (1,3).
If we compare content of old_data and new_data we see that (1,2) element corresponds to space (it is empty).

Body:
It's not at all clear to me what you are asking for, but I suspect you are saying that you would like a way to insert some given text in to a particular row and column.  Perhaps:

$ cat input
A
B
C
D
$ row=2 column=2 text="This is some new data"
$ awk 'NR==row {$column = new_data " " $column}1' row=$row column=$column new_data="$text" input
A
B  This is some new data
C
D


问:
Absolute and fixed positioning together
As you can see in this page: http://pitchfork.com/ , there are some audio elements on the right side. I've inspected them and they seem to have absolute positioning. But if you scroll down, you'll see that they are fixed.

How can achieve this behavior? Can be an element Absolute and Fixed positioned?

答:
You can also use calc() to achieve this. (supported in IE9+):

```<code>.fixed {
    position: fixed;
    right: calc(50% - 360px);
    /* Replace 360px with half of container width plus desired positioning */
}
</code>```

or if you want your fixed div on the left, for instance:

```<code>.fixed {
    position: fixed;
    left: calc(50% - 360px);
    /* Replace 360px with half of container width plus desired positioning */
}
</code>```

Title: Absolute and fixed positioning together

Body:
You can also use calc() to achieve this. (supported in IE9+):

.fixed {
    position: fixed;
    right: calc(50% - 360px);
    /* Replace 360px with half of container width plus desired positioning */
}

or if you want your fixed div on the left, for instance:

.fixed {
    position: fixed;
    left: calc(50% - 360px);
    /* Replace 360px with half of container width plus desired positioning */
}


问:
Should I use Pylons or Pyramid?
I was planning to move from Django to Pylons, but then I bumped into Pyramid.

What are the differences between Pylons and Pyramid?

I read some text in PylonsBook, which currently covers Pylons 0.9.7, and wonder if it is a to start for Pylons and Pyramid.

答:
If you plan to start new project, migrate or just to learn framework I recommend to use Pyramid.

Pylons will stop it's development.
Meanwhile Pyramid is a continuation of Pylons. Thus, it's code is stable. It includes most features from Pylons, adds some new usefull features.

Title: Should I use Pylons or Pyramid?

ContentLicense: CC BY-SA 2.5


问:
enum combination, correct way - vb.net
I have a project in Vb.net and windows form application with dotnet framework 3.5. I am using Emum for storing and processing tasks As :

```<code>Public Enum TaskStatus
        none = 0
        completed = 2
        executing = 4
        executed = 8
        errors = 16      '' Means task got some error in performing some operations
        uploaded = 32
        incomplete = 64  '' Means Task Was Aborted or Process Stopped in between
End Enum
</code>```

One function is processing the task and the other one is Checking its completion status, as

```<code>Private Function Manage()
        Dim ts As TaskStatus = TaskStatus.none
        '' Performing Tasks
        ts = TaskStatus.executing
        '' Task Performed with Error
        ts = TaskStatus.errors Or TaskStatus.executed
        '' Task Uploading
        ts = ts Or TaskStatus.uploaded
        ts = ts Or TaskStatus.completed
        ts = TaskStatus.none
        CheckStatus(ts)
End Function

 Private Function CheckStatus(ByVal ts As TaskStatus)
    ' Now i Want to check
    If ts And (TaskStatus.uploaded Or TaskStatus.errors) Then
        '' Which one of these(Below) is Correct
    End If
    If ts = (TaskStatus.uploaded Or TaskStatus.errors) Then
        '' Which one of these(Above one) is Correct
    End If
    If ts And TaskStatus.incomplete Then
        '' Is it Correct way to check for incompletion
    End If
    If ts And TaskStatus.completed Then
        '' Task is Completed
        '' Is is correct way to check Task Completed
    End If
End Function
</code>```

In the Function CheckStatus, i want to know the correct way to manipulate with enum combinations?

答:
Here is a class that might help with some ideas.  Note the additional enum value all and the flags attribute on the Enum.

```<code>Public Class StatusTask
    <Flags> _
    Public Enum TaskStatus
        none = 0
        completed = 2
        executing = 4
        executed = 8
        errors = 16      '' Means task got some error in performing some operations
        uploaded = 32
        incomplete = 64  '' Means Task Was Aborted or Process Stopped in between
        all = -1
    End Enum

    Public ThisStatus As TaskStatus = TaskStatus.none

    Public Sub SetStatus(aStatus As TaskStatus)
        Me.ThisStatus = aStatus
    End Sub

    Public Sub AddStatus(aStatus As TaskStatus)
        Me.ThisStatus = Me.ThisStatus Or aStatus
    End Sub

    Public Sub ClearStatus(aStatus As TaskStatus)
        Me.ThisStatus = Me.ThisStatus And (aStatus Xor TaskStatus.all)
    End Sub

    Public Function HasStatus(aStatus As TaskStatus) As Boolean
        ''if HasFlag not found use
        ''Return (Me.ThisStatus And aStatus) = aStatus

        Return Me.ThisStatus.HasFlag(aStatus)
    End Function
End Class
</code>```

and some usage

```<code>    Dim foo As New StatusTask
    'set some status
    foo.SetStatus(StatusTask.TaskStatus.completed)
    foo.AddStatus(StatusTask.TaskStatus.executed)
    foo.AddStatus(StatusTask.TaskStatus.incomplete Or StatusTask.TaskStatus.uploaded)
    Debug.WriteLine(foo.ThisStatus)

    'do some checks
    'single
    If foo.HasStatus(StatusTask.TaskStatus.completed) Then
        Stop
    End If

    'multiple(both must be set)
    If foo.HasStatus(StatusTask.TaskStatus.completed) AndAlso foo.HasStatus(StatusTask.TaskStatus.incomplete) Then
        Stop
    End If
    'multiple(both must be set) alternative
    If foo.HasStatus(StatusTask.TaskStatus.completed Or StatusTask.TaskStatus.executed) Then
        Stop
    End If

    'multiple(either set)
    If foo.HasStatus(StatusTask.TaskStatus.errors) OrElse foo.HasStatus(StatusTask.TaskStatus.incomplete) Then
        Stop
    End If

    'clear status
    foo.ClearStatus(StatusTask.TaskStatus.errors) 'errors not set
    Debug.WriteLine(foo.ThisStatus)
    foo.ClearStatus(StatusTask.TaskStatus.completed Or StatusTask.TaskStatus.uploaded)
    Debug.WriteLine(foo.ThisStatus)
    foo.ClearStatus(StatusTask.TaskStatus.incomplete)
    Debug.WriteLine(foo.ThisStatus)
    foo.ClearStatus(StatusTask.TaskStatus.all)
    Debug.WriteLine(foo.ThisStatus)
</code>```

Title: enum combination, correct way - vb.net

Body:
I have a project in Vb.net and windows form application with dotnet framework 3.5. I am using Emum for storing and processing tasks As :

Public Enum TaskStatus
        none = 0
        completed = 2
        executing = 4
        executed = 8
        errors = 16      '' Means task got some error in performing some operations
        uploaded = 32
        incomplete = 64  '' Means Task Was Aborted or Process Stopped in between
End Enum

One function is processing the task and the other one is Checking its completion status, as

Private Function Manage()
        Dim ts As TaskStatus = TaskStatus.none
        '' Performing Tasks
        ts = TaskStatus.executing
        '' Task Performed with Error
        ts = TaskStatus.errors Or TaskStatus.executed
        '' Task Uploading
        ts = ts Or TaskStatus.uploaded
        ts = ts Or TaskStatus.completed
        ts = TaskStatus.none
        CheckStatus(ts)
End Function

 Private Function CheckStatus(ByVal ts As TaskStatus)
    ' Now i Want to check
    If ts And (TaskStatus.uploaded Or TaskStatus.errors) Then
        '' Which one of these(Below) is Correct
    End If
    If ts = (TaskStatus.uploaded Or TaskStatus.errors) Then
        '' Which one of these(Above one) is Correct
    End If
    If ts And TaskStatus.incomplete Then
        '' Is it Correct way to check for incompletion
    End If
    If ts And TaskStatus.completed Then
        '' Task is Completed
        '' Is is correct way to check Task Completed
    End If
End Function

In the Function CheckStatus, i want to know the correct way to manipulate with enum combinations?

Body:
Here is a class that might help with some ideas.  Note the additional enum value all and the flags attribute on the Enum.

Public Class StatusTask
    <Flags> _
    Public Enum TaskStatus
        none = 0
        completed = 2
        executing = 4
        executed = 8
        errors = 16      '' Means task got some error in performing some operations
        uploaded = 32
        incomplete = 64  '' Means Task Was Aborted or Process Stopped in between
        all = -1
    End Enum

    Public ThisStatus As TaskStatus = TaskStatus.none

    Public Sub SetStatus(aStatus As TaskStatus)
        Me.ThisStatus = aStatus
    End Sub

    Public Sub AddStatus(aStatus As TaskStatus)
        Me.ThisStatus = Me.ThisStatus Or aStatus
    End Sub

    Public Sub ClearStatus(aStatus As TaskStatus)
        Me.ThisStatus = Me.ThisStatus And (aStatus Xor TaskStatus.all)
    End Sub

    Public Function HasStatus(aStatus As TaskStatus) As Boolean
        ''if HasFlag not found use
        ''Return (Me.ThisStatus And aStatus) = aStatus

        Return Me.ThisStatus.HasFlag(aStatus)
    End Function
End Class

and some usage

    Dim foo As New StatusTask
    'set some status
    foo.SetStatus(StatusTask.TaskStatus.completed)
    foo.AddStatus(StatusTask.TaskStatus.executed)
    foo.AddStatus(StatusTask.TaskStatus.incomplete Or StatusTask.TaskStatus.uploaded)
    Debug.WriteLine(foo.ThisStatus)

    'do some checks
    'single
    If foo.HasStatus(StatusTask.TaskStatus.completed) Then
        Stop
    End If

    'multiple(both must be set)
    If foo.HasStatus(StatusTask.TaskStatus.completed) AndAlso foo.HasStatus(StatusTask.TaskStatus.incomplete) Then
        Stop
    End If
    'multiple(both must be set) alternative
    If foo.HasStatus(StatusTask.TaskStatus.completed Or StatusTask.TaskStatus.executed) Then
        Stop
    End If

    'multiple(either set)
    If foo.HasStatus(StatusTask.TaskStatus.errors) OrElse foo.HasStatus(StatusTask.TaskStatus.incomplete) Then
        Stop
    End If

    'clear status
    foo.ClearStatus(StatusTask.TaskStatus.errors) 'errors not set
    Debug.WriteLine(foo.ThisStatus)
    foo.ClearStatus(StatusTask.TaskStatus.completed Or StatusTask.TaskStatus.uploaded)
    Debug.WriteLine(foo.ThisStatus)
    foo.ClearStatus(StatusTask.TaskStatus.incomplete)
    Debug.WriteLine(foo.ThisStatus)
    foo.ClearStatus(StatusTask.TaskStatus.all)
    Debug.WriteLine(foo.ThisStatus)


问:
Mulesoft CXF Processing
I cannot seem to figure out how to continue to process the payload for a given SOAP Web Service.

I am sending an Outbound Message from Salesforce and attempting to consume it within Mulesoft. I can receive the message, and process it through CXF as JAX-WS Service.

I would like to do this CXF >> JAVA >> GET RELEVENT VALUE FROM PAYLOAD >> DO MORE STUFF.

This is the issue I am having, I can reference the values from within the Java class, but after that I am lost. Also the Java class implements a interface which returns a boolean based on the WSDL.

What can I do? Should I use a Proxy Service and just work off the XML String?

答:
Use Payload annotation in Java component to access the payload, but prior transformation is required.  please check

https://dzone.com/articles/mulesoft-payload-annotation-usage-in-java-componen

Title: Mulesoft CXF Processing


问:
Issue with CMake when using glib library
I am writing a bluez C program to read battery service. I am using CMake for building the code.
My Cmake File is :

```<code>    # CMakeLists file for module-bluez project

cmake_minimum_required(VERSION 3.02)

project (bluez-module)

find_package(PkgConfig REQUIRED)

# Adding dbus library

pkg_check_modules(DBUS REQUIRED dbus-1>= 1.6)
include_directories(${DBUS_INCLUDE_DIRS})
link_directories(${DBUS_LIBRARY_DIRS})

#Adding glib library
pkg_check_modules(GLIB REQUIRED glib-2.0>=2.23)
include_directories(${GLIB_INCLUDE_DIRS})
link_directories(${GLIB_LIBRARY_DIRS})

pkg_check_modules (DBUSGLIB REQUIRED dbus-glib-1)
include_directories(${DBUSGLIB_INCLUDE_DIRS})
link_directories(${DBUSGLIB_LIBRARY_DIRS})

# Adding bluetooth using extra libs
list(APPEND EXTRA_LIBS "bluetooth")

# Expose 'gattlib.h' to all sub-directories
include_directories(include)

add_executable(bluez-module scantest.c)

# Linking libraries

message(${DBUSGLIB_LIBRARIES})

target_link_libraries(bluez-module ${EXTRA_LIBS})
#target_link_libraries(bluez-module ${DBUS_LIBRARIES})
target_link_libraries(bluez-module ${DBUSGLIB_LIBRARIES})
target_link_libraries(bluez-module ${GLIB_LIBRARIES})
</code>```

I have to use g_main_loop in my code. But after building the source file I always get the below error :

```<code>[ 50%] Linking C executable bluez-module
CMakeFiles/bluez-module.dir/scantest.c.o: In function `read_battery_service':
scantest.c:(.text+0x5b8): undefined reference to `g_dbus_setup_bus'
collect2: error: ld returned 1 exit status
</code>```

My read_battery function code is as below :

```<code>int read_battery_service(struct hci_state *current_hci_state , char *dev_addr)
{
  GError *error = NULL;
  GDBusClient *client;
    GOptionContext *context;
context = g_option_context_new(NULL);
  main_loop = g_main_loop_new(NULL, FALSE);
  dbus_conn = g_dbus_setup_bus(DBUS_BUS_SYSTEM, NULL, NULL);

  return 0;
}
</code>```

Just trying to initialize for to access dbus apis.

I have included these headers in the code

```<code>#include <assert.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
#include <stdio.h>
#include <gdbus.h>
#include <glib/gmain.h>
</code>```

What would be the issue ? Is glib.h contains the function g_main_loop_new ? Where should I find it ? Or Is CMake not linking glib properly ?

答:
Looks like you are missing the gdbus linker flags. Try using
    pkg_check_modules (DBUSGLIB      REQUIRED dbus-glib-1) and add
    target_link_libraries(module-bluez ${DBUS_LIBRARIES} ${DBUSGLIB_LIBRARIES})
 and see if it helps.

Body:
I am writing a bluez C program to read battery service. I am using CMake for building the code.
My Cmake File is :

    # CMakeLists file for module-bluez project

cmake_minimum_required(VERSION 3.02)

project (bluez-module)

find_package(PkgConfig REQUIRED)

# Adding dbus library

pkg_check_modules(DBUS REQUIRED dbus-1>= 1.6)
include_directories(${DBUS_INCLUDE_DIRS})
link_directories(${DBUS_LIBRARY_DIRS})

#Adding glib library
pkg_check_modules(GLIB REQUIRED glib-2.0>=2.23)
include_directories(${GLIB_INCLUDE_DIRS})
link_directories(${GLIB_LIBRARY_DIRS})

pkg_check_modules (DBUSGLIB REQUIRED dbus-glib-1)
include_directories(${DBUSGLIB_INCLUDE_DIRS})
link_directories(${DBUSGLIB_LIBRARY_DIRS})

# Adding bluetooth using extra libs
list(APPEND EXTRA_LIBS "bluetooth")

# Expose 'gattlib.h' to all sub-directories
include_directories(include)

add_executable(bluez-module scantest.c)

# Linking libraries

message(${DBUSGLIB_LIBRARIES})

target_link_libraries(bluez-module ${EXTRA_LIBS})
#target_link_libraries(bluez-module ${DBUS_LIBRARIES})
target_link_libraries(bluez-module ${DBUSGLIB_LIBRARIES})
target_link_libraries(bluez-module ${GLIB_LIBRARIES})

I have to use g_main_loop in my code. But after building the source file I always get the below error :

[ 50%] Linking C executable bluez-module
CMakeFiles/bluez-module.dir/scantest.c.o: In function `read_battery_service':
scantest.c:(.text+0x5b8): undefined reference to `g_dbus_setup_bus'
collect2: error: ld returned 1 exit status

My read_battery function code is as below :

int read_battery_service(struct hci_state *current_hci_state , char *dev_addr)
{
  GError *error = NULL;
  GDBusClient *client;
    GOptionContext *context;
context = g_option_context_new(NULL);
  main_loop = g_main_loop_new(NULL, FALSE);
  dbus_conn = g_dbus_setup_bus(DBUS_BUS_SYSTEM, NULL, NULL);

  return 0;
}

Just trying to initialize for to access dbus apis.

I have included these headers in the code

#include <assert.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
#include <stdio.h>
#include <gdbus.h>
#include <glib/gmain.h>

What would be the issue ? Is glib.h contains the function g_main_loop_new ? Where should I find it ? Or Is CMake not linking glib properly ?


问:
Javascript dynamic input fields on a dynamic inputfield
I added a field for text input between the 2 Drop downs if Option number 3 is selected, the text box will appear.

This new text box should get numbers from the User and add new text fields under the Element for options.

For example: if the user adds the number 3 in the text box the radio button created, 3 new text boxes will show up under the Element row and look like this:

Option 1 _____________
Option 2 _____________
Option 3 _____________

// Funkcija za pravljenje Elemenata
var i = 0;
var a = 1;
function mojaFunkcija() {
    var type1 = document.getElementById('type1').value;
    var type2 = document.getElementById('type2').value;
    var question = document.getElementById('question').value;
    var counter = 'Element';
    counter+= a;
    var prviElement=document.createElement('span');
    prviElement.textContent= counter + ':' +'  ';
    document.body.appendChild(prviElement);
    var pitanje= document.createElement('span');
    var unos='unos';
    unos += i;
    pitanje.id=unos;
    pitanje.textContent=question + ' ';
    document.body.appendChild(pitanje);
    var tip1 = document.createElement("input");
    var element='element';
    element += i;
    tip1.id=element;
    if (type1=='textbox') {
        tip1.type=type2
    } else {
        tip1.type=type1
    }
    document.body.appendChild(tip1);
    var linija1= document.createElement("br");
    document.body.appendChild(linija1);
    var linija2= document.createElement("br");
    document.body.appendChild(linija2);
    i++;
    a++;
}

function AddTextBox(elm) {
    var v = elm.value;
    var iCounter = elm.id.replace('type1', '');

    if (v == 'radio') {
        var textbox = document.createElement('input');
        textbox.type = 'text';
        textbox.id = 'txtSecond' + iCounter;
        elm.parentNode.insertBefore(textbox, elm.nextSibling);
    } else {
        //Ovaj kod ce da izbrise Textbox u slucaju da se izabere druga opcija.
        var rmv = document.getElementById('txtSecond' + iCounter);
        if (rmv != undefined) {
            rmv.remove();
        }
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="pepo.css">
    <meta charset="UTF-8">
    <script src="basa.js"></script>
    <title>OnlineForms</title>
    </head>
<body>
    <!--Ovaj kod je za Main Page-->
    <Main class="kocka">
        <div align="left">
            <input type="button" class="dropbtn" value="Administration" onClick="window.location.reload();return false;"/>

            <button class="dropbtn" id="getAllButton">Forms</button>
        </div>
        <br>
        <div align="left">
            <input type="number" id="key" class="dropbtn"  Placeholder="Type the key value"/>
            <button class="dropbtn" id="getButton"> Search </button>
            <br>
            <br>
        </div>
    </Main>
    <!--Ovaj kod je za Elemente-->
    <div id="element" class="hide">
            <h1>Element <input type="text" class="dropbtn" id="question" value="" Placeholder="Type your question here"/>
            <select title="ddmenu" class="dropbtn" id="type1" onChange="AddTextBox(this)">
                <option selected disabled hidden value="Please select">Please select</option>
                <option value="textbox">textbox</option>
                <option value="checkbox">checkbox</option>
                <option value="radio">radio button</option>
                </select>
            <select title="ddmenu" class="dropbtn" id="type2">
                <option selected disabled hidden value="Please select">Please select</option>
                <option value="none">none</option>
                <option value="mandatory">mandatory</option>
                <option value="number">numeric</option>
            </select>
            </h1>
        <input type="button"  id="adddugme" class="dropbtn2" value="Add"  onclick="mojaFunkcija()"/>
        <br>
        <br>
        <button id="addButton" class='dropbtn'>Save</button>
        </div>
    <br>
    <br>
<div id="status"></div>
    <br>
<div id="status2"></div>
</body>
</html></code>```

答:
I think I understand what you're trying to achieve. It seems you're already able to reference the inputbox you want the value from because you're removing it in your AddTextBox function. In which case you can use similar code to loop depending on that value. Something like this:

```<code>var cnt = document.getElementById('txtSecond' + iCounter);
if (cnt != undefined && Number.isInteger(parseInt(cnt.value))) {
  // loop to create options
}
</code>```

Body:
I added a field for text input between the 2 Drop downs if Option number 3 is selected, the text box will appear.

This new text box should get numbers from the User and add new text fields under the Element for options.

For example: if the user adds the number 3 in the text box the radio button created, 3 new text boxes will show up under the Element row and look like this:

Option 1 _____________
Option 2 _____________
Option 3 _____________

// Funkcija za pravljenje Elemenata
var i = 0;
var a = 1;
function mojaFunkcija() {
    var type1 = document.getElementById('type1').value;
    var type2 = document.getElementById('type2').value;
    var question = document.getElementById('question').value;
    var counter = 'Element';
    counter+= a;
    var prviElement=document.createElement('span');
    prviElement.textContent= counter + ':' +'  ';
    document.body.appendChild(prviElement);
    var pitanje= document.createElement('span');
    var unos='unos';
    unos += i;
    pitanje.id=unos;
    pitanje.textContent=question + ' ';
    document.body.appendChild(pitanje);
    var tip1 = document.createElement("input");
    var element='element';
    element += i;
    tip1.id=element;
    if (type1=='textbox') {
        tip1.type=type2
    } else {
        tip1.type=type1
    }
    document.body.appendChild(tip1);
    var linija1= document.createElement("br");
    document.body.appendChild(linija1);
    var linija2= document.createElement("br");
    document.body.appendChild(linija2);
    i++;
    a++;
}

function AddTextBox(elm) {
    var v = elm.value;
    var iCounter = elm.id.replace('type1', '');

    if (v == 'radio') {
        var textbox = document.createElement('input');
        textbox.type = 'text';
        textbox.id = 'txtSecond' + iCounter;
        elm.parentNode.insertBefore(textbox, elm.nextSibling);
    } else {
        //Ovaj kod ce da izbrise Textbox u slucaju da se izabere druga opcija.
        var rmv = document.getElementById('txtSecond' + iCounter);
        if (rmv != undefined) {
            rmv.remove();
        }
    }
}

<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="pepo.css">
    <meta charset="UTF-8">

    <title>OnlineForms</title>

            <input type="button" class="dropbtn" value="Administration" onClick="window.location.reload();return false;"/>

            <button class="dropbtn" id="getAllButton">Forms</button>

            <input type="number" id="key" class="dropbtn"  Placeholder="Type the key value"/>
            <button class="dropbtn" id="getButton"> Search </button>

Element <input type="text" class="dropbtn" id="question" value="" Placeholder="Type your question here"/>
            <select title="ddmenu" class="dropbtn" id="type1" onChange="AddTextBox(this)">
                <option selected disabled hidden value="Please select">Please select</option>
                <option value="textbox">textbox</option>
                <option value="checkbox">checkbox</option>
                <option value="radio">radio button</option>
                </select>
            <select title="ddmenu" class="dropbtn" id="type2">
                <option selected disabled hidden value="Please select">Please select</option>
                <option value="none">none</option>
                <option value="mandatory">mandatory</option>
                <option value="number">numeric</option>
            </select>

        <input type="button"  id="adddugme" class="dropbtn2" value="Add"  onclick="mojaFunkcija()"/>

        <button id="addButton" class='dropbtn'>Save</button>

Body:
I think I understand what you're trying to achieve. It seems you're already able to reference the inputbox you want the value from because you're removing it in your AddTextBox function. In which case you can use similar code to loop depending on that value. Something like this:

var cnt = document.getElementById('txtSecond' + iCounter);
if (cnt != undefined && Number.isInteger(parseInt(cnt.value))) {
  // loop to create options
}


问:
in gradle build.gradle file - how can i check if a project exists?
Let's say in a build.gradle file I want to do something like:

ext.sharepointBuildDir = project(":MainProject:sharepoint").buildDir.path

But in certain configurations that project may not exist.

How can I check "does a gradle project exist"?

答:
You can use a findProject method, which is according to it's description

Locates a project by path. If the path is relative, it is interpreted relative to this project.

Returns: The project with the given path. Returns null if no such project exists.

So, you can simply use it as follows:

```<code>if (findProject(':MainProject:sharepoint') != null) {
    println 'project exists'
} else {
    println 'project does not exist'
}
</code>```

Body:
You can use a findProject method, which is according to it's description

Locates a project by path. If the path is relative, it is interpreted relative to this project.

Returns: The project with the given path. Returns null if no such project exists.

So, you can simply use it as follows:

if (findProject(':MainProject:sharepoint') != null) {
    println 'project exists'
} else {
    println 'project does not exist'
}


问:
Python - Flask - Google Charts API Get The Value in each CategoryFilter and pass it to the href
I have a table created using GoogleCharts API with multiple CategoryFilters, like below.

After filtering out the data, I would like to retrieve all the values in each filter.

The url of the current page is home/. So if I click on the NEXT button, I want to navigate to the next page, which is home/GT/ALL/ALL/ALL/ALL/.

Now I am confused how to retrieve the value in each filter and write them down in the href.

```<code><div class="btn-group">
    <button class="button" href="#">NEXT</button> <!--how to get the value from each filter and pass them on the href?-->
</div>
</code>```

Any suggestions will be much appreciated. Thanks.

UPDATED

I tried to simplify my problem. So I am in /home/ page. The page looks like below.

I choose a value from the filter, for example I chose A.

Then if I hit NEXT button, it will take me to the next page with the url /home/A.

The HTML looks like this.

```<code><html>
<head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">

      google.charts.load('current', {'packages':['table', 'controls']});

      google.charts.setOnLoadCallback(createTableWithFilter);

      function createTableWithFilter() {

        var data = google.visualization.arrayToDataTable([
                    ['Type', 'Value'],
                    ['A', 1],
                    ['A', 2],
                    ['B', 1],
                    ['B', 2]
                    ]);

        var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div'));

        var categoryFilter = new google.visualization.ControlWrapper({
             'controlType': 'CategoryFilter',
             'containerId': 'filter_div',
             'options': {
                 'filterColumnLabel': 'Type'
             }
        });

        var table = new google.visualization.ChartWrapper({
            'chartType': 'Table',
            'containerId': 'table_div',
        });

        dashboard.bind(categoryFilter, table);
        dashboard.draw(data);

      }

    </script>

    <style>
        .btn-group .button {
            background-color: #008CBA;
            color: white;
            padding: 7px 16px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 12px;
            cursor: pointer;
            float: left;
        }
        .btn-group .button:not(:last-child) {
            border-right: none; /* Prevent double borders */
        }
        .btn-group .button:hover {
            background-color: #195389;
        }

    </style>

</head>

<body>
    <!--Div that will hold the dashboard-->
    <div id="dashboard_div">
        <!--Divs that will hold each control and chart-->
        <div id="filter_div"></div>
        <div id="table_div"></div>
    </div>
    <div class="btn-group">
        <button class="button" href="#">NEXT PAGE</button>
    </div>
</body>
</html>
</code>```

And here is my Python code:

```<code>from flask import Flask, flash, redirect, render_template, request, session, abort
import os

tmpl_dir = 'templates'
app = Flask(__name__, template_folder=tmpl_dir)

@app.route("/")
def index():
    return render_template('example_get_value_from_categoryfilter.html')

if __name__ == "__main__":
    app.run()
</code>```

How to get the value A from the selected option in the CategoryFilter and pass it to the href in the button?

答:
each filter has a state property

use the getState() method to retrieve the selectedValues of the filter...

selectedValues will be an array of one or more selected values

```<code>categoryFilter.getState().selectedValues
</code>```

using jquery, you could update the href with something like...

```<code>if (categoryFilter.getState().selectedValues.length > 0) {
  $('.button').attr('href', categoryFilter.getState().selectedValues[0]);
}
</code>```

EDIT

you'll also need to use the 'statechange' event to know when a filter has occurred

see following working snippet...

google.charts.load('current', {
  callback: function () {
    createTableWithFilter();
    window.addEventListener('resize', createTableWithFilter, false);
  },
  packages: ['table', 'controls']
});

function createTableWithFilter() {
  var data = google.visualization.arrayToDataTable([
    ['Type', 'Value'],
    ['A', 1],
    ['A', 2],
    ['B', 1],
    ['B', 2]
  ]);

  var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div'));

  var categoryFilter = new google.visualization.ControlWrapper({
    'controlType': 'CategoryFilter',
    'containerId': 'filter_div',
    'options': {
      'filterColumnLabel': 'Type'
    }
  });

  google.visualization.events.addListener(categoryFilter, 'statechange', function () {
    var urlAddr = '/home';

    categoryFilter.getState().selectedValues.forEach(function (filterValue) {
      urlAddr += '/' + filterValue;
    });
    $('.button').attr('href', urlAddr);

    console.log($('.button').attr('href'));
  });

  var table = new google.visualization.ChartWrapper({
    'chartType': 'Table',
    'containerId': 'table_div',
  });

  dashboard.bind(categoryFilter, table);
  dashboard.draw(data);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="dashboard_div">
  <div id="filter_div"></div>
  <div id="chart_div"></div>
  <div id="table_div"></div>
</div>
<div class="btn-group">
  NEXT <!--how to get the value from each filter and pass them on the href?-->
</div></code>```

Body:
I have a table created using GoogleCharts API with multiple CategoryFilters, like below.

After filtering out the data, I would like to retrieve all the values in each filter.

The url of the current page is home/. So if I click on the NEXT button, I want to navigate to the next page, which is home/GT/ALL/ALL/ALL/ALL/.

Now I am confused how to retrieve the value in each filter and write them down in the href.

    <button class="button" href="#">NEXT</button>

Any suggestions will be much appreciated. Thanks.

UPDATED

I tried to simplify my problem. So I am in /home/ page. The page looks like below.

I choose a value from the filter, for example I chose A.

Then if I hit NEXT button, it will take me to the next page with the url /home/A.

The HTML looks like this.

        <button class="button" href="#">NEXT PAGE</button>

And here is my Python code:

from flask import Flask, flash, redirect, render_template, request, session, abort
import os

tmpl_dir = 'templates'
app = Flask(__name__, template_folder=tmpl_dir)

@app.route("/")
def index():
    return render_template('example_get_value_from_categoryfilter.html')

if __name__ == "__main__":
    app.run()

How to get the value A from the selected option in the CategoryFilter and pass it to the href in the button?

Body:
each filter has a state property

use the getState() method to retrieve the selectedValues of the filter...

selectedValues will be an array of one or more selected values

categoryFilter.getState().selectedValues

using jquery, you could update the href with something like...

if (categoryFilter.getState().selectedValues.length > 0) {
  $('.button').attr('href', categoryFilter.getState().selectedValues[0]);
}

EDIT

you'll also need to use the 'statechange' event to know when a filter has occurred

see following working snippet...

google.charts.load('current', {
  callback: function () {
    createTableWithFilter();
    window.addEventListener('resize', createTableWithFilter, false);
  },
  packages: ['table', 'controls']
});

function createTableWithFilter() {
  var data = google.visualization.arrayToDataTable([
    ['Type', 'Value'],
    ['A', 1],
    ['A', 2],
    ['B', 1],
    ['B', 2]
  ]);

  var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div'));

  var categoryFilter = new google.visualization.ControlWrapper({
    'controlType': 'CategoryFilter',
    'containerId': 'filter_div',
    'options': {
      'filterColumnLabel': 'Type'
    }
  });

  google.visualization.events.addListener(categoryFilter, 'statechange', function () {
    var urlAddr = '/home';

    categoryFilter.getState().selectedValues.forEach(function (filterValue) {
      urlAddr += '/' + filterValue;
    });
    $('.button').attr('href', urlAddr);

    console.log($('.button').attr('href'));
  });

  var table = new google.visualization.ChartWrapper({
    'chartType': 'Table',
    'containerId': 'table_div',
  });

  dashboard.bind(categoryFilter, table);
  dashboard.draw(data);
}

<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="dashboard_div">
  <div id="filter_div"></div>
  <div id="chart_div"></div>
  <div id="table_div"></div>
</div>
<div class="btn-group">
  <a class="button" href="#">NEXT</a> <!--how to get the value from each filter and pass them on the href?-->
</div>


问:
Mongoose populate a field without ObjectId?
I have a schema:

```<code>var Schema = mongoose.Schema;

var TicketSchema = new Schema({
externalId: String,
name: String,
items: [{
    externalId: String,
    price: Number,
    quantity: {
        type: Number,
        default: 1
    },
    comment: {
        type: String,
        default: '',
        trim: true
    },
    entity: {
        type: String,
        ref: 'Entity'
    }
}],
tableId: String
});

mongoose.model('Ticket', TicketSchema);
</code>```

And I want to populate entity field with an unique field other than ObjectId.
How can I achieve that?

答:
I'm not sure if I understood your question correctly.

In Mongoose model, in case we do not specify a primary key, it automatically adds in an extra field called ObjectId and assigns a unique value for each object.

In case we need to specify our own key, we can do it by specifying the key property.

For example:

```<code>mongoose.model('Todo', {
  todoID: {
    type: String,
    key: true
  },
  text: {
    type: 'text'
  },
  done: {
    type: Boolean,
    default: false,
  },
  date: {
    type: Date,
  },
  items: [{
    entity: {
      type: String,
      ref: 'Entity'
    }
  }]
});
</code>```

I hope, this is what you meant.

If you are asking about fetching objects based on Items -> entity's property,

```<code>Todo.find({'items.entity.type':required_type}, function(err, foundTodos){
      // ---
   });
</code>```

Thanks,

Body:
I have a schema:

var Schema = mongoose.Schema;

var TicketSchema = new Schema({
externalId: String,
name: String,
items: [{
    externalId: String,
    price: Number,
    quantity: {
        type: Number,
        default: 1
    },
    comment: {
        type: String,
        default: '',
        trim: true
    },
    entity: {
        type: String,
        ref: 'Entity'
    }
}],
tableId: String
});

mongoose.model('Ticket', TicketSchema);

And I want to populate entity field with an unique field other than ObjectId.
How can I achieve that?

Body:
I'm not sure if I understood your question correctly.

In Mongoose model, in case we do not specify a primary key, it automatically adds in an extra field called ObjectId and assigns a unique value for each object.

In case we need to specify our own key, we can do it by specifying the key property.

For example:

mongoose.model('Todo', {
  todoID: {
    type: String,
    key: true
  },
  text: {
    type: 'text'
  },
  done: {
    type: Boolean,
    default: false,
  },
  date: {
    type: Date,
  },
  items: [{
    entity: {
      type: String,
      ref: 'Entity'
    }
  }]
});

I hope, this is what you meant.

If you are asking about fetching objects based on Items -> entity's property,

Todo.find({'items.entity.type':required_type}, function(err, foundTodos){
      // ---
   });

Thanks,


问:
Download larger images in UNNotificationServiceExtension
I'm using the UNNotificationServiceExtension to create rich notifications on iOS 10 with an image attachment. Everything works fine with smaller images except when the image to download is a bit larger (e.g. 7MB).

In this case, the download starts but never finishes and the "best attempt" notification is displayed almost immediately after the download started.

According to Apple's docs, images can be up to 10MB so the size should not matter :)

I did implement the serviceExtensionTimeWillExpire where iOS is supposed to notify me that I have to deliver a content as soon as possible but this method is not called so I wonder what is happening.

Update 1
I also noticed that the same image works fine when it's stored locally. So it looks like the problem is in downloading the image. But, as said previously, the downloading is killed almost immediately.

The implementation is straight forward

```<code>- (BOOL)handleNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent *_Nonnull))contentHandler
{

    self.bestAttemptContent = (UNMutableNotificationContent *) [request.content mutableCopy];

    UNMutableNotificationContent *content = [self.bestAttemptContent mutableCopy];

    NSString *urlString = [content.userInfo valueForKeyPath:@"attachment-url"];

    NSLog(@"Downloading notification attachment completed with: %@", url.absoluteString);
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError *_Nullable error) {

        NSLog(@"Downloading notification attachment %@", error == nil ? @"success" : [NSString stringWithFormat:@"error: %@", error]);

        NSError *fileError;
        UNNotificationAttachment *attachment = [UNNotificationAttachment d360_createWithFileName:url.lastPathComponent identifier:url.absoluteString data:data options:nil error:&fileError];

        if (!attachment) {
            NSLog(@"Could not create local attachment file: %@", fileError);
            contentHandler(content);
            return;
        }

        NSLog(@"Adding attachment: %@", attachment);

        NSMutableArray *attachments = content.attachments ? [content.attachments mutableCopy] : [NSMutableArray array];

        [attachments addObject:attachment];

        content.attachments = attachments;
        contentHandler(content);

    }];
    [task resume];

    return YES;
}

- (void)serviceExtensionTimeWillExpire
{
    NSLog(@"Service extension expired. Using best attempt content  %@", self.bestAttemptContent);
    self.contentHandler(self.bestAttemptContent);
}
</code>```

When I debug this in XCode, I see the following logs:

```<code>2017-03-30 14:51:43.723669 D360TestAppNotificationExtension[3393:398992] [D360Extension]: Handling notification request content
2017-03-30 14:51:43.724103 D360TestAppNotificationExtension[3393:398992] [D360Extension]: Downloading notification attachment: https://upload.wikimedia.org/wikipedia/commons/b/b2/Bled_Castle_05.jpg
Program ended with exit code: 0
</code>```

The Program ended with exit code: 0 is suspicious. Any idea what is going on?

thanks
Jan

答:
So the solution is to use a NSURLSessionDownloadTask instead of a NSURLSessionDataTask. In this case, the download content is saved to a temporary location and uses less memory. The UNNotificationAttachment can be then created directly from the temporary file.

Just note that the UNNotificationAttachment needs to read a file with a supported file extension so I simply append the remote file name to the local temporary file URL

```<code>NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {

    NSLog(@"Downloading notification attachment completed with %@", error == nil ? @"success" : [NSString stringWithFormat:@"error: %@", error]);

    NSError *fileError;
    // create a local URL with extension
    NSURL *urlWithExtension = [NSURL fileURLWithPath:[location.path stringByAppendingString:url.lastPathComponent]];

    if (![[NSFileManager defaultManager] moveItemAtURL:location toURL:urlWithExtension error:&fileError]) {
        NSLog(@"Could not append  local attachment file name: %@", fileError);
        contentHandler(content);
        return;
    }

    UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:url.absoluteString
                                                                                URL:urlWithExtension options:nil
                                                                                error:&fileError];

    if (!attachment) {
        NSLog(@"Could not create local attachment file: %@", fileError);
        contentHandler(content);
        return;
    }

    NSLog(@"Adding attachment: %@", attachment);

    NSMutableArray *attachments = content.attachments ? [content.attachments mutableCopy] : [NSMutableArray array];

    [attachments addObject:attachment];

    content.attachments = attachments;

    contentHandler(content);

}];
[task resume];
</code>```

Body:
I'm using the UNNotificationServiceExtension to create rich notifications on iOS 10 with an image attachment. Everything works fine with smaller images except when the image to download is a bit larger (e.g. 7MB).

In this case, the download starts but never finishes and the "best attempt" notification is displayed almost immediately after the download started.

According to Apple's docs, images can be up to 10MB so the size should not matter :)

I did implement the serviceExtensionTimeWillExpire where iOS is supposed to notify me that I have to deliver a content as soon as possible but this method is not called so I wonder what is happening.

Update 1
I also noticed that the same image works fine when it's stored locally. So it looks like the problem is in downloading the image. But, as said previously, the downloading is killed almost immediately.

The implementation is straight forward

- (BOOL)handleNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent *_Nonnull))contentHandler
{

    self.bestAttemptContent = (UNMutableNotificationContent *) [request.content mutableCopy];

    UNMutableNotificationContent *content = [self.bestAttemptContent mutableCopy];

    NSString *urlString = [content.userInfo valueForKeyPath:@"attachment-url"];

    NSLog(@"Downloading notification attachment completed with: %@", url.absoluteString);
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError *_Nullable error) {

        NSLog(@"Downloading notification attachment %@", error == nil ? @"success" : [NSString stringWithFormat:@"error: %@", error]);

        NSError *fileError;
        UNNotificationAttachment *attachment = [UNNotificationAttachment d360_createWithFileName:url.lastPathComponent identifier:url.absoluteString data:data options:nil error:&fileError];

        if (!attachment) {
            NSLog(@"Could not create local attachment file: %@", fileError);
            contentHandler(content);
            return;
        }

        NSLog(@"Adding attachment: %@", attachment);

        NSMutableArray *attachments = content.attachments ? [content.attachments mutableCopy] : [NSMutableArray array];

        [attachments addObject:attachment];

        content.attachments = attachments;
        contentHandler(content);

    }];
    [task resume];

    return YES;
}

- (void)serviceExtensionTimeWillExpire
{
    NSLog(@"Service extension expired. Using best attempt content  %@", self.bestAttemptContent);
    self.contentHandler(self.bestAttemptContent);
}

When I debug this in XCode, I see the following logs:

2017-03-30 14:51:43.723669 D360TestAppNotificationExtension[3393:398992] [D360Extension]: Handling notification request content
2017-03-30 14:51:43.724103 D360TestAppNotificationExtension[3393:398992] [D360Extension]: Downloading notification attachment: https://upload.wikimedia.org/wikipedia/commons/b/b2/Bled_Castle_05.jpg
Program ended with exit code: 0

The Program ended with exit code: 0 is suspicious. Any idea what is going on?

thanks
Jan

Body:
So the solution is to use a NSURLSessionDownloadTask instead of a NSURLSessionDataTask. In this case, the download content is saved to a temporary location and uses less memory. The UNNotificationAttachment can be then created directly from the temporary file.

Just note that the UNNotificationAttachment needs to read a file with a supported file extension so I simply append the remote file name to the local temporary file URL

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {

    NSLog(@"Downloading notification attachment completed with %@", error == nil ? @"success" : [NSString stringWithFormat:@"error: %@", error]);

    NSError *fileError;
    // create a local URL with extension
    NSURL *urlWithExtension = [NSURL fileURLWithPath:[location.path stringByAppendingString:url.lastPathComponent]];

    if (![[NSFileManager defaultManager] moveItemAtURL:location toURL:urlWithExtension error:&fileError]) {
        NSLog(@"Could not append  local attachment file name: %@", fileError);
        contentHandler(content);
        return;
    }

    UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:url.absoluteString
                                                                                URL:urlWithExtension options:nil
                                                                                error:&fileError];

    if (!attachment) {
        NSLog(@"Could not create local attachment file: %@", fileError);
        contentHandler(content);
        return;
    }

    NSLog(@"Adding attachment: %@", attachment);

    NSMutableArray *attachments = content.attachments ? [content.attachments mutableCopy] : [NSMutableArray array];

    [attachments addObject:attachment];

    content.attachments = attachments;

    contentHandler(content);

}];
[task resume];


问:
On-premise AD sync with azure active directory using Azure connect DirSync
If we do on-premise AD sync with azure active directory using Azure connect DirSync and do not select password synchronization then

how the user will login in office 365?

what will be the credential for user?

答:
Users no need to change their credentials after they are synced to Azure AD. During the AAD sync, commonly we will choose to sync users' UPN and ObjectID to Azure AD like below, if Password Synchronization hasn't been enabled no users passwords will be synced to the Cloud.

After you completed creating the Relying Party Trust for Office365/AzureAD,  the default Issuance Transform Rules as below will send the security token which includes users' UPN to Office365/AzureAD during user login. If the UPN matches with the one previously synced to Azure AD, then the user will be allowed to login the portal using their UPNs defined in AD.


问:
SSIS Change datasource in connections
I'm new to SSIS and .net environment, I need to migrate one of the connection to new database server, I have tried by right click on connection and edit the details in dialog testing the connection results into successful notification popup message but when I click ok and review the connection it still the same as it was in the beginning.

I'm trying to change the server name but it never get change

答:
You are currently changing the result of an expression. That's why the original value is back every time you reopen your connection manager. Instead, you should change your parameters.

To find out what parameters your need to set, look into the code of your connection:

You'll find the parameters mentioned in there:

Then just go ahead and change those parameter values in your basic parameters window and you're good to go.

Title: SSIS Change datasource in connections


问:
Sort descending based on part of a title in Wordpress?
I'm having an issue how to sort a title in Wordpress. If I just know how I would solve this in MySQL it would be great. (If someone has an answer specific for wordpress that would be a lot easier for me though)

I have a database where the title (one field in the database-table) is called post_title. The title stores name AND year with a space between

eg.

```<code>Sweden 2017
Sweden 2016
Norway 2018
Norway 2019
</code>```

I want to sort above like this: (descending by year and ascending by name)

```<code>Norway 2019
Norway 2018
Sweden 2017
Sweden 2016
</code>```

UPDATE:
I've tried with Wordpress-builtin sorting with WP_Query:

```<code>$module_args = array(
                'posts_per_page' => -1,
                'post_type' => 'project',
                'include_children' => false,
                'orderby' => 'title',
                'order' => 'DESC',
                'no_found_rows' => true          //No pagination needed
            );

//Do the filtering and retrieve all projects with current service
$projects = get_posts( $module_args );
</code>```

but then I get this result:

```<code>Yacht 2011
Vasastan 2008
Ulrikagatan 2008
Thailand 2010 (?)
Strandvägen 2007
</code>```

but it should be:

```<code>Yacht 2011
Thailand 2010
Ulrikagatan 2008
Vasastan 2008
Strandvägen 2007
</code>```

答:
Please use the following code to get what exactly you need :</p>

```<code>$args = array(
    'orderby' => 'title',
    'order'   => 'DESC',
);
$query = new WP_Query( $args );
</code>```

Body:
I'm having an issue how to sort a title in Wordpress. If I just know how I would solve this in MySQL it would be great. (If someone has an answer specific for wordpress that would be a lot easier for me though)

I have a database where the title (one field in the database-table) is called post_title. The title stores name AND year with a space between

eg.

Sweden 2017
Sweden 2016
Norway 2018
Norway 2019

I want to sort above like this: (descending by year and ascending by name)

Norway 2019
Norway 2018
Sweden 2017
Sweden 2016

UPDATE:
I've tried with Wordpress-builtin sorting with WP_Query:

$module_args = array(
                'posts_per_page' => -1,
                'post_type' => 'project',
                'include_children' => false,
                'orderby' => 'title',
                'order' => 'DESC',
                'no_found_rows' => true          //No pagination needed
            );

//Do the filtering and retrieve all projects with current service
$projects = get_posts( $module_args );

but then I get this result:

Yacht 2011
Vasastan 2008
Ulrikagatan 2008
Thailand 2010 (?)
Strandvägen 2007

but it should be:

Yacht 2011
Thailand 2010
Ulrikagatan 2008
Vasastan 2008
Strandvägen 2007

Body:
Please use the following code to get what exactly you need :

$args = array(
    'orderby' => 'title',
    'order'   => 'DESC',
);
$query = new WP_Query( $args );


问:
C - How to extract different columns from one string?
I had a CSV file. I have managed to convert all the commas to spaces, and have put the entire thing in one massive string.
When I print out the string I get data like this:

DATA1 STUFF1 10 0.1 550 120 140 0.121

DATA2 STUFF2 20 0.1 250 250 200 0.022

DATA3 STUFF3 30 0.1 120 330 10 0.064

DATA4 STUFF4 40 0.1 920 380 10 0.193

etc

I'm currently having a problem in that when I scan the data into my stuct array that is meant to hold this data, it just produces the first line over and over again, ignoring the rest. So when I print it out, I just get

DATA1 STUFF1 10 0.1 550 120 140 0.121

DATA1 STUFF1 10 0.1 550 120 140 0.121

DATA1 STUFF1 10 0.1 550 120 140 0.121

DATA1 STUFF1 10 0.1 550 120 140 0.121

```<code>i=0;
while(i<MAX)
{
    sscanf(str, "%s %s %d %f %d %d %d %f", &datas[i].c1, &datas[i].c2,
    &datas[i].n1, &datas[i].n2, &datas[i].n3, &datas[i].n4,
    &datas[i].n5, &datas[i].n6);
    i++;
}
</code>```

MAX is the number of records in the CSV file, datas is my array of structures, str is the string that i have stored all the data without spaces and i is just an integer.

The actual structure:

```<code>struct data{
    char c1[10], c2[10];
    int n1, n3, n4, n5;
    float n2, n6;
};
struct data datas[MAX];
</code>```

Anyone got a solution? New to C so please explain like I'm 5.

答:
```<code>sscanf(str, "%s %s %d %f %d %d %d %f", &datas[i].c1, &datas[i].c2,
    &datas[i].n1, &datas[i].n2, &datas[i].n3, &datas[i].n4,
    &datas[i].n5, &datas[i].n6);
</code>```

As you said that str is a big string this is why the content of your structure members remains same.
Please modify your code if possible to use str as array of pointers and then use

```<code>sscanf(str[i], "%s %s %d %f %d %d %d %f", &datas[i].c1, &datas[i].c2,
    &datas[i].n1, &datas[i].n2, &datas[i].n3, &datas[i].n4,
    &datas[i].n5, &datas[i].n6);
</code>```

Please check how to declare and use array of pointers.

Body:
I had a CSV file. I have managed to convert all the commas to spaces, and have put the entire thing in one massive string.
When I print out the string I get data like this:

DATA1 STUFF1 10 0.1 550 120 140 0.121

DATA2 STUFF2 20 0.1 250 250 200 0.022

DATA3 STUFF3 30 0.1 120 330 10 0.064

DATA4 STUFF4 40 0.1 920 380 10 0.193

etc

I'm currently having a problem in that when I scan the data into my stuct array that is meant to hold this data, it just produces the first line over and over again, ignoring the rest. So when I print it out, I just get

DATA1 STUFF1 10 0.1 550 120 140 0.121

DATA1 STUFF1 10 0.1 550 120 140 0.121

DATA1 STUFF1 10 0.1 550 120 140 0.121

DATA1 STUFF1 10 0.1 550 120 140 0.121

i=0;
while(i<MAX)
{
    sscanf(str, "%s %s %d %f %d %d %d %f", &datas[i].c1, &datas[i].c2,
    &datas[i].n1, &datas[i].n2, &datas[i].n3, &datas[i].n4,
    &datas[i].n5, &datas[i].n6);
    i++;
}

MAX is the number of records in the CSV file, datas is my array of structures, str is the string that i have stored all the data without spaces and i is just an integer.

The actual structure:

struct data{
    char c1[10], c2[10];
    int n1, n3, n4, n5;
    float n2, n6;
};
struct data datas[MAX];

Anyone got a solution? New to C so please explain like I'm 5.

Body:
sscanf(str, "%s %s %d %f %d %d %d %f", &datas[i].c1, &datas[i].c2,
    &datas[i].n1, &datas[i].n2, &datas[i].n3, &datas[i].n4,
    &datas[i].n5, &datas[i].n6);

As you said that str is a big string this is why the content of your structure members remains same.
Please modify your code if possible to use str as array of pointers and then use

sscanf(str[i], "%s %s %d %f %d %d %d %f", &datas[i].c1, &datas[i].c2,
    &datas[i].n1, &datas[i].n2, &datas[i].n3, &datas[i].n4,
    &datas[i].n5, &datas[i].n6);

Please check how to declare and use array of pointers.


问:
Pandas: Restructure dataframe from column values
The pandas dataframe includes two columns 'A' and 'B'

```<code>A   B
1   a b
2   a c d
3   x
</code>```

Each value in column 'B' is a string containing a variable number of letters separated by spaces.

Is there a simple way to construct:

```<code>A   B
1   a
1   b
2   a
2   c
2   d
3   x
</code>```

答:
You can use the following:

```<code>splitted = df.set_index("A")["B"].str.split(expand=True)
stacked = splitted.stack().reset_index(1, drop=True)
result = stacked.to_frame("B").reset_index()

print(result)
    A   B
0   1   a
1   1   b
2   2   a
3   2   c
4   2   d
5   3   x
</code>```

For the sub steps, see below:

```<code>print(splitted)

   0     1     2
A
1  a     b  None
2  a     c     d
3  x  None  None

print(stacked)

A
1    a
1    b
2    a
2    c
2    d
3    x
dtype: object
</code>```

Or you may also use pd.melt:

```<code>splitted = df["B"].str.split(expand=True)

pd.melt(splitted.assign(A=df.A), id_vars="A", value_name="B")\
    .dropna()\
    .drop("variable", axis=1)\
    .sort_values("A")

    A   B
0   1   a
3   1   b
1   2   a
4   2   c
7   2   d
2   3   x
</code>```

Body:
The pandas dataframe includes two columns 'A' and 'B'

A   B
1   a b
2   a c d
3   x

Each value in column 'B' is a string containing a variable number of letters separated by spaces.

Is there a simple way to construct:

A   B
1   a
1   b
2   a
2   c
2   d
3   x

Body:
You can use the following:

splitted = df.set_index("A")["B"].str.split(expand=True)
stacked = splitted.stack().reset_index(1, drop=True)
result = stacked.to_frame("B").reset_index()

print(result)
    A   B
0   1   a
1   1   b
2   2   a
3   2   c
4   2   d
5   3   x

For the sub steps, see below:

print(splitted)

   0     1     2
A
1  a     b  None
2  a     c     d
3  x  None  None

print(stacked)

A
1    a
1    b
2    a
2    c
2    d
3    x
dtype: object

Or you may also use pd.melt:

splitted = df["B"].str.split(expand=True)

pd.melt(splitted.assign(A=df.A), id_vars="A", value_name="B")\
    .dropna()\
    .drop("variable", axis=1)\
    .sort_values("A")

    A   B
0   1   a
3   1   b
1   2   a
4   2   c
7   2   d
2   3   x


问:
Using two data-toggle for same element in bootstrap
I was messing around with Bootstrap and created a page which has a simple navigation menu. I wanted to add modal for one of the links, which already has a tooltip.

And I did add the modal to li like this,

```<code>data-toggle="modal" data-target="#SettingsModal" data-toggle="tooltip"
</code>```

Surprisingly, its working. It doesn't make much sense. Because at least one data-toggle has to be neglected.

I know that it is better to wrap it inside an element which has tooltip. My question is, how is this working?

答:
It's working because the Bootstrap data attributes use separate jQuery selectors to "activate" the various components.

Since
$('[data-toggle="modal"]') and $('[data-toggle="tooltip"]') are both referenced in the Bootstrap JS code, both modal and tooltip components are working.

Body:
I was messing around with Bootstrap and created a page which has a simple navigation menu. I wanted to add modal for one of the links, which already has a tooltip.

And I did add the modal to li like this,

data-toggle="modal" data-target="#SettingsModal" data-toggle="tooltip"

Surprisingly, its working. It doesn't make much sense. Because at least one data-toggle has to be neglected.

I know that it is better to wrap it inside an element which has tooltip. My question is, how is this working?


问:
How to add a new string to a *.po file w/ a PO editor
I MANUALLY created a file: test.po with the contents:

msgid "greeting"

  msgstr "Hello World"

Now I can edit the translation (hello world) in editors like "poedit" and "GTranslated" (I'm using Ubuntu). I can even add comments to that translation. However neither "poedit" and "GTranslated" will let me ADD a new translation string - I've looked online to no avail and looked at screenshots of other editors and none seem to have a "new" button.

What am I missing??? It seems stupid to have to edit new keys w/ a "plain" text editor and then edit them in these PO editors (whichever they may be). (If you can't tell I'm new to this 'gettext' world - I'm building a website in Zend/PHP.)

答:
open the .po file with any text editor, add these line or what ever the text need to added.

```<code>msgid "All Catalogues"
msgstr "Todos los catalogos"
</code>```

save and launch :-D

Body:
open the .po file with any text editor, add these line or what ever the text need to added.

msgid "All Catalogues"
msgstr "Todos los catalogos"

save and launch :-D


问:
Create template tags from the current function
I have formally constructed the function in my models.py file :

```<code>from datetime import datetime
from django.template.defaultfilters import date as datefilter
from django.utils import translation

def date_customerprofile(language):
    now_ = datetime.today()
    if language == 'English':
        translation.activate('en')
        return datefilter(now_, 'l, F j, Y')
    else:
        translation.activate('fr')
        return datefilter(now_, 'l, j F Y')
</code>```

I know Django's template language is NOT Python, so we can't write {{ customer.date_customerprofile('French') }}.

The solution here is to create a custom templatetag. Also note that translation.activate will change the active language for the remaining of the request/response cycle - using the translation.override context manager is certainly a better idea. As I am not an expert with templatetags, could anyone be able to show me how could I create it in taking into consideration the above function?

I think we could use the following question to do such thing How to format date in different languages?

Could I use context manager : Django switching, for a block of code, switch the language so translations are done in one language?

Thanks!

In fact, I would like to return in the template as output the current date in French 'Jeudi, 30 mars 2017' or the current date in English Thursday, March 30, 2017.

P.S. Please tell me if the question is unclear.

This is an example of Django's template :

```<code>{% load i18n %}
{% load date %}

{{ customer.civil_title }}{{ user.get_full_name }}
{{ customer.civic_number }}, {{ customer.street }}
{{ customer.rough_location }}

{# customer. date_customerprofile('English') #}

                           7 DAYS NOTICE

Subject:  Overdue account with ...
Client id : {{ customer.id }}

Hello {{ customer.civil_title }}{{ user.get_full_name }},

This notice serves to inform you that your payments with Gestion Multi Finance Inc. are pending. Your file has been transferred to our collection service. The balance of your loan is now:  {{ customer.current_balance }}.

We are asking you to communicate with us without delay, by phone at: 1-855-... ext. 324 or by email at: ... to find a payment solution in order to regulate your situation. If this does not happen, we will be forced to send you a notice of acceleration of the process and transfer your file to our judiciary collection service, with authority to take the necessary steps in the collection process. These steps can include the seizure of salary, but we prefer to avoid these measures.

 Also, it is important to remember that at the time of the loan, you signed a contract in which you agreed to respect the payments. Unfortunately, you have no respected this agreement.

 Ignore this notice if an agreement has already been reached.

Cordially,

{{ email.footer.txt }}
</code>```

答:
Now we've seen the total nonsense answer, here's the no-nonsense one:

In your yourapp/templatetags/yourapptags.py module:

```<code>from django import template
register = template.Library()

DATE_FORMATS = {
    "en":  "l, F j, Y",
    "fr": "l, j F Y"
}

DEFAULT_LANG = 'fr'

@register.simple_tag
def localdate(lang=DEFAULT_LANG):
    fmt = DATE_FORMATS.get(lang, DATE_FORMATS[DEFAULT_LANG])
    now = datetime.now()
    with translation.override(lang):
        return datefilter(now, fmt)
</code>```

Then in your template:

```<code>{% load "yourapptags" %}

<p>EN : {% localdate 'en' %}</p>
<p>FR : {% localdate 'fr' %}</p>
</code>```

Note that this is for forcing date formatting / localisation in a given locale whatever the current locale is which in this case seems quite weird to me.

If what you really want is just to display the current date formatted according to the current visitor's locale (cf https://docs.djangoproject.com/en/1.10/topics/i18n/translation/#how-django-discovers-language-preference), you can just get rid of the lang argument and use translation.get_language() instead:

```<code>@register.simple_tag
def localdate():
    lang = translation.get_language()
    fmt = DATE_FORMATS.get(lang, DATE_FORMATS[DEFAULT_LANG])
    now = datetime.now()
    return datefilter(now, fmt)
</code>```

Also note that l10n formats files provided by Django already have some date formats defined and that you can override them.

Body:
I have formally constructed the function in my models.py file :

from datetime import datetime
from django.template.defaultfilters import date as datefilter
from django.utils import translation

def date_customerprofile(language):
    now_ = datetime.today()
    if language == 'English':
        translation.activate('en')
        return datefilter(now_, 'l, F j, Y')
    else:
        translation.activate('fr')
        return datefilter(now_, 'l, j F Y')

I know Django's template language is NOT Python, so we can't write {{ customer.date_customerprofile('French') }}.

The solution here is to create a custom templatetag. Also note that translation.activate will change the active language for the remaining of the request/response cycle - using the translation.override context manager is certainly a better idea. As I am not an expert with templatetags, could anyone be able to show me how could I create it in taking into consideration the above function?

I think we could use the following question to do such thing How to format date in different languages?

Could I use context manager : Django switching, for a block of code, switch the language so translations are done in one language?

Thanks!

In fact, I would like to return in the template as output the current date in French 'Jeudi, 30 mars 2017' or the current date in English Thursday, March 30, 2017.

P.S. Please tell me if the question is unclear.

This is an example of Django's template :

{% load i18n %}
{% load date %}

{{ customer.civil_title }}{{ user.get_full_name }}
{{ customer.civic_number }}, {{ customer.street }}
{{ customer.rough_location }}

{# customer. date_customerprofile('English') #}

                           7 DAYS NOTICE

Subject:  Overdue account with ...
Client id : {{ customer.id }}

Hello {{ customer.civil_title }}{{ user.get_full_name }},

This notice serves to inform you that your payments with Gestion Multi Finance Inc. are pending. Your file has been transferred to our collection service. The balance of your loan is now:  {{ customer.current_balance }}.

We are asking you to communicate with us without delay, by phone at: 1-855-... ext. 324 or by email at: ... to find a payment solution in order to regulate your situation. If this does not happen, we will be forced to send you a notice of acceleration of the process and transfer your file to our judiciary collection service, with authority to take the necessary steps in the collection process. These steps can include the seizure of salary, but we prefer to avoid these measures.

 Also, it is important to remember that at the time of the loan, you signed a contract in which you agreed to respect the payments. Unfortunately, you have no respected this agreement.

 Ignore this notice if an agreement has already been reached.

Cordially,

{{ email.footer.txt }}

Body:
Now we've seen the total nonsense answer, here's the no-nonsense one:

In your yourapp/templatetags/yourapptags.py module:

from django import template
register = template.Library()

DATE_FORMATS = {
    "en":  "l, F j, Y",
    "fr": "l, j F Y"
}

DEFAULT_LANG = 'fr'

@register.simple_tag
def localdate(lang=DEFAULT_LANG):
    fmt = DATE_FORMATS.get(lang, DATE_FORMATS[DEFAULT_LANG])
    now = datetime.now()
    with translation.override(lang):
        return datefilter(now, fmt)

Then in your template:

{% load "yourapptags" %}

<p>EN : {% localdate 'en' %}</p>
<p>FR : {% localdate 'fr' %}</p>

Note that this is for forcing date formatting / localisation in a given locale whatever the current locale is which in this case seems quite weird to me.

If what you really want is just to display the current date formatted according to the current visitor's locale (cf https://docs.djangoproject.com/en/1.10/topics/i18n/translation/#how-django-discovers-language-preference), you can just get rid of the lang argument and use translation.get_language() instead:

@register.simple_tag
def localdate():
    lang = translation.get_language()
    fmt = DATE_FORMATS.get(lang, DATE_FORMATS[DEFAULT_LANG])
    now = datetime.now()
    return datefilter(now, fmt)

Also note that l10n formats files provided by Django already have some date formats defined and that you can override them.


问:
Redirect to different URL for different roles after login
I have created 2 different roles in WordPress: writer and copy-writer, with only "read" capability (so they can change their profile only)

Also, I have developed a plugin.

So after the user logs into the ADMIN panel, they are taken to the "profile" page, but I need them to be taken to my plugin page

Any ideas on how to achieve the above functionality?

Body: add_action('login_redirect','my_function');


问:
Iterator function for IDisposable items
Suppose I want to create an iterator function that yields IDisposable items.

```<code>IEnumerable<Disposable> GetItems()
{
    yield return new Disposable();
    yield return new Disposable();
}
</code>```

This does not seem ideal for the client code:

```<code>foreach (var item in source.GetItems())
{
    using (item)
    {
        // ...
    }
}
</code>```

Intuitively, the using comes too late. Things could get moved around. One could accidentally insert code between the foreach and the using. Not ideal.

I am looking for a better alternative!

One approach that comes to mind is creating the following API instead of an iterator function:

```<code>// Client
while (source.HasItem)
{
    using (var item = source.GetNextItem())
    {
        // ...
    }
}

// Source
private IEnumerator<Disposable> Enumerator { get; }
private bool? _hasItem;
bool HasItem
{
    get
    {
        if (this._hasItem == null) this._hasItem = this.Enumerator.MoveNext();
        return this._hasItem;
    }
}
Disposable GetNextItem()
{
    if (!this.HasItem) throw new IndexOutOfBoundsException();
    this._hasItem = null;
    return this.Enumerator.Current;
}
</code>```

But now it seems that the source has to become IDisposable! How else would it know when to dispose Enumerator? That can be an unpleasant side-effect.

I am looking for an alternative that feels solid in the client, but that keeps the source from becoming IDisposable too.

Edit - Clarification: I forgot to mention that some of the content that we need comes from an iterator. Concretely, imagine that we are returning IDbCommand instances, which are IDisposable. Before returning each command, we need to populate it with some query data, which in turn comes from a simple iterator method.

答:
We can expose only an IEnumerator<T>, which supports nothing but MoveNext() and Current.

Now, the underlying, private iterator function can be streaming, taking care of disposing the items. No invalid operations are introduced to the client - unless they try to store the borrowed objects and try to use them later, where it becomes clear that the objects are already disposed.

```<code>// Client
using (var itemEnumerator = source.GetItemEnumerator())
{
    while (itemEnumerator.MoveNext())
        var current = itemEnumerator.Current;
}

// Source
IEnumerator<Disposable> GetItemEnumerator() => this.StreamItems().GetEnumerator();
private IEnumerable<Disposable> StreamItems()
{
    while (this.ShouldCreateItem())
    {
        using (var item = this.CreateItem())
        {
            yield return item;
        }
    }
}
</code>```

Title: Iterator function for IDisposable items

Body:
Suppose I want to create an iterator function that yields IDisposable items.

IEnumerable<Disposable> GetItems()
{
    yield return new Disposable();
    yield return new Disposable();
}

This does not seem ideal for the client code:

foreach (var item in source.GetItems())
{
    using (item)
    {
        // ...
    }
}

Intuitively, the using comes too late. Things could get moved around. One could accidentally insert code between the foreach and the using. Not ideal.

I am looking for a better alternative!

One approach that comes to mind is creating the following API instead of an iterator function:

// Client
while (source.HasItem)
{
    using (var item = source.GetNextItem())
    {
        // ...
    }
}

// Source
private IEnumerator<Disposable> Enumerator { get; }
private bool? _hasItem;
bool HasItem
{
    get
    {
        if (this._hasItem == null) this._hasItem = this.Enumerator.MoveNext();
        return this._hasItem;
    }
}
Disposable GetNextItem()
{
    if (!this.HasItem) throw new IndexOutOfBoundsException();
    this._hasItem = null;
    return this.Enumerator.Current;
}

But now it seems that the source has to become IDisposable! How else would it know when to dispose Enumerator? That can be an unpleasant side-effect.

I am looking for an alternative that feels solid in the client, but that keeps the source from becoming IDisposable too.

Edit - Clarification: I forgot to mention that some of the content that we need comes from an iterator. Concretely, imagine that we are returning IDbCommand instances, which are IDisposable. Before returning each command, we need to populate it with some query data, which in turn comes from a simple iterator method.

Body:
We can expose only an IEnumerator<T>, which supports nothing but MoveNext() and Current.

Now, the underlying, private iterator function can be streaming, taking care of disposing the items. No invalid operations are introduced to the client - unless they try to store the borrowed objects and try to use them later, where it becomes clear that the objects are already disposed.

// Client
using (var itemEnumerator = source.GetItemEnumerator())
{
    while (itemEnumerator.MoveNext())
        var current = itemEnumerator.Current;
}

// Source
IEnumerator<Disposable> GetItemEnumerator() => this.StreamItems().GetEnumerator();
private IEnumerable<Disposable> StreamItems()
{
    while (this.ShouldCreateItem())
    {
        using (var item = this.CreateItem())
        {
            yield return item;
        }
    }
}


问:
div on click not fired during transition
I have a simple div with an onclick function (Note I removed the content of the svg for readability):

```<code><div id="sidebar-toggler">
  <svg></svg>
</div>

body.on('click', '#sidebar-toggler', function() {
  $('#sidebar').toggleClass('collapsed');
});
</code>```

this is working without a problem. But the div has also a transition to move a little to the right on hover:

```<code>&:hover
  left: 30px
  transition: left 0.4s ease-out
</code>```

Now, sometimes (quite often) during the transition, the click event is not fired. Is this a common Problem and is there a solution to this?
What I have tried is to make a wrapper div around it, which is as big as the animations goes. But the Problem still exist.

What I have done is to add a wrapper around my round div like this:

```<code>( ) = Round div (button)
_________
|       | = wrapper
_________

transition
From:
_________
|( )    |
_________
To:
_________
|    ( )|
_________
</code>```

And of course, I remapped the onclick to the wrapper. I though because the onclick is on the wrapper, and there is no transition on the wrapper, the onclick should be fired. But as said, no success so far.

答:
This is because click is very sensitive: you must click your mouse both down and up without the element moving.

You could use a mousedown or mouseup instead:

```<code>body.on('mouseup', '#sidebar-toggler', function() {
  $('#sidebar').toggleClass('collapsed');
});
</code>```

That wouldn't be dependent on movement.

The same would happen if you have a onClick method on a non-moving element, but you move your mouse. It wouldn't work since it's a drag instead of a click.

ContentLicense: CC BY-SA 4.0

Body:
I have a simple div with an onclick function (Note I removed the content of the svg for readability):

  <svg></svg>

body.on('click', '#sidebar-toggler', function() {
  $('#sidebar').toggleClass('collapsed');
});

this is working without a problem. But the div has also a transition to move a little to the right on hover:

&:hover
  left: 30px
  transition: left 0.4s ease-out

Now, sometimes (quite often) during the transition, the click event is not fired. Is this a common Problem and is there a solution to this?
What I have tried is to make a wrapper div around it, which is as big as the animations goes. But the Problem still exist.

What I have done is to add a wrapper around my round div like this:

( ) = Round div (button)
_________
|       | = wrapper
_________

transition
From:
_________
|( )    |
_________
To:
_________
|    ( )|
_________

And of course, I remapped the onclick to the wrapper. I though because the onclick is on the wrapper, and there is no transition on the wrapper, the onclick should be fired. But as said, no success so far.

Body:
This is because click is very sensitive: you must click your mouse both down and up without the element moving.

You could use a mousedown or mouseup instead:

body.on('mouseup', '#sidebar-toggler', function() {
  $('#sidebar').toggleClass('collapsed');
});

That wouldn't be dependent on movement.

The same would happen if you have a onClick method on a non-moving element, but you move your mouse. It wouldn't work since it's a drag instead of a click.


问:
Calculating shortest path from set node to all other nodes, with some nodes forbidden from path
I would like to implement the following in Python but not sure where to start. Are there good modules for shortest path problems of this type?

I am trying to define the shortest path from a particular atom (node) to all other atoms (nodes) in a given collection of xyz coordinates for a 3D chemical structure (the graph). The bonds between the atoms (nodes) are the edges for which travel from node to node is allowed.

I am trying to filter out certain atoms (nodes) from the molecule (graph) based on the connectivity outward from a selected central node.

**For the paths considered, I want to FORBID certain atoms (nodes) from being crossed. If the shortest path from A to B is through forbidden node, this answer is disallowed. The shortest path from A to B must not include the forbidden node **

If the shortest path from the selected centre atom (A) to another other node(B) INCLUDES the forbidden node, AND there is no other path available from A to B through the available edges (bonds), then node B should be deleted from the final set of xyz coordinates (nodes) to be saved.

This should be repeated for A to C, A to D, A to E, etc. for all other atoms (nodes) in the structure (graph).

Thanks in advance for any help you can offer.

答:
Make sure all edges that would lead to the forbidden node(s) have an infinite cost, and whichever graph-traversing algorithm you use will deal with it automatically.

Alternatively, just remove the forbidden nodes from being considered by the graph traversal algorithm.


问:
How to access uid using Cloud Functions for Firebase?
I wanted to access the uid of a user using javascript on the node environment and creating another reference to the accessed value "name" . My code and firebase data structure is as follows

```<code>exports.getData = functions.database.ref('/Followers/{uid}/{uid}/name')
    .onWrite(event => {

      //Getting the name data value

      const name = event.data.val();

      return admin.database().ref('/Accessed Name').set(name);
    });
</code>```

My Firebase sample data structure:

The accessed data "name" should create a reference such as the example below.

答:
To get the wildcard values from the matched path, you can use the event parameters:

```<code>exports.getData = functions.database.ref('/Followers/{uid1}/{uid2}/name')
    .onWrite(event => {

    const uid1 = event.params.uid1
    const uid2 = event.params.uid2

}
</code>```

Note that you have to give them different names in the path to get different values.  In your example, you gave them the same name.

See the documentation for database triggers for more information.

Body:
I wanted to access the uid of a user using javascript on the node environment and creating another reference to the accessed value "name" . My code and firebase data structure is as follows

exports.getData = functions.database.ref('/Followers/{uid}/{uid}/name')
    .onWrite(event => {

      //Getting the name data value

      const name = event.data.val();

      return admin.database().ref('/Accessed Name').set(name);
    });

My Firebase sample data structure:

The accessed data "name" should create a reference such as the example below.

Body:
To get the wildcard values from the matched path, you can use the event parameters:

exports.getData = functions.database.ref('/Followers/{uid1}/{uid2}/name')
    .onWrite(event => {

    const uid1 = event.params.uid1
    const uid2 = event.params.uid2

}

Note that you have to give them different names in the path to get different values.  In your example, you gave them the same name.

See the documentation for database triggers for more information.


问:
How to force int to string in Laravel JSON?
I've recently updated my server to a newer version of MySQL and PHP 7 for various reasons. On my previous instance, running PHP 5.5, Laravel's response()->json() always converted tinyint's into a string. Now running newer server software, it's returning me int's -as it should...

I'd have to change a lots of my codebase to either cast types / convert them into a string manually, whic I'm trying to avoid at the moment.

Is there a way to somehow force response()->json() to return int's as string's?

答:
You can typecast it to string:

return response->json(["data" => (string)1]);


问:
Why doesn't os/exec.CombinedOutput() have a race condition?
The Go bytes.Buffer isn't thread-safe. Yet, when I read the source code I notice that os/exec.CombinedOutput() uses the same buffer for both c.Stdout and c.Stderr. Further reading the implementation of the package it looks like there is no synchronisation when writing to the c.Stderr/c.Stdout here.

Am I missing something or have I found a possible synchronisation issue? AFAIK stderr and stdout can be written to concurrently by the child process.

答:
Stderr and Stdout are not written concurrently if they are the same writer as stated in the Cmd documentation:

If Stdout and Stderr are the same writer, at most one goroutine at a time will call Write.

This feature is implemented in the Cmd.stderr function. If Stdout and Stderr are the same, then the same fd is passed the child process stdout and stderr. In the case where the fd is a pipe with a goroutine to pump it, there's only one goroutine writing to Stdout/Stderr.


问:
Perform object recognition based on colour
I have captured each frame of a video .Then I have used background subtraction to eliminate the background .Now I have the people with their bounding boxes.I have to compare the colour features of this person with the features of the same person in another video. The person will be wearing the same dress in every video.
I am developing this in opencv 2.4 and python 2.7

Here it the background subtraction code I have used:

```<code>import numpy as np
import cv2
cap = cv2.VideoCapture('test.mp4')
fgbg = cv2.BackgroundSubtractorMOG()
j=0
count = int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT))
while j<count:
    ret, frame = cap.read()
    cmask = fgbg.apply(frame)
    fgmask = cmask.copy()
    floodfill =cmask.copy()

    (cnts, _) = cv2.findContours(cmask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cnts = sorted(cnts, key = cv2.contourArea, reverse = True)
    if(len(cnts)!=0):
        h, w = floodfill.shape[:2]
        mask = np.zeros((h+2, w+2), np.uint8)
        cv2.floodFill(floodfill, mask, (0,0), 255)
        floodfill_inv = cv2.bitwise_not(floodfill)
        fgmask=fgmask|floodfill_inv

    # screenCnt = None
    print "K="+str(j)
    j+=1
    for cnt in cnts:
        x,y,w,h = cv2.boundingRect(cnt)
        cv2.rectangle(fgmask,(x,y),(x+w,y+h),255,4)
    if(len(cnts)!=0):
        cv2.imshow('frame',fgmask)

    k = cv2.waitKey(30) & 0xff

    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()
</code>```

Is there any method for comparing objects based on the colour?

I have not used face recognition because I don't have pictures of the people in the video

Any help would be appreciated

答:
You could try to extract the 'average' color of an image, since the dress will have a large impact on the color shade of the entire image (since you extracted it, it makes up most of the image).

However, depending on lighting conditions and the way you extract the persons from the image, the values can change from time to time. It's therefore most likely not the most secure method, especially not when these persons have similar colors of clothing. But you could give it a try.

You can use the following code to extract the average color of an image (you can apply this to the extracted image you have):

```<code># Get the average color values of each row in an array
average_row_color = numpy.average(input_img, axis=0)
# Now get the average of that array to get the overall average image color
average_image_color = numpy.average(average_row_color, axis=0)
# Convert it to uint8 to get your 3 channel color values, like [100, 150, 200]
average_color_uint8 = numpy.uint8(average_image_color)
</code>```

You can then compare your results and see how close they are to colors you found in other videos and match the colors that are closest.

Body:
I have captured each frame of a video .Then I have used background subtraction to eliminate the background .Now I have the people with their bounding boxes.I have to compare the colour features of this person with the features of the same person in another video. The person will be wearing the same dress in every video.
I am developing this in opencv 2.4 and python 2.7

Here it the background subtraction code I have used:

import numpy as np
import cv2
cap = cv2.VideoCapture('test.mp4')
fgbg = cv2.BackgroundSubtractorMOG()
j=0
count = int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT))
while j<count:
    ret, frame = cap.read()
    cmask = fgbg.apply(frame)
    fgmask = cmask.copy()
    floodfill =cmask.copy()

    (cnts, _) = cv2.findContours(cmask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cnts = sorted(cnts, key = cv2.contourArea, reverse = True)
    if(len(cnts)!=0):
        h, w = floodfill.shape[:2]
        mask = np.zeros((h+2, w+2), np.uint8)
        cv2.floodFill(floodfill, mask, (0,0), 255)
        floodfill_inv = cv2.bitwise_not(floodfill)
        fgmask=fgmask|floodfill_inv

    # screenCnt = None
    print "K="+str(j)
    j+=1
    for cnt in cnts:
        x,y,w,h = cv2.boundingRect(cnt)
        cv2.rectangle(fgmask,(x,y),(x+w,y+h),255,4)
    if(len(cnts)!=0):
        cv2.imshow('frame',fgmask)

    k = cv2.waitKey(30) & 0xff

    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()

Is there any method for comparing objects based on the colour?

I have not used face recognition because I don't have pictures of the people in the video

Any help would be appreciated

Body:
You could try to extract the 'average' color of an image, since the dress will have a large impact on the color shade of the entire image (since you extracted it, it makes up most of the image).

However, depending on lighting conditions and the way you extract the persons from the image, the values can change from time to time. It's therefore most likely not the most secure method, especially not when these persons have similar colors of clothing. But you could give it a try.

You can use the following code to extract the average color of an image (you can apply this to the extracted image you have):

# Get the average color values of each row in an array
average_row_color = numpy.average(input_img, axis=0)
# Now get the average of that array to get the overall average image color
average_image_color = numpy.average(average_row_color, axis=0)
# Convert it to uint8 to get your 3 channel color values, like [100, 150, 200]
average_color_uint8 = numpy.uint8(average_image_color)

You can then compare your results and see how close they are to colors you found in other videos and match the colors that are closest.