问:
How to build subsections in an NSFetchedResultsController
I'm building an expense tracker where an Expense can belong to only one Category but can have multiple Tags. This is my object graph:

In the screen where I list all the expenses in a table view, I want the expenses to be grouped by date (the sectionDate), and then by Category (or, using a segmented control, by Tag). This is the intended UI:

I can already make an NSFetchedResultsController query all expenses, section them by date, then by category, but I can't get the (1) total for the category and (2) the list of expenses in it. How might I proceed to do that? This is my current code:

```<code>let fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult> = {
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Expense")
    fetchRequest.resultType = .dictionaryResultType

    fetchRequest.sortDescriptors = [
        NSSortDescriptor(key: #keyPath(Expense.sectionDate), ascending: false)
    ]

    fetchRequest.propertiesToFetch = [
        #keyPath(Expense.sectionDate),
        #keyPath(Expense.category)
    ]
    fetchRequest.propertiesToGroupBy = [
        #keyPath(Expense.sectionDate),
        #keyPath(Expense.category)
    ]

    let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,
                                                              managedObjectContext: Global.coreDataStack.viewContext,
                                                              sectionNameKeyPath: #keyPath(Expense.sectionDate),
                                                              cacheName: nil)
    return fetchedResultsController
}()
</code>```

答:
I appreciate @pbasdf's answer, but I feel that I'll have a hard time wrapping my head around the solution after a long time of not looking at the code.

What I've come around to doing is instead of fetching Expense objects, I defined a new entity for the subsections themselves (CategoryGroup, and I will also make a TagGroup) and fetch those entities instead. These entities have references to the Expense objects that they contain, and the Category or the Tag that represents the group. This is my (partially complete) data model:

And my NSFetchedResultsController is now far simpler in code:

```<code>let fetchedResultsController: NSFetchedResultsController<CategoryGroup> = {
    let fetchRequest = NSFetchRequest<CategoryGroup>(entityName: "CategoryGroup")
    fetchRequest.sortDescriptors = [
        NSSortDescriptor(key: #keyPath(CategoryGroup.sectionDate), ascending: false)
    ]
    return NSFetchedResultsController(fetchRequest: fetchRequest,
                                      managedObjectContext: Global.coreDataStack.viewContext,
                                      sectionNameKeyPath: #keyPath(CategoryGroup.sectionDate),
                                      cacheName: "CacheName")
}()
</code>```

The downside is that I now have to write extra code to make absolutely sure that the relationships among the entities are correctly defined whenever an Expense or a Category is created/updated/deleted, but that's an acceptable tradeoff for me as it is easier to comprehend in code.

Body:
I'm building an expense tracker where an Expense can belong to only one Category but can have multiple Tags. This is my object graph:

In the screen where I list all the expenses in a table view, I want the expenses to be grouped by date (the sectionDate), and then by Category (or, using a segmented control, by Tag). This is the intended UI:

I can already make an NSFetchedResultsController query all expenses, section them by date, then by category, but I can't get the (1) total for the category and (2) the list of expenses in it. How might I proceed to do that? This is my current code:

let fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult> = {
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Expense")
    fetchRequest.resultType = .dictionaryResultType

    fetchRequest.sortDescriptors = [
        NSSortDescriptor(key: #keyPath(Expense.sectionDate), ascending: false)
    ]

    fetchRequest.propertiesToFetch = [
        #keyPath(Expense.sectionDate),
        #keyPath(Expense.category)
    ]
    fetchRequest.propertiesToGroupBy = [
        #keyPath(Expense.sectionDate),
        #keyPath(Expense.category)
    ]

    let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,
                                                              managedObjectContext: Global.coreDataStack.viewContext,
                                                              sectionNameKeyPath: #keyPath(Expense.sectionDate),
                                                              cacheName: nil)
    return fetchedResultsController
}()

Body:
I appreciate @pbasdf's answer, but I feel that I'll have a hard time wrapping my head around the solution after a long time of not looking at the code.

What I've come around to doing is instead of fetching Expense objects, I defined a new entity for the subsections themselves (CategoryGroup, and I will also make a TagGroup) and fetch those entities instead. These entities have references to the Expense objects that they contain, and the Category or the Tag that represents the group. This is my (partially complete) data model:

And my NSFetchedResultsController is now far simpler in code:

let fetchedResultsController: NSFetchedResultsController<CategoryGroup> = {
    let fetchRequest = NSFetchRequest<CategoryGroup>(entityName: "CategoryGroup")
    fetchRequest.sortDescriptors = [
        NSSortDescriptor(key: #keyPath(CategoryGroup.sectionDate), ascending: false)
    ]
    return NSFetchedResultsController(fetchRequest: fetchRequest,
                                      managedObjectContext: Global.coreDataStack.viewContext,
                                      sectionNameKeyPath: #keyPath(CategoryGroup.sectionDate),
                                      cacheName: "CacheName")
}()

The downside is that I now have to write extra code to make absolutely sure that the relationships among the entities are correctly defined whenever an Expense or a Category is created/updated/deleted, but that's an acceptable tradeoff for me as it is easier to comprehend in code.


来源: stackexchange

问:
map.js is not working with highstock in 4.2.4 version ( mapNavigation )
I am trying to integrate mapNavigation future. MapNavigation is available on map.js.

I have seem some working example of map.js with highstock for mapNavigation.

```<code>mapNavigation = {
   enabled: true,
   enableButtons: false
}
</code>```

My problem on 4.2.4 only. Latest version is working fine

Getting following error.

Cannot read property 'documentElement' of undefined

http://jsfiddle.net/MohaideenIsmail/uvmfkcvu/ - Working example with latest version ( 5.0.2 )

http://jsfiddle.net/MohaideenIsmail/uvmfkcvu/1/ - Not working in 4.2.4 version

答:
For 4.2.4 version use all of script file of that version

Forked Fiddle

```<code><script src="https://code.highcharts.com/stock/4.2.4/highstock.js">
</script>
<script src="https://code.highcharts.com/maps/4.2.4/modules/map.js"></script>
<script src="https://code.highcharts.com/stock/4.2.4/modules/exporting.js"></script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to integrate mapNavigation future. MapNavigation is available on map.js.

I have seem some working example of map.js with highstock for mapNavigation.

mapNavigation = {
   enabled: true,
   enableButtons: false
}

My problem on 4.2.4 only. Latest version is working fine

Getting following error.

Cannot read property 'documentElement' of undefined

http://jsfiddle.net/MohaideenIsmail/uvmfkcvu/ - Working example with latest version ( 5.0.2 )

http://jsfiddle.net/MohaideenIsmail/uvmfkcvu/1/ - Not working in 4.2.4 version

Body:
For 4.2.4 version use all of script file of that version

Forked Fiddle

<script src="https://code.highcharts.com/stock/4.2.4/highstock.js">
</script>
<script src="https://code.highcharts.com/maps/4.2.4/modules/map.js"></script>
<script src="https://code.highcharts.com/stock/4.2.4/modules/exporting.js"></script>


问:
Map Reduce with F# agents
After playing with F# agents I tried to do a map reduce using them.

The basic structure I use is:

map supervisor which queues up all the work to do in its state and receives work request from map workers

reduce supervisor does the same thing as map supervisor for reduce work

a bunch of map and reduce workers that map and reduce, if one fails its work it sends it back to the respective supervisr to be reprocessed.

The questions I wonder about is:

does this make any sense compared to a more traditional (yet very nice) map reduce like (http://tomasp.net/blog/fsharp-parallel-aggregate.aspx) that uses PSeq ?

the way I implemented the map and reduce workers seems ugly is there a better way ?

it seems like I can create a 1000 000 map workers and 1000 0000 reduce workers lol, how should I choose these numbers, the more the better ?

Thanks a lot,

```<code>type Agent<'T> = MailboxProcessor<'T>

//This is the response the supervisor
//gives to the worker request for work
type 'work SupervisorResponse =
| Work of 'work //a piece of work
| NoWork//no work left to do

//This is the message to the supervisor
type 'work WorkMsg =
| ToDo of 'work //piles up work in the Supervisor queue
| WorkReq of   AsyncReplyChannel<SupervisorResponse<'work>> //'

//The supervisor agent can be interacted with
type AgentOperation =
| Stop //stop the agent
| Status //yield the current status of supervisor

type 'work SupervisorMsg =
| WorkRel of 'work WorkMsg
| Operation of AgentOperation

//Supervises Map and Reduce workers
module AgentSupervisor=
    let getNew (name:string) =
        new Agent<SupervisorMsg<'work>>(fun inbox -> //'
            let rec loop state  = async {
                let! msg = inbox.Receive()
                match msg with
                | WorkRel(m) ->
                    match m with
                    | ToDo(work) ->
                        let newState = work:state
                        return! loop newState
                    | WorkReq(replyChannel) ->
                        match state with
                        | [] ->
                            replyChannel.Reply(NoWork)
                            return! loop []
                        | [item] ->
                            replyChannel.Reply(Work(item))
                            return! loop []
                        | (item::remaining) ->
                            replyChannel.Reply(Work(item))
                            return! loop remaining
                | Operation(op) ->
                    match op with
                    | Status ->
                        Console.WriteLine(name+" current Work Queue "+
                                            string (state.Length))
                        return! loop state
                    | Stop ->
                        Console.WriteLine("Stoppped SuperVisor Agent "+name)
                        return()
            }
            loop [] )
    let stop (agent:Agent<SupervisorMsg<'work>>) = agent.Post(Operation(Stop))
    let status (agent:Agent<SupervisorMsg<'work>>) =agent.Post(Operation(Status))

//Code for the workers
type 'success WorkOutcome =
| Success of 'success
| Fail

type WorkerMsg =
| Start
| Stop
| Continue

module AgentWorker =
    type WorkerSupervisors<'reduce,'work> =
        { Map:Agent<SupervisorMsg<'work>> ; Reduce:Agent<SupervisorMsg<'reduce>> }

    let stop (agent:Agent<WorkerMsg>) = agent.Post(Stop)
    let start (agent:Agent<WorkerMsg>) = agent.Start()
                                         agent.Post(Start)

    let getNewMapWorker( map, supervisors:WorkerSupervisors<'reduce,'work>  ) =
        new Agent<WorkerMsg>(fun inbox ->
            let rec loop ()  = async {
                let! msg = inbox.Receive()
                match msg with
                | Start -> inbox.Post(Continue)
                           return! loop ()
                | Continue ->
                    let! supervisorOrder =
                    supervisors.Map.PostAndAsyncReply(
                        fun replyChannel ->
                            WorkRel(WorkReq(replyChannel)))
                    match supervisorOrder with
                    | Work(work) ->
                        let! res = map work
                        match res with
                        | Success(toReduce) ->
                            supervisors.Reduce
                                .Post(WorkRel(ToDo(toReduce)))
                        | Fail ->
                            Console.WriteLine("Map Fail")
                            supervisors.Map
                                .Post(WorkRel(ToDo(work)))
                            inbox.Post(Continue)
                   | NoWork ->
                            inbox.Post(Continue)
                            return! loop ()
                | Stop ->
                    Console.WriteLine("Map worker stopped")
                    return ()
                }
            loop ()  )

    let getNewReduceWorker(reduce,reduceSupervisor:Agent<SupervisorMsg<'work>>)=//'
        new Agent<WorkerMsg>(fun inbox ->
            let rec loop ()  = async {
                let! msg = inbox.Receive()
                match msg with
                | Start -> inbox.Post(Continue)
                           return! loop()
                | Continue ->
                    let! supervisorOrder =
                        reduceSupervisor.PostAndAsyncReply(fun replyChannel ->
                            WorkRel(WorkReq(replyChannel)))
                    match supervisorOrder with
                    | Work(work) ->
                        let! res = reduce work
                        match res with
                        | Success(toReduce) -> inbox.Post(Continue)
                        | Fail ->
                            Console.WriteLine("ReduceFail")
                            reduceSupervisor.Post(WorkRel(ToDo(work)))
                            inbox.Post(Continue)
                    | NoWork -> inbox.Post(Continue)
                    return! loop()
                |Stop ->Console.WriteLine("Reduce worker stopped"); return ()
                }
            loop() )

open AgentWorker

type MapReduce<'work,'reduce>( numberMap:int ,
                               numberReduce: int,
                               toProcess:'work list,
                               map:'work->Async<'reduce WorkOutcome>,
                               reduce:'reduce-> Async<unit WorkOutcome>) =

    let mapSupervisor= AgentSupervisor.getNew("MapSupervisor")
    let reduceSupervisor  = AgentSupervisor.getNew("ReduceSupervisor")

    let workerSupervisors = {Map = mapSupervisor ; Reduce = reduceSupervisor }

    let mapWorkers =
        [for i in 1..numberMap ->
            AgentWorker.getNewMapWorker(map,workerSupervisors) ]
    let reduceWorkers =
        [for i in 1..numberReduce ->
            AgentWorker.getNewReduceWorker(reduce,workerSupervisors.Reduce) ]

    member this.Start() =
        //Post work to do
        toProcess
        |>List.iter(fun elem -> mapSupervisor.Post( WorkRel(ToDo(elem))))
        //Start supervisors
        mapSupervisor.Start()
        reduceSupervisor.Start()
        //start workers
        List.iter( fun mapper -> mapper |>start) mapWorkers
        List.iter( fun reducer ->reducer|>start) reduceWorkers

    member this.Status() =  (mapSupervisor|>AgentSupervisor.status)
                            (reduceSupervisor|>AgentSupervisor.status)
    member this.Stop() =
        List.map2(fun mapper reducer ->
            mapper |>stop; reducer|>stop) mapWorkers reduceWorkers

//Run some tests
let map = function (n:int64) -> async{ return Success(n) }

let reduce = function (toto: int64) -> async{ return Success() }

let mp = MapReduce<int64,int64>( 1,1,[for i in 1L..1000000L->i],map,reduce)

mp.Start()
mp.Status()
mp.Stop()
</code>```

答:
I like to use MailboxProcessor for the reduce part of the algorithm, and async block that's invoked with Async.Parallel for the map part.  It makes things more explicit, giving you finer control over exception handling, timeouts, and cancellation.

The following code was designed with Brian's help, and with the help of his excellent F# block highlighting "F# Depth Colorizer" plug-in for VS2010.

This code is meant to pull RSS feeds from yahoo weather server in a map-reduce pattern.  It demonstrates how we can control execution flow from the outside of actual algorithm.

fetchWeather is the map part, and mailboxLoop is the reduce part of the algorithm.

```<code>#r "System.Xml.Linq.dll"

#r "FSharp.PowerPack.dll"

open System
open System.Diagnostics
open System.IO
open System.Linq
open System.Net
open System.Xml.Linq

open Microsoft.FSharp.Control.WebExtensions

type Weather (city, region, temperature) = class
   member x.City = city
   member x.Region = region
   member x.Temperature : int = temperature

   override this.ToString() =
      sprintf "%s, %s: %d F" this.City this.Region this.Temperature
end

type MessageForActor =
   | ProcessWeather of Weather
   | ProcessError of int
   | GetResults of (Weather * Weather * Weather list) AsyncReplyChannel

let parseRss woeid (rssStream : Stream) =
   let xn str = XName.Get str
   let yweather elementName = XName.Get(elementName, "http://xml.weather.yahoo.com/ns/rss/1.0")

   let channel = (XDocument.Load rssStream).Descendants(xn "channel").First()
   let location   = channel.Element(yweather "location")
   let condition  = channel.Element(xn "item").Element(yweather "condition")

   //  If the RSS server returns error, condition XML element won't be available.
   if not(condition = null) then
      let temperature = Int32.Parse(condition.Attribute(xn "temp").Value)
      ProcessWeather(new Weather(
                    location.Attribute(xn "city").Value,
                    location.Attribute(xn "region").Value,
                    temperature))
   else
      ProcessError(woeid)

let fetchWeather (actor : MessageForActor MailboxProcessor) woeid =
   async {
      let rssAddress = sprintf "http://weather.yahooapis.com/forecastrss?w=%d&u=f" woeid
      let webRequest =  WebRequest.Create rssAddress
      use! response = webRequest.AsyncGetResponse()
      use responseStream = response.GetResponseStream()
      let weather = parseRss woeid responseStream
      //do! Async.Sleep 1000 // enable this line to see amplified timing that proves concurrent flow
      actor.Post(weather)
   }

let mailboxLoop initialCount =
   let chooseCityByTemperature op (x : Weather) (y : Weather) =
      if op x.Temperature y.Temperature then x else y

   let sortWeatherByCityAndState (weatherList : Weather list) =
      weatherList
      |> List.sortWith (fun x y -> x.City.CompareTo(y.City))
      |> List.sortWith (fun x y -> x.Region.CompareTo(y.Region))

   MailboxProcessor.Start(fun inbox ->
      let rec loop minAcc maxAcc weatherList remaining =
         async {
            let! message = inbox.Receive()
            let remaining = remaining - 1

            match message with
            | ProcessWeather weather ->
               let colderCity = chooseCityByTemperature (<) minAcc weather
               let warmerCity = chooseCityByTemperature (>) maxAcc weather
               return! loop colderCity warmerCity (weather :: weatherList) remaining
            | ProcessError woeid ->
               let errorWeather = new Weather(sprintf "Error with woeid=%d" woeid, "ZZ", 99999)
               return! loop minAcc maxAcc (errorWeather :: weatherList) remaining
            | GetResults replyChannel ->
               replyChannel.Reply(minAcc, maxAcc, sortWeatherByCityAndState weatherList)
         }

      let minValueInitial = new Weather("", "", Int32.MaxValue)
      let maxValueInitial = new Weather("", "", Int32.MinValue)
      loop minValueInitial maxValueInitial [] initialCount
      )

let RunSynchronouslyWithExceptionAndTimeoutHandlers computation =
   let timeout = 30000
   try
      Async.RunSynchronously(Async.Catch(computation), timeout)
      |> function Choice1Of2 answer               -> answer |> ignore
                | Choice2Of2 (except : Exception) -> printfn "%s" except.Message; printfn "%s" except.StackTrace; exit -4
   with
   | :? System.TimeoutException -> printfn "Timed out waiting for results for %d seconds!" <| timeout / 1000; exit -5

let main =
   // Should have script name, sync/async select, and at least one woeid
   if fsi.CommandLineArgs.Length < 3 then
      printfn "Expecting at least two arguments!"
      printfn "There were %d arguments" (fsi.CommandLineArgs.Length - 1)
      exit -1

   let woeids =
      try
         fsi.CommandLineArgs
         |> Seq.skip 2 // skip the script name and sync/async select
         |> Seq.map Int32.Parse
         |> Seq.toList
      with
      | except -> printfn "One of supplied arguments was not an integer: %s" except.Message; exit -2

   let actor = mailboxLoop woeids.Length

   let processWeatherItemsConcurrently woeids =
      woeids
      |> Seq.map (fetchWeather actor)
      |> Async.Parallel
      |> RunSynchronouslyWithExceptionAndTimeoutHandlers

   let processOneWeatherItem woeid =
      woeid
      |> fetchWeather actor
      |> RunSynchronouslyWithExceptionAndTimeoutHandlers

   let stopWatch = new Stopwatch()
   stopWatch.Start()
   match fsi.CommandLineArgs.[1].ToUpper() with
   | "C" -> printfn "Concurrent execution:  "; processWeatherItemsConcurrently woeids
   | "S" -> printfn "Synchronous execution: "; woeids |> Seq.iter processOneWeatherItem
   | _   -> printfn "Unexpected run options!"; exit -3

   let (min, max, weatherList) = actor.PostAndReply GetResults
   stopWatch.Stop()
   assert (weatherList.Length = woeids.Length)

   printfn "{"
   weatherList |> List.iter (printfn "   %O")
   printfn "}"
   printfn "Coldest place: %O" min
   printfn "Hottest place: %O" max
   printfn "Completed in %d millisec" stopWatch.ElapsedMilliseconds

main
</code>```

ContentLicense: CC BY-SA 2.5

Title: Map Reduce with F# agents

Body:
After playing with F# agents I tried to do a map reduce using them.

The basic structure I use is:

map supervisor which queues up all the work to do in its state and receives work request from map workers

reduce supervisor does the same thing as map supervisor for reduce work

a bunch of map and reduce workers that map and reduce, if one fails its work it sends it back to the respective supervisr to be reprocessed.

The questions I wonder about is:

does this make any sense compared to a more traditional (yet very nice) map reduce like (http://tomasp.net/blog/fsharp-parallel-aggregate.aspx) that uses PSeq ?

the way I implemented the map and reduce workers seems ugly is there a better way ?

it seems like I can create a 1000 000 map workers and 1000 0000 reduce workers lol, how should I choose these numbers, the more the better ?

Thanks a lot,

type Agent<'T> = MailboxProcessor<'T>

//This is the response the supervisor
//gives to the worker request for work
type 'work SupervisorResponse =
| Work of 'work //a piece of work
| NoWork//no work left to do

//This is the message to the supervisor
type 'work WorkMsg =
| ToDo of 'work //piles up work in the Supervisor queue
| WorkReq of   AsyncReplyChannel<SupervisorResponse<'work>> //'

//The supervisor agent can be interacted with
type AgentOperation =
| Stop //stop the agent
| Status //yield the current status of supervisor

type 'work SupervisorMsg =
| WorkRel of 'work WorkMsg
| Operation of AgentOperation

//Supervises Map and Reduce workers
module AgentSupervisor=
    let getNew (name:string) =
        new Agent<SupervisorMsg<'work>>(fun inbox -> //'
            let rec loop state  = async {
                let! msg = inbox.Receive()
                match msg with
                | WorkRel(m) ->
                    match m with
                    | ToDo(work) ->
                        let newState = work:state
                        return! loop newState
                    | WorkReq(replyChannel) ->
                        match state with
                        | [] ->
                            replyChannel.Reply(NoWork)
                            return! loop []
                        | [item] ->
                            replyChannel.Reply(Work(item))
                            return! loop []
                        | (item::remaining) ->
                            replyChannel.Reply(Work(item))
                            return! loop remaining
                | Operation(op) ->
                    match op with
                    | Status ->
                        Console.WriteLine(name+" current Work Queue "+
                                            string (state.Length))
                        return! loop state
                    | Stop ->
                        Console.WriteLine("Stoppped SuperVisor Agent "+name)
                        return()
            }
            loop [] )
    let stop (agent:Agent<SupervisorMsg<'work>>) = agent.Post(Operation(Stop))
    let status (agent:Agent<SupervisorMsg<'work>>) =agent.Post(Operation(Status))

//Code for the workers
type 'success WorkOutcome =
| Success of 'success
| Fail

type WorkerMsg =
| Start
| Stop
| Continue

module AgentWorker =
    type WorkerSupervisors<'reduce,'work> =
        { Map:Agent<SupervisorMsg<'work>> ; Reduce:Agent<SupervisorMsg<'reduce>> }

    let stop (agent:Agent<WorkerMsg>) = agent.Post(Stop)
    let start (agent:Agent<WorkerMsg>) = agent.Start()
                                         agent.Post(Start)

    let getNewMapWorker( map, supervisors:WorkerSupervisors<'reduce,'work>  ) =
        new Agent<WorkerMsg>(fun inbox ->
            let rec loop ()  = async {
                let! msg = inbox.Receive()
                match msg with
                | Start -> inbox.Post(Continue)
                           return! loop ()
                | Continue ->
                    let! supervisorOrder =
                    supervisors.Map.PostAndAsyncReply(
                        fun replyChannel ->
                            WorkRel(WorkReq(replyChannel)))
                    match supervisorOrder with
                    | Work(work) ->
                        let! res = map work
                        match res with
                        | Success(toReduce) ->
                            supervisors.Reduce
                                .Post(WorkRel(ToDo(toReduce)))
                        | Fail ->
                            Console.WriteLine("Map Fail")
                            supervisors.Map
                                .Post(WorkRel(ToDo(work)))
                            inbox.Post(Continue)
                   | NoWork ->
                            inbox.Post(Continue)
                            return! loop ()
                | Stop ->
                    Console.WriteLine("Map worker stopped")
                    return ()
                }
            loop ()  )

    let getNewReduceWorker(reduce,reduceSupervisor:Agent<SupervisorMsg<'work>>)=//'
        new Agent<WorkerMsg>(fun inbox ->
            let rec loop ()  = async {
                let! msg = inbox.Receive()
                match msg with
                | Start -> inbox.Post(Continue)
                           return! loop()
                | Continue ->
                    let! supervisorOrder =
                        reduceSupervisor.PostAndAsyncReply(fun replyChannel ->
                            WorkRel(WorkReq(replyChannel)))
                    match supervisorOrder with
                    | Work(work) ->
                        let! res = reduce work
                        match res with
                        | Success(toReduce) -> inbox.Post(Continue)
                        | Fail ->
                            Console.WriteLine("ReduceFail")
                            reduceSupervisor.Post(WorkRel(ToDo(work)))
                            inbox.Post(Continue)
                    | NoWork -> inbox.Post(Continue)
                    return! loop()
                |Stop ->Console.WriteLine("Reduce worker stopped"); return ()
                }
            loop() )

open AgentWorker

type MapReduce<'work,'reduce>( numberMap:int ,
                               numberReduce: int,
                               toProcess:'work list,
                               map:'work->Async<'reduce WorkOutcome>,
                               reduce:'reduce-> Async<unit WorkOutcome>) =

    let mapSupervisor= AgentSupervisor.getNew("MapSupervisor")
    let reduceSupervisor  = AgentSupervisor.getNew("ReduceSupervisor")

    let workerSupervisors = {Map = mapSupervisor ; Reduce = reduceSupervisor }

    let mapWorkers =
        [for i in 1..numberMap ->
            AgentWorker.getNewMapWorker(map,workerSupervisors) ]
    let reduceWorkers =
        [for i in 1..numberReduce ->
            AgentWorker.getNewReduceWorker(reduce,workerSupervisors.Reduce) ]

    member this.Start() =
        //Post work to do
        toProcess
        |>List.iter(fun elem -> mapSupervisor.Post( WorkRel(ToDo(elem))))
        //Start supervisors
        mapSupervisor.Start()
        reduceSupervisor.Start()
        //start workers
        List.iter( fun mapper -> mapper |>start) mapWorkers
        List.iter( fun reducer ->reducer|>start) reduceWorkers

    member this.Status() =  (mapSupervisor|>AgentSupervisor.status)
                            (reduceSupervisor|>AgentSupervisor.status)
    member this.Stop() =
        List.map2(fun mapper reducer ->
            mapper |>stop; reducer|>stop) mapWorkers reduceWorkers

//Run some tests
let map = function (n:int64) -> async{ return Success(n) }

let reduce = function (toto: int64) -> async{ return Success() }

let mp = MapReduce<int64,int64>( 1,1,[for i in 1L..1000000L->i],map,reduce)

mp.Start()
mp.Status()
mp.Stop()

Body:
I like to use MailboxProcessor for the reduce part of the algorithm, and async block that's invoked with Async.Parallel for the map part.  It makes things more explicit, giving you finer control over exception handling, timeouts, and cancellation.

The following code was designed with Brian's help, and with the help of his excellent F# block highlighting "F# Depth Colorizer" plug-in for VS2010.

This code is meant to pull RSS feeds from yahoo weather server in a map-reduce pattern.  It demonstrates how we can control execution flow from the outside of actual algorithm.

fetchWeather is the map part, and mailboxLoop is the reduce part of the algorithm.

#r "System.Xml.Linq.dll"

#r "FSharp.PowerPack.dll"

open System
open System.Diagnostics
open System.IO
open System.Linq
open System.Net
open System.Xml.Linq

open Microsoft.FSharp.Control.WebExtensions

type Weather (city, region, temperature) = class
   member x.City = city
   member x.Region = region
   member x.Temperature : int = temperature

   override this.ToString() =
      sprintf "%s, %s: %d F" this.City this.Region this.Temperature
end

type MessageForActor =
   | ProcessWeather of Weather
   | ProcessError of int
   | GetResults of (Weather * Weather * Weather list) AsyncReplyChannel

let parseRss woeid (rssStream : Stream) =
   let xn str = XName.Get str
   let yweather elementName = XName.Get(elementName, "http://xml.weather.yahoo.com/ns/rss/1.0")

   let channel = (XDocument.Load rssStream).Descendants(xn "channel").First()
   let location   = channel.Element(yweather "location")
   let condition  = channel.Element(xn "item").Element(yweather "condition")

   //  If the RSS server returns error, condition XML element won't be available.
   if not(condition = null) then
      let temperature = Int32.Parse(condition.Attribute(xn "temp").Value)
      ProcessWeather(new Weather(
                    location.Attribute(xn "city").Value,
                    location.Attribute(xn "region").Value,
                    temperature))
   else
      ProcessError(woeid)

let fetchWeather (actor : MessageForActor MailboxProcessor) woeid =
   async {
      let rssAddress = sprintf "http://weather.yahooapis.com/forecastrss?w=%d&u=f" woeid
      let webRequest =  WebRequest.Create rssAddress
      use! response = webRequest.AsyncGetResponse()
      use responseStream = response.GetResponseStream()
      let weather = parseRss woeid responseStream
      //do! Async.Sleep 1000 // enable this line to see amplified timing that proves concurrent flow
      actor.Post(weather)
   }

let mailboxLoop initialCount =
   let chooseCityByTemperature op (x : Weather) (y : Weather) =
      if op x.Temperature y.Temperature then x else y

   let sortWeatherByCityAndState (weatherList : Weather list) =
      weatherList
      |> List.sortWith (fun x y -> x.City.CompareTo(y.City))
      |> List.sortWith (fun x y -> x.Region.CompareTo(y.Region))

   MailboxProcessor.Start(fun inbox ->
      let rec loop minAcc maxAcc weatherList remaining =
         async {
            let! message = inbox.Receive()
            let remaining = remaining - 1

            match message with
            | ProcessWeather weather ->
               let colderCity = chooseCityByTemperature (<) minAcc weather
               let warmerCity = chooseCityByTemperature (>) maxAcc weather
               return! loop colderCity warmerCity (weather :: weatherList) remaining
            | ProcessError woeid ->
               let errorWeather = new Weather(sprintf "Error with woeid=%d" woeid, "ZZ", 99999)
               return! loop minAcc maxAcc (errorWeather :: weatherList) remaining
            | GetResults replyChannel ->
               replyChannel.Reply(minAcc, maxAcc, sortWeatherByCityAndState weatherList)
         }

      let minValueInitial = new Weather("", "", Int32.MaxValue)
      let maxValueInitial = new Weather("", "", Int32.MinValue)
      loop minValueInitial maxValueInitial [] initialCount
      )

let RunSynchronouslyWithExceptionAndTimeoutHandlers computation =
   let timeout = 30000
   try
      Async.RunSynchronously(Async.Catch(computation), timeout)
      |> function Choice1Of2 answer               -> answer |> ignore
                | Choice2Of2 (except : Exception) -> printfn "%s" except.Message; printfn "%s" except.StackTrace; exit -4
   with
   | :? System.TimeoutException -> printfn "Timed out waiting for results for %d seconds!" <| timeout / 1000; exit -5

let main =
   // Should have script name, sync/async select, and at least one woeid
   if fsi.CommandLineArgs.Length < 3 then
      printfn "Expecting at least two arguments!"
      printfn "There were %d arguments" (fsi.CommandLineArgs.Length - 1)
      exit -1

   let woeids =
      try
         fsi.CommandLineArgs
         |> Seq.skip 2 // skip the script name and sync/async select
         |> Seq.map Int32.Parse
         |> Seq.toList
      with
      | except -> printfn "One of supplied arguments was not an integer: %s" except.Message; exit -2

   let actor = mailboxLoop woeids.Length

   let processWeatherItemsConcurrently woeids =
      woeids
      |> Seq.map (fetchWeather actor)
      |> Async.Parallel
      |> RunSynchronouslyWithExceptionAndTimeoutHandlers

   let processOneWeatherItem woeid =
      woeid
      |> fetchWeather actor
      |> RunSynchronouslyWithExceptionAndTimeoutHandlers

   let stopWatch = new Stopwatch()
   stopWatch.Start()
   match fsi.CommandLineArgs.[1].ToUpper() with
   | "C" -> printfn "Concurrent execution:  "; processWeatherItemsConcurrently woeids
   | "S" -> printfn "Synchronous execution: "; woeids |> Seq.iter processOneWeatherItem
   | _   -> printfn "Unexpected run options!"; exit -3

   let (min, max, weatherList) = actor.PostAndReply GetResults
   stopWatch.Stop()
   assert (weatherList.Length = woeids.Length)

   printfn "{"
   weatherList |> List.iter (printfn "   %O")
   printfn "}"
   printfn "Coldest place: %O" min
   printfn "Hottest place: %O" max
   printfn "Completed in %d millisec" stopWatch.ElapsedMilliseconds

main


问:
Why bash alias doesn't work in scripts?
I'm using a Mac and I have this alias defined in .bashrc:

```<code>$cat .bashrc | grep la
alias la='ls -la'
</code>```

then I try to use it in a script:

```<code>$cat ./mytest.sh
#!/bin/bash
la
</code>```

It runs and says it cannot find la:

```<code>./mytest.sh: line 2: la: command not found
</code>```

Why is this? I tried on both Mac and Linux, same error!

答:
At the beginning of the ~/.bashrc file usually can be found two lines as:

```<code># If not running interactively, don't do anything
[ -z "$PS1" ] && return
</code>```

This line aborts the inclusion for scripts which is not recommended anyway. For portability issues, you usually write the full command or define the alias in the script itself.

ContentLicense: CC BY-SA 4.0

Title: Why bash alias doesn't work in scripts?

Body:
I'm using a Mac and I have this alias defined in .bashrc:

$cat .bashrc | grep la
alias la='ls -la'

then I try to use it in a script:

$cat ./mytest.sh
#!/bin/bash
la

It runs and says it cannot find la:

./mytest.sh: line 2: la: command not found

Why is this? I tried on both Mac and Linux, same error!

Body:
At the beginning of the ~/.bashrc file usually can be found two lines as:

# If not running interactively, don't do anything
[ -z "$PS1" ] && return

This line aborts the inclusion for scripts which is not recommended anyway. For portability issues, you usually write the full command or define the alias in the script itself.


问:
Sorting of footable column of integers rendering unexpected results due to string sort
I am using footable.js plugin to sort a table in my MVC application. On clicking the row header for a column containing integers values they are being sorted as follows:

```<code>81, 811, 776, 700, 70
</code>```

Is there anything I can do to this library that would enable the sorting of integer columns to be sorted on value:

```<code>811,776,700,81, 70
</code>```

Any help would be greatly appreciated!

答: In newer releases, data-type="number" will do it.

Body:
I am using footable.js plugin to sort a table in my MVC application. On clicking the row header for a column containing integers values they are being sorted as follows:

81, 811, 776, 700, 70

Is there anything I can do to this library that would enable the sorting of integer columns to be sorted on value:

811,776,700,81, 70

Any help would be greatly appreciated!


问:
Missing likes/comments in LinkedIn API response
since 4 days my job which is fetching linkedIn updates is getting null responses for likes and comments (requests on specific updates : /updates/key={update-key}/likes and /updates/key={update-key}/update-comments endpoints). This is probably expected since when requesting on /updates/key={update-key}, the response does not have likes nor comments field.

My question is how can I get those values for specific updates (which I managed to get previously) since I can get them differently (maybe? read following)

Here's the strangest part : when I don't specify the update (request only on /updates endpoint), I get the following response : (modified a bit for readability/privacy)

{
  "_count": 10,
  "_start": 0,
  "_total": 212,
  "values": [
    {
      "isCommentable": false,
      "isLikable": false,
      "isLiked": false,
      "likes": {
        "_total": 3,
        "values": [...]
      },
      "numLikes": 7,
      "timestamp": ...,
      "updateComments": {"_total": 0},
      "updateContent": {...},
      "updateKey": ...
      "updateType": ...
    },{
      "isCommentable": false,
      "isLikable": false,
      "isLiked": false,
      "likes": {
        "_total": 3,
        "values": [...]
      },
      "numLikes": 9,
      "timestamp": ...,
      "updateComments": {"_total": 0},
      "updateContent": {...},
      "updateKey": "...",
      "updateType": "..."
    }, ....

So first, the updates have their fields isCommentable, isLikable and isLiked set to false, despite the fact that they have likes/comments.

Second, there is an inconsistency between the fields likes._total and numLikes (the latter one is the correct amount of likes)

Does anyone else encountered a similar problem? (well linkedin api update comment count null) Is it something expected or a change from LinkedIn side?
I already ask to LinkedIn help center which redirected me to StackOverflow.

Thanks for your time.

答:
Ok, I retried today :

{
  "isCommentable": true,
  "isLikable": true,
  "isLiked": false,
  "likes": {
    "_total": 9,
    "values": [
      { ...

So definitely an issues on linkedin side, fixed for now.


问:
how to start adb server?
hi im getting the error:

Unable to create Debug Bridge: Unable to start adb server: error: could not install smartsocket listener: cannot bind to 127.0.0.1:5037: An attempt was made to access a socket in a way forbidden by its access permissions. (10013)
  This application has requested the Runtime to terminate it in an unusual way.
  Please contact the application's support team for more information.
  could not read ok from ADB Server
  * failed to start daemon *
  error: cannot connect to daemon
  'C:\Users\user\AppData\Local\Android\Sdk\platform-tools\adb.exe start-server' failed -- run manually if necessary

How can I fix this issue? i have tried to uninstall the sdk platform tool and reinstall but that does not seem to work, any suggestions?

答:
I had the same issue, found the solution here:
stackoverflow - Android - could not install smartsocket listener

In summary, for windows:
Open command prompt and enter following command

```<code>netstat -ano | findstr :5037
</code>```

example output - final column is process id (PID)

```<code>TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 832
</code>```

in this example, 832 is PID

Now run command

```<code>tasklist | findstr _PID_ (e.g tasklist | findstr 832)
</code>```

It will show process/service name like bash.exe  (for me it was MBAM.exe)

go to task manager and end the task bash.exe and use following command to start adb

```<code>adb start-server
</code>```

Title: how to start adb server?

Body:
I had the same issue, found the solution here:
stackoverflow - Android - could not install smartsocket listener

In summary, for windows:
Open command prompt and enter following command

netstat -ano | findstr :5037

example output - final column is process id (PID)

TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 832

in this example, 832 is PID

Now run command

tasklist | findstr _PID_ (e.g tasklist | findstr 832)

It will show process/service name like bash.exe  (for me it was MBAM.exe)

go to task manager and end the task bash.exe and use following command to start adb

adb start-server


问:
Updated iphone application not live yet
3 weeks back we uploaded an application on the iTunes(V1.0). On Thursday we updated that application with new build (V1.2). I clicked the "Update" button on itunesconnect.apple.com and followed uploaded the new binary and new contents.

On the next day the Description and price tag are updated successfully, but the build version number and screens shots are still from the previous version. And the amazing thing we noticed is that application status is "Waiting for Review" from last 2 days... :(

I tried to play with release date, but still application status is "Waiting for Review".

Its been 2 days that there is no activity happening from apple... :(

Please help me in this scenario.....

Thanks in advance.

Regards,
Vishal.

答: Once new version of App is submitted for review all you can do is wait for Apple to approve it. From my own experience (5 Mobile App Releases so far) approval time is always different however usually takes between 3-7 days.</p>

Title: Updated iphone application not live yet


问:
Find the circle on the experimental image (Matlab)
I have a series of the experimental images. In order to process it, at first, I need to determine the area of interest. This area is between two concentric circles. These circles can be a little different on each image (e.g. center can be shifted by a small distance).

In order to find these circles, I converted my image to binary image. Now it looks like this:

I am interested in the biggest circle and the one after the biggest (See note on the picture). Does anyone know a fast algorithm that can find it? Exhausted search seems to be a bad option. I know, that at each image the locations and radii of these circles can change only by a little. Here is a link to .mat file with the picture I attached link.

Thanks,

答:
You can achieve this task even without using inbuilt function imfindcircles. I follow the following method. Get all the non-zero pixels using find. Now you have all the points, I want to classify them into different circles, for this I will use histogram. I can fix the number of bins (which is number of circles) here. Once I got all the points separated, I have scattered points along a circle..with these points, I will fit a circle along those points. You may check the below code:

```<code>load Sample.mat ;
I = Immm ;
[y,x] = find(I) ;
%% Get Bounding box
x0 = min(x) ; x1 = max(x) ;
y0 = min(y) ; y1 = max(y) ;
% length and breadth
L = abs(x1-x0) ;
B = abs(y1-y0) ;
% center bounding box
C = [x0+B/2 y0+L/2] ;
%% Get distances of the points from center of bounding box
data = repmat(C,[length(x),1])-[x,y] ;
dist = sqrt(data(:,1).^2+data(:,2).^2);
%% Classify the points into circles
nbins = 4 ;   % number of circles you want
[N,edges,bin] = histcounts(dist,nbins) ;
% plot the classified circle points for check
figure(1)
imshow(I)
hold on
for i = 1:nbins
    plot((x(bin==i)),y(bin==i),'.','color',rand(1,3)) ;
end

%% Circle's radii and center
Circ = cell(nbins,1) ;
for i = 1:nbins
    [xc1,yc1,R] = circfit(x(bin==i),y(bin==i)) ;
    Circ{i} = [xc1 yc1 R] ;
end
figure(2)
imshow(I)
hold on
th = linspace(0,2*pi) ;
for i = 1:nbins
    xc = Circ{i}(1)+Circ{i}(3)*cos(th) ;
    yc = Circ{i}(2)+Circ{i}(3)*sin(th) ;
    plot(xc,yc,'color',rand(1,3),'linewidth',3) ;
end
</code>```

Circ is cell, which centers and Radii of circles. You can download the function circfit from this link: http://matlab.wikia.com/wiki/FAQ#How_can_I_fit_a_circle_to_a_set_of_XY_data.3F

Body:
You can achieve this task even without using inbuilt function imfindcircles. I follow the following method. Get all the non-zero pixels using find. Now you have all the points, I want to classify them into different circles, for this I will use histogram. I can fix the number of bins (which is number of circles) here. Once I got all the points separated, I have scattered points along a circle..with these points, I will fit a circle along those points. You may check the below code:

load Sample.mat ;
I = Immm ;
[y,x] = find(I) ;
%% Get Bounding box
x0 = min(x) ; x1 = max(x) ;
y0 = min(y) ; y1 = max(y) ;
% length and breadth
L = abs(x1-x0) ;
B = abs(y1-y0) ;
% center bounding box
C = [x0+B/2 y0+L/2] ;
%% Get distances of the points from center of bounding box
data = repmat(C,[length(x),1])-[x,y] ;
dist = sqrt(data(:,1).^2+data(:,2).^2);
%% Classify the points into circles
nbins = 4 ;   % number of circles you want
[N,edges,bin] = histcounts(dist,nbins) ;
% plot the classified circle points for check
figure(1)
imshow(I)
hold on
for i = 1:nbins
    plot((x(bin==i)),y(bin==i),'.','color',rand(1,3)) ;
end

%% Circle's radii and center
Circ = cell(nbins,1) ;
for i = 1:nbins
    [xc1,yc1,R] = circfit(x(bin==i),y(bin==i)) ;
    Circ{i} = [xc1 yc1 R] ;
end
figure(2)
imshow(I)
hold on
th = linspace(0,2*pi) ;
for i = 1:nbins
    xc = Circ{i}(1)+Circ{i}(3)*cos(th) ;
    yc = Circ{i}(2)+Circ{i}(3)*sin(th) ;
    plot(xc,yc,'color',rand(1,3),'linewidth',3) ;
end

Circ is cell, which centers and Radii of circles. You can download the function circfit from this link: http://matlab.wikia.com/wiki/FAQ#How_can_I_fit_a_circle_to_a_set_of_XY_data.3F


问:
The final field cannot be assigned, for an interface
I have a class Product and an interface LargeProduct. Product implements LargeProduct.

LargeProduct has a variable height which has getter and setter methods which have to be implemented in the Product class.

The height variable in LargeProduct is defined like so:

```<code>public int height = null;
</code>```

The getter method works fine:

```<code>public int getHeight() {
    return height;
}
</code>```

But the setter method does not:

```<code>public void setHeight(int height) {
    this.height = height;
}
</code>```

Errors:

```<code>The final field LargeProduct.height cannot be assigned
The static field LargeProduct.height should be accessed in a static way
</code>```

I'm not sure which error it's actually giving.. I'm using Eclipse and when I hover it gives the first error, and at the bottom of the window it gives the second error.

答:
Interfaces can only include constants, not general-purpose variables. Interfaces should only contain constants if they're genuinely relevant to the rest of the interface, and they should use SHOUTY_CASE as per any other constant. It sounds like LargeProduct shouldn't have a constant called height - but instead, your implementation should declare the height field.

Note that interfaces are meant to be APIs, showing the abilities of types. Fields shouldn't be part of the API - they're an implementation detail. After all, who's to say that you'll write getHeight and setHeight based on a simple variable? Those methods could query a database, or delegate to an instance of some other type. The consumer of the interface shouldn't know or care about that.

For further information about fields in interfaces, I suggest you read section 9.3 of the Java Language Specification:

Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.

Body:
I have a class Product and an interface LargeProduct. Product implements LargeProduct.

LargeProduct has a variable height which has getter and setter methods which have to be implemented in the Product class.

The height variable in LargeProduct is defined like so:

public int height = null;

The getter method works fine:

public int getHeight() {
    return height;
}

But the setter method does not:

public void setHeight(int height) {
    this.height = height;
}

Errors:

The final field LargeProduct.height cannot be assigned
The static field LargeProduct.height should be accessed in a static way

I'm not sure which error it's actually giving.. I'm using Eclipse and when I hover it gives the first error, and at the bottom of the window it gives the second error.


问:
SQL server unit test on TFS build
We has a solution which is being built by TFS and SQL server unit tests which should be run on each build. The tests part also consists of a Database project which should be deployed to localDB before tests are running.
The config for SQL server unit test project is:

<configSections>

    </configSections>
  <connectionStrings>
    <add name="SnapDBContext" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SampleDatabase;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
  </connectionStrings>
    <SqlUnitTesting>
        <DatabaseDeployment DatabaseProjectFileName="..\..\..\..\Database\SampleDatabase.sqlproj" Configuration="Debug" />
        <DataGeneration ClearDatabase="true" />
        <ExecutionContext Provider="System.Data.SqlClient" ConnectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SampleDatabase;Integrated Security=True;Pooling=False" CommandTimeout="30" />
        <PrivilegedContext Provider="System.Data.SqlClient" ConnectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SampleDatabase;Integrated Security=True;Pooling=False" CommandTimeout="30" />
    </SqlUnitTesting>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>```

Everything work fine on my local machine but on TFS it fails with an error:

An error occurred while SQL Server unit testing settings were being read from the configuration file.  Click the test project, open the SQL Server Test Configuration dialog box from the SQL menu, add the settings to the dialog box, and rebuild the project.

The guys assumes that the tests worked fine on TFS 2013 but after the upgrading to TFS 2015 we started to get this error. Tried different solutions found here and over the internet but nothing helps. What am I missing?
Thank you.

答:
Try to use another SQL Server instance (not localdb, using another SQL Server instance works fine for me).

On the other hand, you are using windows authentication, so make sure the build service account has the enough permission (e.g. create database) for target SQL Server.

Title: SQL server unit test on TFS build

Body:
We has a solution which is being built by TFS and SQL server unit tests which should be run on each build. The tests part also consists of a Database project which should be deployed to localDB before tests are running.
The config for SQL server unit test project is:

<configSections>

    </configSections>
  <connectionStrings>
    <add name="SnapDBContext" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SampleDatabase;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
  </connectionStrings>
    <SqlUnitTesting>
        <DatabaseDeployment DatabaseProjectFileName="..\..\..\..\Database\SampleDatabase.sqlproj" Configuration="Debug" />
        <DataGeneration ClearDatabase="true" />
        <ExecutionContext Provider="System.Data.SqlClient" ConnectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SampleDatabase;Integrated Security=True;Pooling=False" CommandTimeout="30" />
        <PrivilegedContext Provider="System.Data.SqlClient" ConnectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SampleDatabase;Integrated Security=True;Pooling=False" CommandTimeout="30" />
    </SqlUnitTesting>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>

Everything work fine on my local machine but on TFS it fails with an error:

An error occurred while SQL Server unit testing settings were being read from the configuration file.  Click the test project, open the SQL Server Test Configuration dialog box from the SQL menu, add the settings to the dialog box, and rebuild the project.

The guys assumes that the tests worked fine on TFS 2013 but after the upgrading to TFS 2015 we started to get this error. Tried different solutions found here and over the internet but nothing helps. What am I missing?
Thank you.


问:
Delete a record from an Entity in core data
I'm working on a project in swift 3.0 where I have a core data module with an entity called "PlayListDetails". This holds two sub- elements names playlistName and trackID. So each playlist name has a trackID interline with it. My requirement is to delete a particular tuple when the indexPath.row is been passed. Though I have implemented a method once I execute the method it gives me an exception saying "fatal error: Index out of range". My methods are as bellow Where I save data and the method I use to delete data.

save

```<code> public static func savePlaylistDetails(audio:[(title:String,healerName:String,trackUrl:String, trackID:String, imageUrl: String)] = [], playListName: String) {

        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext
        let newPlaylist = NSEntityDescription.insertNewObject(forEntityName: PlayList_DETAILS_ENTITY, into: context)

        let track = audio.map{$0.trackID}
        print("Track",track)

        let trackId = track[0]

        print("ID is :",trackId)
        newPlaylist.setValue(playListName, forKey:"playlistName")
        newPlaylist.setValue(trackId, forKey:"trackID")

        do{
            try context.save();
            print("Saved.....")
        }
        catch{
            print("There was an error")
        }
    }
</code>```

Delete // this is where I get the exception, and I pass the selected rowIndex to the function

```<code>func deleteCoreData(rowIndex: Int) {
    let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    var playList = [PlayListDetails] ()
    managedContext.delete(playList[rowIndex]) // this is where the exception throws

    do {
         try managedContext.save()

    }catch{
        print("fail")
    }

}
</code>```

What am I missing ??

答:
If you are trying to delete item with specific index, i have provided solution for deleting item at index (this might cause array out of bound exception), but i recommend  to use predicate, lets say that may be id, name of item that you are willing to delete.

I am providing solution with perception from your question,
You can use process of fetching entity from DB and delete that particular item you want to remove.

Please manage to add following code, Do not forgot to use predicate if you want to delete some particular item

```<code> func deleteCoreData(rowIndex: Int) {

    let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    do{
        //1. Create Request
        let request: NSFetchRequest<PlayListDetails> = PlayListDetails.fetchRequest()

        //Predicate is optional as per need
        //let predicate = NSPredicate(format: "playlistId = %@", id)
        //request.predicate = predicate

        //2. Result object
        let results = try managedObjectcontext.fetch(request as! NSFetchRequest<NSFetchRequestResult>)

        guard results.count > 0 else {
            print("No tems available handle error")
            return
        }

        for i in 0...results.count-1 {

            if i == rowIndex {
                let theItem = results[index] as NSManagedObject
                managedObjectcontext.delete(item)
            }
        }
         /*
        for item in results as! [NSManagedObject]{
            print(item)
            //hit delete for item you want
            managedObjectcontext.delete(item)
        } */

        do {
            try managedObjectcontext.save() // <- remember to put this :)

        } catch {
            // Do something... fatalerror
            print("handle error")
            return
        }

    } catch{
        print(error)
        print("handle error")
        return

    }
    print("handle error")

}
</code>```

Update

"This is the query i wants to execute sir.. Delete all from PlayListDetails where trackId=123 and playlistName= demo How would I achieve this in above code"

Using predicate

```<code>//use predicate for single predicate and compound for multiple predicate
//Predicate is optional as per need
let predicate = NSPredicate(format: "trackId = %@", id)
let predicate2 = NSPredicate(format: "name = %@", "some name")

//let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, predicate2])

    request.predicate = predicate
</code>```

on delete section use

```<code>for item in results as! [NSManagedObject]{
                print(item)
                //hit delete for item you want
                managedObjectcontext.delete(item)
            }
</code>```

Body:
I'm working on a project in swift 3.0 where I have a core data module with an entity called "PlayListDetails". This holds two sub- elements names playlistName and trackID. So each playlist name has a trackID interline with it. My requirement is to delete a particular tuple when the indexPath.row is been passed. Though I have implemented a method once I execute the method it gives me an exception saying "fatal error: Index out of range". My methods are as bellow Where I save data and the method I use to delete data.

save

 public static func savePlaylistDetails(audio:[(title:String,healerName:String,trackUrl:String, trackID:String, imageUrl: String)] = [], playListName: String) {

        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext
        let newPlaylist = NSEntityDescription.insertNewObject(forEntityName: PlayList_DETAILS_ENTITY, into: context)

        let track = audio.map{$0.trackID}
        print("Track",track)

        let trackId = track[0]

        print("ID is :",trackId)
        newPlaylist.setValue(playListName, forKey:"playlistName")
        newPlaylist.setValue(trackId, forKey:"trackID")

        do{
            try context.save();
            print("Saved.....")
        }
        catch{
            print("There was an error")
        }
    }

Delete // this is where I get the exception, and I pass the selected rowIndex to the function

func deleteCoreData(rowIndex: Int) {
    let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    var playList = [PlayListDetails] ()
    managedContext.delete(playList[rowIndex]) // this is where the exception throws

    do {
         try managedContext.save()

    }catch{
        print("fail")
    }

}

What am I missing ??

Body:
If you are trying to delete item with specific index, i have provided solution for deleting item at index (this might cause array out of bound exception), but i recommend  to use predicate, lets say that may be id, name of item that you are willing to delete.

I am providing solution with perception from your question,
You can use process of fetching entity from DB and delete that particular item you want to remove.

Please manage to add following code, Do not forgot to use predicate if you want to delete some particular item

 func deleteCoreData(rowIndex: Int) {

    let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    do{
        //1. Create Request
        let request: NSFetchRequest<PlayListDetails> = PlayListDetails.fetchRequest()

        //Predicate is optional as per need
        //let predicate = NSPredicate(format: "playlistId = %@", id)
        //request.predicate = predicate

        //2. Result object
        let results = try managedObjectcontext.fetch(request as! NSFetchRequest<NSFetchRequestResult>)

        guard results.count > 0 else {
            print("No tems available handle error")
            return
        }

        for i in 0...results.count-1 {

            if i == rowIndex {
                let theItem = results[index] as NSManagedObject
                managedObjectcontext.delete(item)
            }
        }
         /*
        for item in results as! [NSManagedObject]{
            print(item)
            //hit delete for item you want
            managedObjectcontext.delete(item)
        } */

        do {
            try managedObjectcontext.save() // <- remember to put this :)

        } catch {
            // Do something... fatalerror
            print("handle error")
            return
        }

    } catch{
        print(error)
        print("handle error")
        return

    }
    print("handle error")

}

Update

"This is the query i wants to execute sir.. Delete all from PlayListDetails where trackId=123 and playlistName= demo How would I achieve this in above code"

Using predicate

//use predicate for single predicate and compound for multiple predicate
//Predicate is optional as per need
let predicate = NSPredicate(format: "trackId = %@", id)
let predicate2 = NSPredicate(format: "name = %@", "some name")

//let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, predicate2])

    request.predicate = predicate

on delete section use

for item in results as! [NSManagedObject]{
                print(item)
                //hit delete for item you want
                managedObjectcontext.delete(item)
            }


问:
Assign variable to group based on filter of one event using data.table
I need to create new columns based on if a user has completed an action at least once.

```<code> USER ACTION
 A    Attack
 A    Jump
 B    Attack
 B    Die
 C    Attack
 C    Die
 C    Jump
 D    Die
</code>```

Desired result would be something like:

```<code> ## If ACTION == something
 ## Create new column and apply '1' for that user for all rows

 USER ACTION HAS_DIED HAS_JUMPED HAS_ATTACKED
 A    Attack    0         1            1
 A    Jump      0         1            1
 B    Attack    1         0            1
 B    Die       1         0            1
 C    Attack    1         1            1
 C    Die       1         1            1
 C    Jump      1         1            1
 D    Die       1         0            0
</code>```

So I can end up with a unique USER list

```<code> USER  HAS_DIED HAS_JUMPED HAS_ATTACKED
 A       0         1            1
 B       1         0            1
 C       1         1            1
 D       1         0            0
</code>```

I've been using the method below of filtering and merging for each feature, but that's getting cumbersome with large amounts of features. Ex)

```<code> ## mark logs of deaths
 df[ACTION == "Die", HAS_DIED := 1]

 ## get unique list of users that have died
 died_df <- df[HAS_DIED == 1]

 ## merge and change none 1s to 0s
 merged_df <- died_df[df, on = "USER"]
 merged_df$HAS_DIED[is.na(merged_df$HAS_DIED)] <- 0
</code>```

Looking for a faster and more efficient way to do this!

答:
Using dplyr and tidyr:

```<code>df %>%
  mutate(n=1) %>%
  spread(ACTION, n, fill=0) %>%
  setNames(c('USER', 'HAS_ATTACKED', 'HAS_DIED', 'HAS_JUMPED'))

#   USER HAS_ATTACKED HAS_DIED HAS_JUMPED
# 1    A            1        0          1
# 2    B            1        1          0
# 3    C            1        1          1
# 4    D            0        1          0
</code>```

Body:
I need to create new columns based on if a user has completed an action at least once.

 USER ACTION
 A    Attack
 A    Jump
 B    Attack
 B    Die
 C    Attack
 C    Die
 C    Jump
 D    Die

Desired result would be something like:

 ## If ACTION == something
 ## Create new column and apply '1' for that user for all rows

 USER ACTION HAS_DIED HAS_JUMPED HAS_ATTACKED
 A    Attack    0         1            1
 A    Jump      0         1            1
 B    Attack    1         0            1
 B    Die       1         0            1
 C    Attack    1         1            1
 C    Die       1         1            1
 C    Jump      1         1            1
 D    Die       1         0            0

So I can end up with a unique USER list

 USER  HAS_DIED HAS_JUMPED HAS_ATTACKED
 A       0         1            1
 B       1         0            1
 C       1         1            1
 D       1         0            0

I've been using the method below of filtering and merging for each feature, but that's getting cumbersome with large amounts of features. Ex)

 ## mark logs of deaths
 df[ACTION == "Die", HAS_DIED := 1]

 ## get unique list of users that have died
 died_df <- df[HAS_DIED == 1]

 ## merge and change none 1s to 0s
 merged_df <- died_df[df, on = "USER"]
 merged_df$HAS_DIED[is.na(merged_df$HAS_DIED)] <- 0

Looking for a faster and more efficient way to do this!

Body:
Using dplyr and tidyr:

df %>%
  mutate(n=1) %>%
  spread(ACTION, n, fill=0) %>%
  setNames(c('USER', 'HAS_ATTACKED', 'HAS_DIED', 'HAS_JUMPED'))

#   USER HAS_ATTACKED HAS_DIED HAS_JUMPED
# 1    A            1        0          1
# 2    B            1        1          0
# 3    C            1        1          1
# 4    D            0        1          0


问:
Android Listview select first ten item
In my listview I have a checkbox and when I select the checkbox first 10 rows need to be selected, I did the code like this .. but it is selecting the rest of all rows except the first 10 rows..can anyone help me..what change I need to do here.</p>

```<code>if (checked)
                  {
                     // Toast.makeText(MyList.this, "Checked.", Toast.LENGTH_LONG).show();
                      //for(int i=0; i<lv.getChildCount();i++)
                      for(int i=0; i<lv.getAdapter().getCount();i++)
                      {

                          int m = 1;
                          final int firstListItemPosition = lv.getFirstVisiblePosition();

                          //final int firstListItemPosition = (int) lv.getItemAtPosition(m);
                          final int lastListItemPosition = firstListItemPosition + 9;

                          if (i < firstListItemPosition || i > lastListItemPosition ) {
                              View vii = lv.getAdapter().getView(i, null, lv);
                              //return listView.getAdapter().getView(pos, null, listView);
                              CheckBox cb = (CheckBox)vii.findViewById(R.id.selected);
                              cb.setChecked(true);

                          } else {
                              final int childIndex = i - firstListItemPosition;

                              CheckBox cb = (CheckBox)lv.getChildAt(childIndex).findViewById(R.id.selected);
                              cb.setChecked(true);
                          }
                          //Toast.makeText(MyList.this,s, Toast.LENGTH_LONG).show();

                      }
</code>```

答:
Your if condition is wrong  if (i < firstListItemPosition || i > lastListItemPosition )

change it to

if (i > firstListItemPosition && i < lastListItemPosition )

Title: Android Listview select first ten item

Body:
In my listview I have a checkbox and when I select the checkbox first 10 rows need to be selected, I did the code like this .. but it is selecting the rest of all rows except the first 10 rows..can anyone help me..what change I need to do here.

if (checked)
                  {
                     // Toast.makeText(MyList.this, "Checked.", Toast.LENGTH_LONG).show();
                      //for(int i=0; i<lv.getChildCount();i++)
                      for(int i=0; i<lv.getAdapter().getCount();i++)
                      {

                          int m = 1;
                          final int firstListItemPosition = lv.getFirstVisiblePosition();

                          //final int firstListItemPosition = (int) lv.getItemAtPosition(m);
                          final int lastListItemPosition = firstListItemPosition + 9;

                          if (i < firstListItemPosition || i > lastListItemPosition ) {
                              View vii = lv.getAdapter().getView(i, null, lv);
                              //return listView.getAdapter().getView(pos, null, listView);
                              CheckBox cb = (CheckBox)vii.findViewById(R.id.selected);
                              cb.setChecked(true);

                          } else {
                              final int childIndex = i - firstListItemPosition;

                              CheckBox cb = (CheckBox)lv.getChildAt(childIndex).findViewById(R.id.selected);
                              cb.setChecked(true);
                          }
                          //Toast.makeText(MyList.this,s, Toast.LENGTH_LONG).show();

                      }


问:
Why phpMyAdmin is not importing my table?
I'm a designer, but as there's no programmer in my company I have to start studing programming. Which I did only somedays ago (and I have only  a html and css knowledge background) so pleasepleaseplease don't take any knowledge for granted if you can answer me!

I'm studing PHP and MySQL using "PHP & MySQL in easy steps" by Mike McGranth (if any of you have it I'm at page 90/91). So, the task is simple: write a .sql file and create a table in phpMyAdmin with it.

Since it's an exercise from a book I just have to write as it's written on the page and test it; yes, I have the solution-file too, but the point is I can't see the difference between my code, which can't be processed by phpMyAdmin, and the solution-code, which gives no problem.

The .sql file written by me is this:

```<code>CREATE TABLE IF NOT EXISTS products
(
id INT UNIQUE AUTO_INCREMENT ,
code INT NOT_NULL ,
name VARCHAR(25) NOT NULL ,
quantity INT DEFAULT 1 NULL ,
price DECIMAL(6,2) NOT NULL
) ;
</code>```

And the solution-file code is this:

```<code>CREATE TABLE IF NOT EXISTS products
(
  id        INT UNIQUE  AUTO_INCREMENT ,
  code      INT     NOT NULL ,
  name      VARCHAR(25)     NOT NULL ,
  quantity  INT     DEFAULT 1 NULL ,
  price     DECIMAL(6,2)    NOT NULL
) ;
</code>```

This is also how the look like in a code-editor program:

This is the error that phpMyAdmin gives to me (if the japanese part is important I can add the translation):

Since I have a solution, why do I ask? Because maybe I've done just a small mistake, but if I don't understand it I'm afraid to do it again when handling bigger files, maybe a client db, real work, not just an exercise.
So, if anyone will be so kind to explain it to me he/she will have my ethernal gratitude!

答:
In your code there is

```<code>code INT NOT_NULL
</code>```

That underscore is wrong .

If you take a look at other lines in your sql, you'll see others NOT NULL fields without underscore.

That's the difference between your code and solution.

Body:
I'm a designer, but as there's no programmer in my company I have to start studing programming. Which I did only somedays ago (and I have only  a html and css knowledge background) so pleasepleaseplease don't take any knowledge for granted if you can answer me!

I'm studing PHP and MySQL using "PHP & MySQL in easy steps" by Mike McGranth (if any of you have it I'm at page 90/91). So, the task is simple: write a .sql file and create a table in phpMyAdmin with it.

Since it's an exercise from a book I just have to write as it's written on the page and test it; yes, I have the solution-file too, but the point is I can't see the difference between my code, which can't be processed by phpMyAdmin, and the solution-code, which gives no problem.

The .sql file written by me is this:

CREATE TABLE IF NOT EXISTS products
(
id INT UNIQUE AUTO_INCREMENT ,
code INT NOT_NULL ,
name VARCHAR(25) NOT NULL ,
quantity INT DEFAULT 1 NULL ,
price DECIMAL(6,2) NOT NULL
) ;

And the solution-file code is this:

CREATE TABLE IF NOT EXISTS products
(
  id        INT UNIQUE  AUTO_INCREMENT ,
  code      INT     NOT NULL ,
  name      VARCHAR(25)     NOT NULL ,
  quantity  INT     DEFAULT 1 NULL ,
  price     DECIMAL(6,2)    NOT NULL
) ;

This is also how the look like in a code-editor program:

This is the error that phpMyAdmin gives to me (if the japanese part is important I can add the translation):

Since I have a solution, why do I ask? Because maybe I've done just a small mistake, but if I don't understand it I'm afraid to do it again when handling bigger files, maybe a client db, real work, not just an exercise.
So, if anyone will be so kind to explain it to me he/she will have my ethernal gratitude!

Body:
In your code there is

code INT NOT_NULL

That underscore is wrong .

If you take a look at other lines in your sql, you'll see others NOT NULL fields without underscore.

That's the difference between your code and solution.


问:
Activity indicator not centered in landscape mode
I am trying to add an activity indicator on top of my table view such that it is appearing in the center of the screen in both portrait and landscape mode.

The activity indicator is placed inside a view which is a subview of the main view. The table view is included via a view container in the main view.

When I click "Add Missing Constraints", the indicator gets a Center Y alignment constraint and a Horizontal space (141) constraint. As expected this makes things look just fine in portrait mode, but in landscape mode the activity indicator appears to the left instead of being horizontally centered.

I have tried to change the Horizontal space constraint to a Center X alignment constraint, but that does not seem to make the situation any better.

Any suggestions?

Here is a close up:

答:
@Stine I don't know that you got the answer or not. But try the following in the storyboard. In my case, it is worked.

In storyboard set the vertical and horizontal alignments for the activity indicator view. And after that set, the width and height constraints in the Add New Constraints.

After that

Here is the final result in portrait and landscape modes

For Portrait:

For Landscape:


问:
Build dynamic list in Terraform?
I am trying to dynamically create some aws resources in terraform making use of count and then build an output variable containing a list of all created resource ids

```<code>resource "aws_subnet" "subnet-1" {
  // If subnet_id value is supplied then we set count to 1 to create otherwise skip
  count = "${replace(replace(var.primary_subnet_cidr, "/^.+/", "1"), "/^$/", "0")}"
  tags = {
    Name = "subnet-1"
  }
  cidr_block = "${var.primary_subnet_cidr}"
  vpc_id = "${var.vpc_id}"
  availability_zone = "${var.aws_region}a"
}
resource "aws_subnet" "subnet-2" {
  // If subnet_id value is supplied then we set count to 1 to create otherwise skip
  count = "${replace(replace(var.secondary_subnet_cidr, "/^.+/", "1"),"/^$/", "0")}"
  tags = {
    Name = "subnet-2"
  }
  cidr_block = "${var.secondary_subnet_cidr}"
  vpc_id = "${var.vpc_id}"
  availability_zone = "${var.aws_region}b"
}

output "ids" {
      value = ["${aws_subnet.subnet-1.id}","${aws_subnet.subnet-2.id}"]
}
</code>```

The idea is to create only the subnet you want by supplying its variable (primary_subnet_cidr or secondary_subnet_cidr).

Creating them dynamically works fine however my issue is with the dynamic list.

When attempting to use this list in something like a aws_db_subnet_group.subnet_ids which takes in a list, it only works if both subnets have been created otherwise it throws me the following error

InvalidSubnet: Subnet IDs are required.

I have also tried this

```<code>output "ids" {
      value = ["${aws_subnet.*.id}"]
}
</code>```

But terraform does not seem to support wildcards on resource level.

I suspect this has to do with the way I generated the output list. Is there a better way to generate that dynamic list so it includes only the created resources?

答:
You were close, but you need to use the correct Terraform resource syntax of RESOURCE-TYPE.RESOURCE-NAME.PROPERTY_NAME or RESOURCE-TYPE.RESOURCE-NAME.*.PROPERTY_NAME. So, in your example, you would output:

```<code>output "ids" {
   value = "${aws_subnet.subnet-1.*.id}"
}
</code>```

Of course, you may want to join the two lists using the concat interpolation function:

```<code>output "ids" {
   value = "${concat(aws_subnet.subnet-1.*.id, aws_subnet.subnet-2.*.id)}"
}
</code>```

But if your count property is set to 0 on either resource, this might throw an error. To remedy that, you can use some combination of other interpolation functions (e.g. coalescelist()), but I'm afraid I can't remember the exact combination.

Finally, for your count properties, these var definitions are a little tricky to read. Here are some other ideas to try:

```<code>// Count = 1 if var.secondary_subnet_cidr is non-empty
resource "aws_subnet" "subnet-1" {
  count = "${signum(length(var.secondary_subnet_cidr))}"
  ...
}

// Define a separate var altogether. Ideally, you could infer this, but sometimes it's the best you can do.
resource "aws_subnet" "subnet-1" {
  count = "${var.should_create_secondary_subnet)}"
  ...
}
</code>```

Update Jun 6, 2017: Thanks to @MartinAtkins for pointing out that as of Terraform 0.9.x, you no longer need to wrap list outputs in [ and ]. I've updated my answer.

Update Jun 8, 2017: To select only the non-empty list out of two lists where one may be empty, use ${element(concat(aws_subnet.subnet-1.*.id, aws_subnet.subnet-2.*.id), 0)}. The concat() function will accept an empty list, and the element(..., 0) will always returns the first element, which in this case is the non-empty list.

Title: Build dynamic list in Terraform?

Body:
I am trying to dynamically create some aws resources in terraform making use of count and then build an output variable containing a list of all created resource ids

resource "aws_subnet" "subnet-1" {
  // If subnet_id value is supplied then we set count to 1 to create otherwise skip
  count = "${replace(replace(var.primary_subnet_cidr, "/^.+/", "1"), "/^$/", "0")}"
  tags = {
    Name = "subnet-1"
  }
  cidr_block = "${var.primary_subnet_cidr}"
  vpc_id = "${var.vpc_id}"
  availability_zone = "${var.aws_region}a"
}
resource "aws_subnet" "subnet-2" {
  // If subnet_id value is supplied then we set count to 1 to create otherwise skip
  count = "${replace(replace(var.secondary_subnet_cidr, "/^.+/", "1"),"/^$/", "0")}"
  tags = {
    Name = "subnet-2"
  }
  cidr_block = "${var.secondary_subnet_cidr}"
  vpc_id = "${var.vpc_id}"
  availability_zone = "${var.aws_region}b"
}

output "ids" {
      value = ["${aws_subnet.subnet-1.id}","${aws_subnet.subnet-2.id}"]
}

The idea is to create only the subnet you want by supplying its variable (primary_subnet_cidr or secondary_subnet_cidr).

Creating them dynamically works fine however my issue is with the dynamic list.

When attempting to use this list in something like a aws_db_subnet_group.subnet_ids which takes in a list, it only works if both subnets have been created otherwise it throws me the following error

InvalidSubnet: Subnet IDs are required.

I have also tried this

output "ids" {
      value = ["${aws_subnet.*.id}"]
}

But terraform does not seem to support wildcards on resource level.

I suspect this has to do with the way I generated the output list. Is there a better way to generate that dynamic list so it includes only the created resources?

Body:
You were close, but you need to use the correct Terraform resource syntax of RESOURCE-TYPE.RESOURCE-NAME.PROPERTY_NAME or RESOURCE-TYPE.RESOURCE-NAME.*.PROPERTY_NAME. So, in your example, you would output:

output "ids" {
   value = "${aws_subnet.subnet-1.*.id}"
}

Of course, you may want to join the two lists using the concat interpolation function:

output "ids" {
   value = "${concat(aws_subnet.subnet-1.*.id, aws_subnet.subnet-2.*.id)}"
}

But if your count property is set to 0 on either resource, this might throw an error. To remedy that, you can use some combination of other interpolation functions (e.g. coalescelist()), but I'm afraid I can't remember the exact combination.

Finally, for your count properties, these var definitions are a little tricky to read. Here are some other ideas to try:

// Count = 1 if var.secondary_subnet_cidr is non-empty
resource "aws_subnet" "subnet-1" {
  count = "${signum(length(var.secondary_subnet_cidr))}"
  ...
}

// Define a separate var altogether. Ideally, you could infer this, but sometimes it's the best you can do.
resource "aws_subnet" "subnet-1" {
  count = "${var.should_create_secondary_subnet)}"
  ...
}

Update Jun 6, 2017: Thanks to @MartinAtkins for pointing out that as of Terraform 0.9.x, you no longer need to wrap list outputs in [ and ]. I've updated my answer.

Update Jun 8, 2017: To select only the non-empty list out of two lists where one may be empty, use ${element(concat(aws_subnet.subnet-1.*.id, aws_subnet.subnet-2.*.id), 0)}. The concat() function will accept an empty list, and the element(..., 0) will always returns the first element, which in this case is the non-empty list.


问:
Remove space of checkbox if it does not exist
I have a listView populated with the help of a CustomAdapter.

I make a test while retrieving the values from my db.

One of the rows if 'Homework'. If homework = 1, then I show a CheckBox in the beginning of the line of my listView. But if it's 0 , I dont show anything. But I'd like to move all the text after the checkbox to the left. in my list_row.xml I declared a checkbox, so if homework is 0, i just setVisibility to INVISIBLE on my checkbox.

I can't post images, so I'll give an example :

if homework is 1 , my listView is like this :

```<code>Checkbox - Date of creation - Title
</code>```

if Homework is 0, my row of the listview is like this :

```<code>         - Date of creation - Title
</code>```

So you can see that there will have an empty space if Homework is 0. How can I change that so it stays like this:

```<code>-Date of creation - Title
</code>```

Thank you !And tell me if you need the code my CustomAdapter please

@UPDATE-my customadapter

```<code>`public class CustomAdapterJalons extends SimpleCursorAdapter {

private Context mContext;
private Context appContext;
private int layout;
private Cursor cr;
private final LayoutInflater inflater;

public CustomAdapterJalons(Context context, int layout, Cursor c, String[] from, int[] to) {
    super(context, layout, c, from, to);
    this.layout = layout;
    this.mContext = context;
    this.inflater = LayoutInflater.from(context);
    this.cr = c;
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return inflater.inflate(layout, null);
}

@Override
public void bindView(View view, final Context context, final Cursor cursor) {
    super.bindView(view, context, cursor);

    final int position = cursor.getPosition();

    cursor.moveToPosition(position);

    int devoir = cursor.getInt(3);
    int evaluation = cursor.getInt(4);
    int importance = cursor.getInt(5);
    int fait = cursor.getInt(10);
    final CheckBox cbdevoir = (CheckBox) view.findViewById(R.id.CBDevoir);
    final TextView couleur = (TextView)view.findViewById(R.id.TVCouleurImportance);

    if(importance==0)
    {
        couleur.setBackgroundColor(Color.parseColor("#ff8080"));
    }
    if(importance==1)
    {
        couleur.setBackgroundColor(Color.parseColor("#ff0000"));
    }
    if(importance==2)
    {
        couleur.setBackgroundColor(Color.parseColor("#4d0000"));
    }

    if (fait == 1) {
        cbdevoir.setChecked(true);
    } else {
        cbdevoir.setChecked(false);
    }

    cbdevoir.setVisibility(devoir ==1? View.VISIBLE: View.GONE);`
</code>```

my list_row.xml:

```<code>`<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:id="@+id/item_root"
android:weightSum="1">

<CheckBox
    android:id="@+id/CBDevoir"
    android:layout_width="30dp"
    android:layout_height="20dp"
    android:layout_marginLeft="1dp"
    android:layout_marginTop="-1dp"
    android:checked="false"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/text_branche_cours"
    android:layout_width="75dp"
    android:layout_height="16dp"
    android:layout_marginLeft="32dp"
    android:layout_marginTop="2dp"
    android:text="English"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/text_trait"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=" - "
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="-1dp"
    android:layout_marginLeft="106dp"
    app:layout_constraintLeft_toLeftOf="parent" />

<TextView
    android:id="@+id/text_designation"
    android:layout_width="150dp"
    android:layout_height="18dp"
    android:layout_marginLeft="122dp"
    android:layout_marginTop="2dp"
    android:ellipsize="end"
    android:maxLines="1"
    android:text="Reading"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/TVCouleurImportance"
    android:layout_width="25dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="281dp"
    android:layout_marginTop="-1dp"
    android:layout_weight="1"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
</code>```

`

答:
You have to Do something like this

```<code> @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        View rowView;
        rowView = inflater.inflate(R.layout.yourLayout, null);
        CheckBox cb = (CheckBox) rowView.findViewById(R.id.CheckBoxId);
        cb.setVisibility(View.INVISIBLE);
        if(getHomeWork()==1){
          cb.setVisibility(View.VISIBLE);
        }
        return rowView;
    }
</code>```

setVisibility have Three different options

View.VISIBLE - This show the view in screen if it is gone

View.GONE - This will hide the view and your other content take place of this view

View.INVISIBLE - This will hide view but other view will not take the place of this view (means space is remains as it is of that view)

Body:
I have a listView populated with the help of a CustomAdapter.

I make a test while retrieving the values from my db.

One of the rows if 'Homework'. If homework = 1, then I show a CheckBox in the beginning of the line of my listView. But if it's 0 , I dont show anything. But I'd like to move all the text after the checkbox to the left. in my list_row.xml I declared a checkbox, so if homework is 0, i just setVisibility to INVISIBLE on my checkbox.

I can't post images, so I'll give an example :

if homework is 1 , my listView is like this :

Checkbox - Date of creation - Title

if Homework is 0, my row of the listview is like this :

         - Date of creation - Title

So you can see that there will have an empty space if Homework is 0. How can I change that so it stays like this:

-Date of creation - Title

Thank you !And tell me if you need the code my CustomAdapter please

@UPDATE-my customadapter

`public class CustomAdapterJalons extends SimpleCursorAdapter {

private Context mContext;
private Context appContext;
private int layout;
private Cursor cr;
private final LayoutInflater inflater;

public CustomAdapterJalons(Context context, int layout, Cursor c, String[] from, int[] to) {
    super(context, layout, c, from, to);
    this.layout = layout;
    this.mContext = context;
    this.inflater = LayoutInflater.from(context);
    this.cr = c;
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return inflater.inflate(layout, null);
}

@Override
public void bindView(View view, final Context context, final Cursor cursor) {
    super.bindView(view, context, cursor);

    final int position = cursor.getPosition();

    cursor.moveToPosition(position);

    int devoir = cursor.getInt(3);
    int evaluation = cursor.getInt(4);
    int importance = cursor.getInt(5);
    int fait = cursor.getInt(10);
    final CheckBox cbdevoir = (CheckBox) view.findViewById(R.id.CBDevoir);
    final TextView couleur = (TextView)view.findViewById(R.id.TVCouleurImportance);

    if(importance==0)
    {
        couleur.setBackgroundColor(Color.parseColor("#ff8080"));
    }
    if(importance==1)
    {
        couleur.setBackgroundColor(Color.parseColor("#ff0000"));
    }
    if(importance==2)
    {
        couleur.setBackgroundColor(Color.parseColor("#4d0000"));
    }

    if (fait == 1) {
        cbdevoir.setChecked(true);
    } else {
        cbdevoir.setChecked(false);
    }

    cbdevoir.setVisibility(devoir ==1? View.VISIBLE: View.GONE);`

my list_row.xml:

`<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:id="@+id/item_root"
android:weightSum="1">

<CheckBox
    android:id="@+id/CBDevoir"
    android:layout_width="30dp"
    android:layout_height="20dp"
    android:layout_marginLeft="1dp"
    android:layout_marginTop="-1dp"
    android:checked="false"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/text_branche_cours"
    android:layout_width="75dp"
    android:layout_height="16dp"
    android:layout_marginLeft="32dp"
    android:layout_marginTop="2dp"
    android:text="English"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/text_trait"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=" - "
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="-1dp"
    android:layout_marginLeft="106dp"
    app:layout_constraintLeft_toLeftOf="parent" />

<TextView
    android:id="@+id/text_designation"
    android:layout_width="150dp"
    android:layout_height="18dp"
    android:layout_marginLeft="122dp"
    android:layout_marginTop="2dp"
    android:ellipsize="end"
    android:maxLines="1"
    android:text="Reading"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/TVCouleurImportance"
    android:layout_width="25dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="281dp"
    android:layout_marginTop="-1dp"
    android:layout_weight="1"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

`

Body:
You have to Do something like this

 @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        View rowView;
        rowView = inflater.inflate(R.layout.yourLayout, null);
        CheckBox cb = (CheckBox) rowView.findViewById(R.id.CheckBoxId);
        cb.setVisibility(View.INVISIBLE);
        if(getHomeWork()==1){
          cb.setVisibility(View.VISIBLE);
        }
        return rowView;
    }

setVisibility have Three different options

View.VISIBLE - This show the view in screen if it is gone

View.GONE - This will hide the view and your other content take place of this view

View.INVISIBLE - This will hide view but other view will not take the place of this view (means space is remains as it is of that view)


问:
Facing Null Pointer Exception: Cannot invoke method firstMethod() on null Object : Grails 3.2.10
I wrote a simple rest-api Controller in Grails 3.2.10 version. Below are my system configurations. Created application is also rest-api profile.

Grails Version: 3.2.10
Groovy Version: 2.4.10
JVM Version: 1.8.0_131

Sample code written is as follows:
Controller:

```<code>package mydevpath

import grails.rest.*
import grails.converters.*

class LoginController {
static responseFormats = ['json', 'xml']

def index() {
        def loginService
        def val = loginService.firstMethod()

        render 'hello World' + val
     }
   }
</code>```

Service :`
     package mydevpath

```<code>import grails.transaction.Transactional

 @Transactional
 class LoginService {
    static scope = "prototype"

     def firstMethod(){
        return 'From Service'
  }
}
</code>```

On running and hitting the URL , I am facing below error.

```<code>NullPointerException occurred when processing request
: [POST] /login
Cannot invoke method firstMethod() on null object. Stacktrace follows:

java.lang.reflect.InvocationTargetException: null
        at org.grails.core.DefaultGrailsControllerClass$ReflectionInvoker.
invoke(DefaultGrailsControllerClass.java:211)
        at org.grails.core.DefaultGrailsControllerClass.invoke(DefaultGrai
lsControllerClass.java:188)
</code>```

Can somebody help me with the Issue?

Regards,
Pramod

答:
Your service should be declared outside of the index action:</p>

```<code>package mydevpath

import grails.rest.*
import grails.converters.*

class LoginController {
static responseFormats = ['json', 'xml']

def loginService

def index() {
    def val = loginService.firstMethod()

    render 'hello World' + val
}
}
</code>```

Body:
I wrote a simple rest-api Controller in Grails 3.2.10 version. Below are my system configurations. Created application is also rest-api profile.

Grails Version: 3.2.10
Groovy Version: 2.4.10
JVM Version: 1.8.0_131

Sample code written is as follows:
Controller:

package mydevpath

import grails.rest.*
import grails.converters.*

class LoginController {
static responseFormats = ['json', 'xml']

def index() {
        def loginService
        def val = loginService.firstMethod()

        render 'hello World' + val
     }
   }

Service :`
     package mydevpath

import grails.transaction.Transactional

 @Transactional
 class LoginService {
    static scope = "prototype"

     def firstMethod(){
        return 'From Service'
  }
}

On running and hitting the URL , I am facing below error.

NullPointerException occurred when processing request
: [POST] /login
Cannot invoke method firstMethod() on null object. Stacktrace follows:

java.lang.reflect.InvocationTargetException: null
        at org.grails.core.DefaultGrailsControllerClass$ReflectionInvoker.
invoke(DefaultGrailsControllerClass.java:211)
        at org.grails.core.DefaultGrailsControllerClass.invoke(DefaultGrai
lsControllerClass.java:188)

Can somebody help me with the Issue?

Regards,
Pramod

Body:
Your service should be declared outside of the index action:

package mydevpath

import grails.rest.*
import grails.converters.*

class LoginController {
static responseFormats = ['json', 'xml']

def loginService

def index() {
    def val = loginService.firstMethod()

    render 'hello World' + val
}
}


问:
I need a Dynamic News Bar Javascript
Can anyone tel me where I can find a script for a horizental dynamic news bar.

what I mean in dynamic is that I can feed the news into the news bar using xml file or mySQL database or something like this.

I searched for such thing in the internet and found some news bars but there aren't dynamic

Nicest Regards

Title: I need a Dynamic News Bar Javascript


问:
Not able to see JSON Editor even after installing JSON Editor Plugin in eclipse
I am using eclipse neon version.
I installed JSON Editor Plugin using Eclipse Marketplace. It installed successfully.

I can see entry for JSON Editor Plugin in Installed Software list.
This is developed by Boothen Technology.

But still I can not find JSON Editor in the list of editors.
It used to work fine in the past.
I tried reinstalling many times but did not get success.

答:
There was some problem with my .plugins folder because of corrupt eclipse workspace.
This was present in the following location

```<code><Eclipse-Workspace>/.metadata/.plugins
</code>```

Shutdown Eclipse.

Delete content present inside .plugins folder.

Restart Eclipse.

Import projects again from the workspace.

JSON Editor mapped to the .json files.

The same thing also solved the problem for .sh files also.

Body:
There was some problem with my .plugins folder because of corrupt eclipse workspace.
This was present in the following location

<Eclipse-Workspace>/.metadata/.plugins

Shutdown Eclipse.

Delete content present inside .plugins folder.

Restart Eclipse.

Import projects again from the workspace.

JSON Editor mapped to the .json files.

The same thing also solved the problem for .sh files also.