问:
Why does the get() operation in multiprocessing.Pool.map_async take so long?
```<code>import multiprocessing as mp
import numpy as np

pool   = mp.Pool( processes = 4 )
inp    = np.linspace( 0.01, 1.99, 100 )
result = pool.map_async( func, inp ) #Line1 ( func is some Python function which acts on input )
output = result.get()                #Line2
</code>```

So, I was trying to parallelize some code in Python, using a .map_async() method on a multiprocessing.Pool() instance.

I noticed that while

Line1 takes around a thousandth of a second,

Line2 takes about .3 seconds.

Is there a better way to do this or a way to get around the bottleneck caused by Line2,

or

am I doing something wrong here?

( I am rather new to this. )

答:
Am I doing something wrong here?

Do not panic, many users do the very same - Paid more than received.

This is a common lecture not on using some "promising" syntax-constructor, but on paying the actual costs for using it.

The story is long, the effect was straightforward - you expected a low hanging fruit, but had to pay an immense cost of process-instantiation, work-package re-distribution and for collection of results, all that circus just for doing but a few rounds of func()-calls.

Wow?
Stop!
Parallelisation was brought to me that will SPEEDUP processing?!?

Well, who told you that any such ( potential ) speedup is for free?

Let's be quantitative and rather measure the actual code-execution time, instead of emotions, right?

Benchmarking is always a fair move.

It helps us, mortals, to escape from just expectations

and get ourselves into quantitative records-of-evidence supported knowledge:

```<code>from zmq import Stopwatch; aClk = Stopwatch() # this is a handy tool to do so
</code>```

AS-IS test:

Before moving forwards, one ought record this pair:

```<code>>>> aClk.start(); _ = [   func( SEQi ) for SEQi in inp ]; aClk.stop() # [SEQ]
>>> HowMuchWillWePAY2RUN( func, 4, 100 )                              # [RUN]
>>> HowMuchWillWePAY2MAP( func, 4, 100 )                              # [MAP]
</code>```

This will set the span among the performance envelopes from a pure-[SERIAL] [SEQ]-of-calls, to an un-optimised joblib.Parallel() or any other, if one wishes to extend the experiment with any other tools, like a said  multiprocessing.Pool() or other.

Test-case A:

Intent:

so as to measure the cost of a { process | job }-instantiation, we need a NOP-work-package payload, that will spend almost nothing "there" but return "back" and will not require to pay any additional add-on costs ( be it for any input parameters' transmissions or returning any value )

```<code>def a_NOP_FUN( aNeverConsumedPAR ):
    """                                                 __doc__
    The intent of this FUN() is indeed to do nothing at all,
                             so as to be able to benchmark
                             all the process-instantiation
                             add-on overhead costs.
    """
    pass
</code>```

So, the setup-overhead add-on costs comparison is here:

```<code>#-------------------------------------------------------<function a_NOP_FUN
[SEQ]-pure-[SERIAL] worked within ~   37 ..     44 [us] on this localhost
[MAP]-just-[CONCURENT] tool         2536 ..   7343 [us]
[RUN]-just-[CONCURENT] tool       111162 .. 112609 [us]
</code>```

Using a strategy of
joblib.delayed() on joblib.Parallel() task-processing:

```<code>def HowMuchWillWePAY2RUN( aFun2TEST = a_NOP_FUN, JOBS_TO_SPAWN = 4, RUNS_TO_RUN = 10 ):
    from zmq import Stopwatch; aClk = Stopwatch()
    try:
         aClk.start()
         joblib.Parallel(  n_jobs = JOBS_TO_SPAWN
                          )( joblib.delayed( aFun2TEST )
                                           ( aFunPARAM )
                                       for ( aFunPARAM )
                                       in  range( RUNS_TO_RUN )
                             )
    except:
         pass
    finally:
         try:
             _ = aClk.stop()
         except:
             _ = -1
             pass
    pass;  pMASK = "CLK:: {0:_>24d} [us] @{1: >4d}-JOBs ran{2: >6d} RUNS {3:}"
    print( pMASK.format( _,
                         JOBS_TO_SPAWN,
                         RUNS_TO_RUN,
                         " ".join( repr( aFun2TEST ).split( " ")[:2] )
                         )
            )
</code>```

Using a strategy of a lightweight
.map_async() method on a multiprocessing.Pool() instance:

```<code>def HowMuchWillWePAY2MAP( aFun2TEST = a_NOP_FUN, PROCESSES_TO_SPAWN = 4, RUNS_TO_RUN = 1 ):
    from zmq import Stopwatch; aClk = Stopwatch()
    try:
         import numpy           as np
         import multiprocessing as mp

         pool = mp.Pool( processes = PROCESSES_TO_SPAWN )
         inp  = np.linspace( 0.01, 1.99, 100 )

         aClk.start()
         for i in xrange( RUNS_TO_RUN ):
             pass;    result = pool.map_async( aFun2TEST, inp )
             output = result.get()
         pass
    except:
         pass
    finally:
         try:
             _ = aClk.stop()
         except:
             _ = -1
             pass
    pass;  pMASK = "CLK:: {0:_>24d} [us] @{1: >4d}-PROCs ran{2: >6d} RUNS {3:}"
    print( pMASK.format( _,
                         PROCESSES_TO_SPAWN,
                         RUNS_TO_RUN,
                         " ".join( repr( aFun2TEST ).split( " ")[:2] )
                         )
            )
</code>```

So,

the first set of pain and surprises

comes straight at the actual cost-of-doing-NOTHING in a concurrent pool of joblib.Parallel():

```<code> CLK:: __________________117463 [us] @   4-JOBs ran    10 RUNS <function a_NOP_FUN
 CLK:: __________________111182 [us] @   3-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________110229 [us] @   3-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________110095 [us] @   3-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________111794 [us] @   3-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________110030 [us] @   3-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________110697 [us] @   3-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: _________________4605843 [us] @ 123-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________336208 [us] @ 123-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________298816 [us] @ 123-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________355492 [us] @ 123-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________320837 [us] @ 123-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________308365 [us] @ 123-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________372762 [us] @ 123-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________304228 [us] @ 123-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________337537 [us] @ 123-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________941775 [us] @ 123-JOBs ran 10000 RUNS <function a_NOP_FUN
 CLK:: __________________987440 [us] @ 123-JOBs ran 10000 RUNS <function a_NOP_FUN
 CLK:: _________________1080024 [us] @ 123-JOBs ran 10000 RUNS <function a_NOP_FUN
 CLK:: _________________1108432 [us] @ 123-JOBs ran 10000 RUNS <function a_NOP_FUN
 CLK:: _________________7525874 [us] @ 123-JOBs ran100000 RUNS <function a_NOP_FUN
</code>```

So, this scientifically fair and rigorous test started from this simplest ever case, already showing the benchmarked costs of all the associated code-execution processing setup-overheads a smallest ever joblib.Parallel() penalty sine-qua-non.

This forwards us into a direction, where real-world algorithms do live - best with next adding some larger and larger "payload"-sizes into the testing loop.

Now, we know the penalty
for going into a "just"-[CONCURRENT] code-execution - and next?

Using this systematic and lightweight approach, we may go forwards in the story, as we will need to also benchmark the add-on costs and other Amdahl's Law indirect effects of { remote-job-PAR-XFER(s) | remote-job-MEM.alloc(s) | remote-job-CPU-bound-processing | remote-job-fileIO(s) }

A function template like this may help in re-testing ( as you see there will be a lot to re-run, while the O/S noise and some additional artifacts will step into the actual cost-of-use patterns ):

Test-case B:

Once we have paid the up-front cost, the next most common mistake is to forget the costs of memory allocations. So, lets test it:

```<code>def a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR( aNeverConsumedPAR, SIZE1D = 1000 ):
    """                                                 __doc__
    The intent of this FUN() is to do nothing but
                             a MEM-allocation
                             so as to be able to benchmark
                             all the process-instantiation
                             add-on overhead costs.
    """
    import numpy as np              # yes, deferred import, libs do defer imports
    aMemALLOC = np.zeros( ( SIZE1D, #       so as to set
                            SIZE1D, #       realistic ceilings
                            SIZE1D, #       as how big the "Big Data"
                            SIZE1D  #       may indeed grow into
                            ),
                          dtype = np.float64,
                          order = 'F'
                          )         # .ALLOC + .SET
    aMemALLOC[2,3,4,5] = 8.7654321  # .SET
    aMemALLOC[3,3,4,5] = 1.2345678  # .SET

    return aMemALLOC[2:3,3,4,5]
</code>```

In case your platform will stop to be able to allocate the requested memory-blocks, there we head-bang into another kind of problems ( with a class of hidden glass-ceilings if trying to go-parallel in a physical-resources agnostic manner ). One may edit the SIZE1D scaling, so as to at least fit into the platform RAM addressing / sizing capabilites, yet, the performance envelopes of the real-world problem computing are still of our great interest here:

```<code>>>> HowMuchWillWePAY2RUN( a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR, 200, 1000 )
</code>```

may yield

a cost-to-pay, being anything between 0.1 [s] and +9 [s] (!!)

just for doing STILL NOTHING, but now also without forgetting about some realistic MEM-allocation add-on costs "there"

```<code>CLK:: __________________116310 [us] @   4-JOBs ran    10 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________120054 [us] @   4-JOBs ran    10 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________129441 [us] @  10-JOBs ran   100 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________123721 [us] @  10-JOBs ran   100 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________127126 [us] @  10-JOBs ran   100 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________124028 [us] @  10-JOBs ran   100 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________305234 [us] @ 100-JOBs ran   100 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________243386 [us] @ 100-JOBs ran   100 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________241410 [us] @ 100-JOBs ran   100 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________267275 [us] @ 100-JOBs ran   100 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________244207 [us] @ 100-JOBs ran   100 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________653879 [us] @ 100-JOBs ran  1000 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________405149 [us] @ 100-JOBs ran  1000 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________351182 [us] @ 100-JOBs ran  1000 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________362030 [us] @ 100-JOBs ran  1000 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: _________________9325428 [us] @ 200-JOBs ran  1000 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________680429 [us] @ 200-JOBs ran  1000 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________533559 [us] @ 200-JOBs ran  1000 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: _________________1125190 [us] @ 200-JOBs ran  1000 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________591109 [us] @ 200-JOBs ran  1000 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
</code>```

Test-case C:

kindly read the tail sections of this post

Test-case D:

kindly read the tail sections of this post

Epilogue:

For each and every "promise", the fair best next step is first to cross-validate the actual code-execution costs, before starting any code re-engineering. The sum of real-world platform's add-on costs may devastate any expected speedups, even if the original, overhead-naive Amdahl's Law might have created some expected speedup-effects.

As Mr. Walter E. Deming has expressed many times, without DATA we make ourselves left to just OPINIONS.

 A bonus part:

having read as far as here, one might already found, that there is not any kind of "drawback" or "error" in the #Line2 per se, but the carefull design practice will show any better syntax-constructor, that spend less to achieve more ( as actual resources ( CPU, MEM, IOs, O/S ) permit on the code-execution platform ). Anything else is not principally different from a just blind telling Fortune.

Body:
import multiprocessing as mp
import numpy as np

pool   = mp.Pool( processes = 4 )
inp    = np.linspace( 0.01, 1.99, 100 )
result = pool.map_async( func, inp ) #Line1 ( func is some Python function which acts on input )
output = result.get()                #Line2

So, I was trying to parallelize some code in Python, using a .map_async() method on a multiprocessing.Pool() instance.

I noticed that while

Line1 takes around a thousandth of a second,

Line2 takes about .3 seconds.

Is there a better way to do this or a way to get around the bottleneck caused by Line2,

or

am I doing something wrong here?

( I am rather new to this. )

Body:
Am I doing something wrong here?

Do not panic, many users do the very same - Paid more than received.

This is a common lecture not on using some "promising" syntax-constructor, but on paying the actual costs for using it.

The story is long, the effect was straightforward - you expected a low hanging fruit, but had to pay an immense cost of process-instantiation, work-package re-distribution and for collection of results, all that circus just for doing but a few rounds of func()-calls.

Wow?
Stop!
Parallelisation was brought to me that will SPEEDUP processing?!?

Well, who told you that any such ( potential ) speedup is for free?

Let's be quantitative and rather measure the actual code-execution time, instead of emotions, right?

Benchmarking is always a fair move.

It helps us, mortals, to escape from just expectations

and get ourselves into quantitative records-of-evidence supported knowledge:

from zmq import Stopwatch; aClk = Stopwatch() # this is a handy tool to do so

AS-IS test:

Before moving forwards, one ought record this pair:

>>> aClk.start(); _ = [   func( SEQi ) for SEQi in inp ]; aClk.stop() # [SEQ]
>>> HowMuchWillWePAY2RUN( func, 4, 100 )                              # [RUN]
>>> HowMuchWillWePAY2MAP( func, 4, 100 )                              # [MAP]

This will set the span among the performance envelopes from a pure-[SERIAL] [SEQ]-of-calls, to an un-optimised joblib.Parallel() or any other, if one wishes to extend the experiment with any other tools, like a said  multiprocessing.Pool() or other.

Test-case A:

Intent:

so as to measure the cost of a { process | job }-instantiation, we need a NOP-work-package payload, that will spend almost nothing "there" but return "back" and will not require to pay any additional add-on costs ( be it for any input parameters' transmissions or returning any value )

def a_NOP_FUN( aNeverConsumedPAR ):
    """                                                 __doc__
    The intent of this FUN() is indeed to do nothing at all,
                             so as to be able to benchmark
                             all the process-instantiation
                             add-on overhead costs.
    """
    pass

So, the setup-overhead add-on costs comparison is here:

#-------------------------------------------------------<function a_NOP_FUN
[SEQ]-pure-[SERIAL] worked within ~   37 ..     44 [us] on this localhost
[MAP]-just-[CONCURENT] tool         2536 ..   7343 [us]
[RUN]-just-[CONCURENT] tool       111162 .. 112609 [us]

Using a strategy of
joblib.delayed() on joblib.Parallel() task-processing:

def HowMuchWillWePAY2RUN( aFun2TEST = a_NOP_FUN, JOBS_TO_SPAWN = 4, RUNS_TO_RUN = 10 ):
    from zmq import Stopwatch; aClk = Stopwatch()
    try:
         aClk.start()
         joblib.Parallel(  n_jobs = JOBS_TO_SPAWN
                          )( joblib.delayed( aFun2TEST )
                                           ( aFunPARAM )
                                       for ( aFunPARAM )
                                       in  range( RUNS_TO_RUN )
                             )
    except:
         pass
    finally:
         try:
             _ = aClk.stop()
         except:
             _ = -1
             pass
    pass;  pMASK = "CLK:: {0:_>24d} [us] @{1: >4d}-JOBs ran{2: >6d} RUNS {3:}"
    print( pMASK.format( _,
                         JOBS_TO_SPAWN,
                         RUNS_TO_RUN,
                         " ".join( repr( aFun2TEST ).split( " ")[:2] )
                         )
            )

Using a strategy of a lightweight
.map_async() method on a multiprocessing.Pool() instance:

def HowMuchWillWePAY2MAP( aFun2TEST = a_NOP_FUN, PROCESSES_TO_SPAWN = 4, RUNS_TO_RUN = 1 ):
    from zmq import Stopwatch; aClk = Stopwatch()
    try:
         import numpy           as np
         import multiprocessing as mp

         pool = mp.Pool( processes = PROCESSES_TO_SPAWN )
         inp  = np.linspace( 0.01, 1.99, 100 )

         aClk.start()
         for i in xrange( RUNS_TO_RUN ):
             pass;    result = pool.map_async( aFun2TEST, inp )
             output = result.get()
         pass
    except:
         pass
    finally:
         try:
             _ = aClk.stop()
         except:
             _ = -1
             pass
    pass;  pMASK = "CLK:: {0:_>24d} [us] @{1: >4d}-PROCs ran{2: >6d} RUNS {3:}"
    print( pMASK.format( _,
                         PROCESSES_TO_SPAWN,
                         RUNS_TO_RUN,
                         " ".join( repr( aFun2TEST ).split( " ")[:2] )
                         )
            )

So,

the first set of pain and surprises

comes straight at the actual cost-of-doing-NOTHING in a concurrent pool of joblib.Parallel():

 CLK:: __________________117463 [us] @   4-JOBs ran    10 RUNS <function a_NOP_FUN
 CLK:: __________________111182 [us] @   3-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________110229 [us] @   3-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________110095 [us] @   3-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________111794 [us] @   3-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________110030 [us] @   3-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________110697 [us] @   3-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: _________________4605843 [us] @ 123-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________336208 [us] @ 123-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________298816 [us] @ 123-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________355492 [us] @ 123-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________320837 [us] @ 123-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________308365 [us] @ 123-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________372762 [us] @ 123-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________304228 [us] @ 123-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________337537 [us] @ 123-JOBs ran   100 RUNS <function a_NOP_FUN
 CLK:: __________________941775 [us] @ 123-JOBs ran 10000 RUNS <function a_NOP_FUN
 CLK:: __________________987440 [us] @ 123-JOBs ran 10000 RUNS <function a_NOP_FUN
 CLK:: _________________1080024 [us] @ 123-JOBs ran 10000 RUNS <function a_NOP_FUN
 CLK:: _________________1108432 [us] @ 123-JOBs ran 10000 RUNS <function a_NOP_FUN
 CLK:: _________________7525874 [us] @ 123-JOBs ran100000 RUNS <function a_NOP_FUN

So, this scientifically fair and rigorous test started from this simplest ever case, already showing the benchmarked costs of all the associated code-execution processing setup-overheads a smallest ever joblib.Parallel() penalty sine-qua-non.

This forwards us into a direction, where real-world algorithms do live - best with next adding some larger and larger "payload"-sizes into the testing loop.

Now, we know the penalty
for going into a "just"-[CONCURRENT] code-execution - and next?

Using this systematic and lightweight approach, we may go forwards in the story, as we will need to also benchmark the add-on costs and other Amdahl's Law indirect effects of { remote-job-PAR-XFER(s) | remote-job-MEM.alloc(s) | remote-job-CPU-bound-processing | remote-job-fileIO(s) }

A function template like this may help in re-testing ( as you see there will be a lot to re-run, while the O/S noise and some additional artifacts will step into the actual cost-of-use patterns ):

Test-case B:

Once we have paid the up-front cost, the next most common mistake is to forget the costs of memory allocations. So, lets test it:

def a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR( aNeverConsumedPAR, SIZE1D = 1000 ):
    """                                                 __doc__
    The intent of this FUN() is to do nothing but
                             a MEM-allocation
                             so as to be able to benchmark
                             all the process-instantiation
                             add-on overhead costs.
    """
    import numpy as np              # yes, deferred import, libs do defer imports
    aMemALLOC = np.zeros( ( SIZE1D, #       so as to set
                            SIZE1D, #       realistic ceilings
                            SIZE1D, #       as how big the "Big Data"
                            SIZE1D  #       may indeed grow into
                            ),
                          dtype = np.float64,
                          order = 'F'
                          )         # .ALLOC + .SET
    aMemALLOC[2,3,4,5] = 8.7654321  # .SET
    aMemALLOC[3,3,4,5] = 1.2345678  # .SET

    return aMemALLOC[2:3,3,4,5]

In case your platform will stop to be able to allocate the requested memory-blocks, there we head-bang into another kind of problems ( with a class of hidden glass-ceilings if trying to go-parallel in a physical-resources agnostic manner ). One may edit the SIZE1D scaling, so as to at least fit into the platform RAM addressing / sizing capabilites, yet, the performance envelopes of the real-world problem computing are still of our great interest here:

>>> HowMuchWillWePAY2RUN( a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR, 200, 1000 )

may yield

a cost-to-pay, being anything between 0.1 [s] and +9 [s] (!!)

just for doing STILL NOTHING, but now also without forgetting about some realistic MEM-allocation add-on costs "there"

CLK:: __________________116310 [us] @   4-JOBs ran    10 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________120054 [us] @   4-JOBs ran    10 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________129441 [us] @  10-JOBs ran   100 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________123721 [us] @  10-JOBs ran   100 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________127126 [us] @  10-JOBs ran   100 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________124028 [us] @  10-JOBs ran   100 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________305234 [us] @ 100-JOBs ran   100 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________243386 [us] @ 100-JOBs ran   100 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________241410 [us] @ 100-JOBs ran   100 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________267275 [us] @ 100-JOBs ran   100 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________244207 [us] @ 100-JOBs ran   100 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________653879 [us] @ 100-JOBs ran  1000 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________405149 [us] @ 100-JOBs ran  1000 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________351182 [us] @ 100-JOBs ran  1000 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________362030 [us] @ 100-JOBs ran  1000 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: _________________9325428 [us] @ 200-JOBs ran  1000 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________680429 [us] @ 200-JOBs ran  1000 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________533559 [us] @ 200-JOBs ran  1000 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: _________________1125190 [us] @ 200-JOBs ran  1000 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR
CLK:: __________________591109 [us] @ 200-JOBs ran  1000 RUNS <function a_NOP_FUN_WITH_JUST_A_MEM_ALLOCATOR

Test-case C:

kindly read the tail sections of this post

Test-case D:

kindly read the tail sections of this post

Epilogue:

For each and every "promise", the fair best next step is first to cross-validate the actual code-execution costs, before starting any code re-engineering. The sum of real-world platform's add-on costs may devastate any expected speedups, even if the original, overhead-naive Amdahl's Law might have created some expected speedup-effects.

As Mr. Walter E. Deming has expressed many times, without DATA we make ourselves left to just OPINIONS.

 A bonus part:

having read as far as here, one might already found, that there is not any kind of "drawback" or "error" in the #Line2 per se, but the carefull design practice will show any better syntax-constructor, that spend less to achieve more ( as actual resources ( CPU, MEM, IOs, O/S ) permit on the code-execution platform ). Anything else is not principally different from a just blind telling Fortune.


来源: stackexchange

问:
Plot emojis/emoticons in R with ggplot
I'm trying to make a plot with emojis in ggplot2. What I want is to show emojis instead of labels or show like geom. This question in Stack is very similar to my problem, but it does not solve it either, the answer is quite manual and I need to make automatic (my real data frame has 3000 rows).

Just to clarify in this plot below I want to show emojis instead of text labels or within the bars. But seems impossible.

After trying differents solutions I'm stacked so any help would be appreciated. I read different ways to face the problem like here, here, here.

My last try was like this:

```<code>mult_format <- function() {
  function(x) emo::ji(x)
}
ggplot(foo, aes(name_emoji, n)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  scale_y_continuous(labels = mult_format())
</code>```

But it doesn't work.

My data looks like this, name_emoji cames from emo package, and I also can change it to byte:

```<code>               name_emoji     n        emoji
                    <chr> <int>        <chr>
 1            closed book     1 "\U0001f4d5"
 2          confused face     7 "\U0001f615"
 3                  dizzy     20 "\U0001f4ab"
 4 face with tears of joy     1 "\U0001f602"
 5          flexed biceps     1 "\U0001f4aa"
 6             light bulb     1 "\U0001f4a1"
</code>```

Here to reproduce:

```<code>structure(list(name_emoji = c("closed book", "confused face",
"dizzy", "face with tears of joy", "flexed biceps", "light bulb"
), n = c(1L, 7L, 20L, 1L, 1L, 1L), emoji = c("\U0001f4d5", "\U0001f615",
"\U0001f4ab", "\U0001f602", "\U0001f4aa", "\U0001f4a1")), .Names = c("name_emoji",
"n", "emoji"), row.names = c(NA, -6L), class = c("tbl_df", "tbl",
"data.frame"))
</code>```

Thanks in advance! (I'm about to hate emoticons :) )

Edit with output following answer by J_F and sessionInfo

```<code>foo$name_emoji <- as.factor(foo$name_emoji)
foo$emoji <- as.factor(foo$emoji)

ggplot(foo, aes(name_emoji, n)) +
  geom_bar(stat = "identity") +
  scale_x_discrete(breaks = foo$name_emoji, labels = foo$emoji) +
  coord_flip()
</code>```

This is my session:

```<code>R version 3.4.3 (2017-11-30)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.1

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

locale:
[1] es_ES.UTF-8/es_ES.UTF-8/es_ES.UTF-8/C/es_ES.UTF-8/es_ES.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets
[6] methods   base

other attached packages:
 [1] emo_0.0.0.9000     emojifont_0.5.1
 [3] DataCombine_0.2.21 forcats_0.2.0
 [5] stringr_1.2.0      dplyr_0.7.4
 [7] purrr_0.2.4        readr_1.1.1
 [9] tidyr_0.7.2        tibble_1.3.4
[11] ggplot2_2.2.1      tidyverse_1.2.1

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.14        lubridate_1.7.1
 [3] lattice_0.20-35     twitteR_1.1.9
 [5] sysfonts_0.7.1      assertthat_0.2.0
 [7] digest_0.6.12       psych_1.7.8
 [9] mime_0.5            R6_2.2.2
[11] cellranger_1.1.0    plyr_1.8.4
[13] httr_1.3.1          rlang_0.1.4
[15] lazyeval_0.2.1      readxl_1.0.0
[17] rstudioapi_0.7      data.table_1.10.4-3
[19] miniUI_0.1.1        proto_1.0.0
[21] labeling_0.3        foreign_0.8-69
[23] bit_1.1-12          munsell_0.4.3
[25] shiny_1.0.5         broom_0.4.3
[27] compiler_3.4.3      httpuv_1.3.5
[29] modelr_0.1.1        pkgconfig_2.0.1
[31] mnormt_1.5-5        htmltools_0.3.6
[33] crayon_1.3.4        showtextdb_2.0
[35] grid_3.4.3          xtable_1.8-2
[37] nlme_3.1-131        jsonlite_1.5
[39] gtable_0.2.0        DBI_0.7
[41] magrittr_1.5        scales_0.5.0
[43] cli_1.0.0           stringi_1.1.6
[45] reshape2_1.4.2      bindrcpp_0.2
[47] xml2_1.1.1          rjson_0.2.15
[49] tools_3.4.3         showtext_0.5
[51] bit64_0.9-7         glue_1.2.0
[53] hms_0.4.0           parallel_3.4.3
[55] yaml_2.1.15         colorspace_1.3-2
[57] rvest_0.3.2         bindr_0.1
[59] haven_1.1.0
</code>```

答:
I tried the following:

```<code>foo$name_emoji <- as.factor(foo$name_emoji)
foo$emoji <- as.factor(foo$emoji)

ggplot(foo, aes(name_emoji, n)) +
  geom_bar(stat = "identity") +
  scale_x_discrete(breaks = foo$name_emoji, labels = foo$emoji) +
  coord_flip()
</code>```

ContentLicense: CC BY-SA 3.0

Title: Plot emojis/emoticons in R with ggplot

Body:
I'm trying to make a plot with emojis in ggplot2. What I want is to show emojis instead of labels or show like geom. This question in Stack is very similar to my problem, but it does not solve it either, the answer is quite manual and I need to make automatic (my real data frame has 3000 rows).

Just to clarify in this plot below I want to show emojis instead of text labels or within the bars. But seems impossible.

After trying differents solutions I'm stacked so any help would be appreciated. I read different ways to face the problem like here, here, here.

My last try was like this:

mult_format <- function() {
  function(x) emo::ji(x)
}
ggplot(foo, aes(name_emoji, n)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  scale_y_continuous(labels = mult_format())

But it doesn't work.

My data looks like this, name_emoji cames from emo package, and I also can change it to byte:

               name_emoji     n        emoji
                    <chr> <int>        <chr>
 1            closed book     1 "\U0001f4d5"
 2          confused face     7 "\U0001f615"
 3                  dizzy     20 "\U0001f4ab"
 4 face with tears of joy     1 "\U0001f602"
 5          flexed biceps     1 "\U0001f4aa"
 6             light bulb     1 "\U0001f4a1"

Here to reproduce:

structure(list(name_emoji = c("closed book", "confused face",
"dizzy", "face with tears of joy", "flexed biceps", "light bulb"
), n = c(1L, 7L, 20L, 1L, 1L, 1L), emoji = c("\U0001f4d5", "\U0001f615",
"\U0001f4ab", "\U0001f602", "\U0001f4aa", "\U0001f4a1")), .Names = c("name_emoji",
"n", "emoji"), row.names = c(NA, -6L), class = c("tbl_df", "tbl",
"data.frame"))

Thanks in advance! (I'm about to hate emoticons :) )

Edit with output following answer by J_F and sessionInfo

foo$name_emoji <- as.factor(foo$name_emoji)
foo$emoji <- as.factor(foo$emoji)

ggplot(foo, aes(name_emoji, n)) +
  geom_bar(stat = "identity") +
  scale_x_discrete(breaks = foo$name_emoji, labels = foo$emoji) +
  coord_flip()

This is my session:

R version 3.4.3 (2017-11-30)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.1

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

locale:
[1] es_ES.UTF-8/es_ES.UTF-8/es_ES.UTF-8/C/es_ES.UTF-8/es_ES.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets
[6] methods   base

other attached packages:
 [1] emo_0.0.0.9000     emojifont_0.5.1
 [3] DataCombine_0.2.21 forcats_0.2.0
 [5] stringr_1.2.0      dplyr_0.7.4
 [7] purrr_0.2.4        readr_1.1.1
 [9] tidyr_0.7.2        tibble_1.3.4
[11] ggplot2_2.2.1      tidyverse_1.2.1

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.14        lubridate_1.7.1
 [3] lattice_0.20-35     twitteR_1.1.9
 [5] sysfonts_0.7.1      assertthat_0.2.0
 [7] digest_0.6.12       psych_1.7.8
 [9] mime_0.5            R6_2.2.2
[11] cellranger_1.1.0    plyr_1.8.4
[13] httr_1.3.1          rlang_0.1.4
[15] lazyeval_0.2.1      readxl_1.0.0
[17] rstudioapi_0.7      data.table_1.10.4-3
[19] miniUI_0.1.1        proto_1.0.0
[21] labeling_0.3        foreign_0.8-69
[23] bit_1.1-12          munsell_0.4.3
[25] shiny_1.0.5         broom_0.4.3
[27] compiler_3.4.3      httpuv_1.3.5
[29] modelr_0.1.1        pkgconfig_2.0.1
[31] mnormt_1.5-5        htmltools_0.3.6
[33] crayon_1.3.4        showtextdb_2.0
[35] grid_3.4.3          xtable_1.8-2
[37] nlme_3.1-131        jsonlite_1.5
[39] gtable_0.2.0        DBI_0.7
[41] magrittr_1.5        scales_0.5.0
[43] cli_1.0.0           stringi_1.1.6
[45] reshape2_1.4.2      bindrcpp_0.2
[47] xml2_1.1.1          rjson_0.2.15
[49] tools_3.4.3         showtext_0.5
[51] bit64_0.9-7         glue_1.2.0
[53] hms_0.4.0           parallel_3.4.3
[55] yaml_2.1.15         colorspace_1.3-2
[57] rvest_0.3.2         bindr_0.1
[59] haven_1.1.0

Body:
I tried the following:

foo$name_emoji <- as.factor(foo$name_emoji)
foo$emoji <- as.factor(foo$emoji)

ggplot(foo, aes(name_emoji, n)) +
  geom_bar(stat = "identity") +
  scale_x_discrete(breaks = foo$name_emoji, labels = foo$emoji) +
  coord_flip()


问:
Python Intercept Web Traffic from Browser
I'm trying to create a simple web filtering app in python. The way I want to do this is to monitor traffic on ports tcp 80/443 (http) and if there is traffic, I want to check something before I let it go through. If it fails the check, I would like for the user to be redirected to a page of my choosing.

So my question is, when the user visits http://www.google.com in the browser, is there a way that I can intercept that request, and is there a way I can redirect them to another page by my choosing?

答:
You need to write a web proxy, and set your web clients proxy server to http://localhost:8000/ (or whatever the proxy is listening on).

Your web client will then send HTTP like this:

GET http://www.google.com

to your proxy which it must then rewrite as:

GET /

and send on to www.google.com, getting the response and then sending it back on the original socket to the client. Note that explanation is massively simplified.

Anyway, its all standard stuff and I suspect Python web proxies exist already for you to hack on.

Edit: http://proxies.xhaus.com/python/

ContentLicense: CC BY-SA 2.5


问:
What is the default textarea name for Summernote?
Can someone help me with the default textarea name value for Summernote?  The editor looks correct on the page (I can modify text using the interface) but POST isn't working based on my understanding.

I've tried a variety of POST variables but none of them seem correct.  Examples are summernote, note-codable and text-area.  The last two came from summernote.js.  Jquery isn't something that I have much experience with, so please baby-step me.

These are what I am using.

```<code> $('#summernote').summernote({height: 300});
 var sHTML = $('#summernote').code();
</code>```

and

```<code> <div name="summernote" id="summernote"><?php echo $news_body; ?></div>
</code>```

I've also tried the lines below separately in an attempt to change the textarea name to content:

```<code>var sHTML = $('#summernote').code();
$('#summernote').code();
var content = $('textarea[name="content"]').html($('#summernote').code());
$('textarea[name="content"]').html($('#summernote').code());
var sHTML =  $('textarea[name="content"]').html($('#summernote').code());
var textareaValue = $("#content").code();
$("summernote").code(html);
</code>```

答:
Try this:</p>

```<code>var sHTML = $('.summernote').summernote('code')
</code>```

Body:
Can someone help me with the default textarea name value for Summernote?  The editor looks correct on the page (I can modify text using the interface) but POST isn't working based on my understanding.

I've tried a variety of POST variables but none of them seem correct.  Examples are summernote, note-codable and text-area.  The last two came from summernote.js.  Jquery isn't something that I have much experience with, so please baby-step me.

These are what I am using.

 $('#summernote').summernote({height: 300});
 var sHTML = $('#summernote').code();

and

<?php echo $news_body; ?>

I've also tried the lines below separately in an attempt to change the textarea name to content:

var sHTML = $('#summernote').code();
$('#summernote').code();
var content = $('textarea[name="content"]').html($('#summernote').code());
$('textarea[name="content"]').html($('#summernote').code());
var sHTML =  $('textarea[name="content"]').html($('#summernote').code());
var textareaValue = $("#content").code();
$("summernote").code(html);

Body:
Try this:

var sHTML = $('.summernote').summernote('code')


问:
Dynamically alloc size of array based on user input in C
I'm new to C so I'm having a little trouble handling everything Java already did for me in the background.
Basically what I would like to achieve is this:

Declare an array of char with no specified size

Ask to the user a string in input (single word or phrase)

Set the previous array of char with size of the length of the input string (dynamically)

Put the inputed string inside the char array

I've tried using scanf but it doesn't seem to handle string as an array of char(?) so I'm not able to work on the variable
I've also read about malloc() functions which dynamically allocates space for an array so I could use it to set the size of the array as the strlen of the string and then put '\0' at the end (just like .asciiz in some assembly language) but I can't figure out how to correlate malloc and input string.
Any help would be appreciated!
Thanks for your attention

答:
You can use getline to read an entire line and not have to worry about managing memory during that read. The function was only standardized in POSIX.1-2008, so if you’re using glibc you’ll need to compile with -D_POSIX_C_SOURCE=200809L, for example.

To summarize the linked documentation: getline takes a pointer to a string, and will allocate memory entirely for you if the string is NULL and the size is 0. It returns −1 if it fails to allocate memory (e.g. there’s more input than free memory) or if the end of the input is reached immediately. You always have to free the memory allocated in this way, even if it fails.

```<code>#include <stdio.h>
#include <stdlib.h>

int main(void) {
    size_t input_size = 0;
    char* input_line = NULL;

    if (getline(&input_line, &input_size, stdin) == -1) {
        free(input_line);
        perror("Failed to read input");
        return EXIT_FAILURE;
    }

    printf("Got input: '%s'\n", input_line);
    free(input_line);
}
</code>```

Body:
You can use getline to read an entire line and not have to worry about managing memory during that read. The function was only standardized in POSIX.1-2008, so if you’re using glibc you’ll need to compile with -D_POSIX_C_SOURCE=200809L, for example.

To summarize the linked documentation: getline takes a pointer to a string, and will allocate memory entirely for you if the string is NULL and the size is 0. It returns −1 if it fails to allocate memory (e.g. there’s more input than free memory) or if the end of the input is reached immediately. You always have to free the memory allocated in this way, even if it fails.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    size_t input_size = 0;
    char* input_line = NULL;

    if (getline(&input_line, &input_size, stdin) == -1) {
        free(input_line);
        perror("Failed to read input");
        return EXIT_FAILURE;
    }

    printf("Got input: '%s'\n", input_line);
    free(input_line);
}


问:
Model binding with inheritance in Asp.Core
I need to accept list of objects from user:

```<code>public async Task<IActionResult> CreateArticle(List<InformationBlockModel> informationBlocks)
    {
        ...
    }
</code>```

ModelBinder should determine concrete types, but when I trying to cast InformationBlock to TextInformationBlock, exception throws.

Hierarchy:

```<code>public class InformationBlockModel
{
    public virtual InformationBlockType Type { get; set; }
}

public class TextInformationBlockModel : InformationBlockModel
{
    public string Text { get; set; }

    public override InformationBlockType Type { get; set; } = InformationBlockType.Text;
}

public class ImageInformationBlockModel : InformationBlockModel
{
    public override InformationBlockType Type { get; set; } = InformationBlockType.Image;
    public string Name { get; set; }
}
</code>```

答:
Finally, I found a solution:

Startup.cs

```<code>services.AddMvc()
    .AddJsonOptions(options => options.SerializerSettings.Converters.Add(new InformationBlockConverter()));
</code>```

JsonCreationConverter.cs

```<code>public abstract class JsonCreationConverter<T> : JsonConverter
{
    public override bool CanWrite { get; } = false;

    public override bool CanRead { get; } = true;

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
    }

    protected abstract T Create(Type objectType, JObject jObject);

    public override bool CanConvert(Type objectType)
    {
        return typeof(T) == objectType;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
        JsonSerializer serializer)
    {
        var jObject = JObject.Load(reader);

        var target = Create(objectType, jObject);

        serializer.Populate(jObject.CreateReader(), target);

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

InformationBlockConverter

```<code>public class InformationBlockConverter : JsonCreationConverter<InformationBlockModel>
{
    private readonly Dictionary<InformationBlockType, Type> _types = new Dictionary<InformationBlockType, Type>
    {
        {InformationBlockType.Text, typeof(TextInformationBlockModel)},
        {InformationBlockType.Image, typeof(ImageInformationBlockModel)},
        {InformationBlockType.Video, typeof(VideoInformationBlockModel)}
    };

    protected override InformationBlockModel Create(Type objectType, JObject jObject)
    {
        return (InformationBlockModel) jObject.ToObject(_types[Enum.Parse<InformationBlockType>(
            jObject.GetValue("type", StringComparison.InvariantCultureIgnoreCase).Value<string>(), true)]);
    }
}
</code>```

InformationBlockType

```<code>public enum InformationBlockType
{
    Text,
    Image,
    Video
}
</code>```

Body:
I need to accept list of objects from user:

public async Task<IActionResult> CreateArticle(List<InformationBlockModel> informationBlocks)
    {
        ...
    }

ModelBinder should determine concrete types, but when I trying to cast InformationBlock to TextInformationBlock, exception throws.

Hierarchy:

public class InformationBlockModel
{
    public virtual InformationBlockType Type { get; set; }
}

public class TextInformationBlockModel : InformationBlockModel
{
    public string Text { get; set; }

    public override InformationBlockType Type { get; set; } = InformationBlockType.Text;
}

public class ImageInformationBlockModel : InformationBlockModel
{
    public override InformationBlockType Type { get; set; } = InformationBlockType.Image;
    public string Name { get; set; }
}

Body:
Finally, I found a solution:

Startup.cs

services.AddMvc()
    .AddJsonOptions(options => options.SerializerSettings.Converters.Add(new InformationBlockConverter()));

JsonCreationConverter.cs

public abstract class JsonCreationConverter<T> : JsonConverter
{
    public override bool CanWrite { get; } = false;

    public override bool CanRead { get; } = true;

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
    }

    protected abstract T Create(Type objectType, JObject jObject);

    public override bool CanConvert(Type objectType)
    {
        return typeof(T) == objectType;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
        JsonSerializer serializer)
    {
        var jObject = JObject.Load(reader);

        var target = Create(objectType, jObject);

        serializer.Populate(jObject.CreateReader(), target);

        return target;
    }
}

InformationBlockConverter

public class InformationBlockConverter : JsonCreationConverter<InformationBlockModel>
{
    private readonly Dictionary<InformationBlockType, Type> _types = new Dictionary<InformationBlockType, Type>
    {
        {InformationBlockType.Text, typeof(TextInformationBlockModel)},
        {InformationBlockType.Image, typeof(ImageInformationBlockModel)},
        {InformationBlockType.Video, typeof(VideoInformationBlockModel)}
    };

    protected override InformationBlockModel Create(Type objectType, JObject jObject)
    {
        return (InformationBlockModel) jObject.ToObject(_types[Enum.Parse<InformationBlockType>(
            jObject.GetValue("type", StringComparison.InvariantCultureIgnoreCase).Value<string>(), true)]);
    }
}

InformationBlockType

public enum InformationBlockType
{
    Text,
    Image,
    Video
}


问:
tensorflow: "trying to mutate a frozen object", bazel
MacOS high sierra, MBP 2016, in terminal.

I'm following the directions here:
https://github.com/tensorflow/models/tree/master/research/syntaxnet
All options for ./configure chosen as default (and all python directories double-checked.). All steps have completed cleanly until this:

```<code>bazel test ...
# On Mac, run the following:
bazel test --linkopt=-headerpad_max_install_names \
  dragnn/... syntaxnet/... util/utf8/...
</code>```

I assume I'm supposed to run the latter line ("bazel test --linkopt" etc.).  But I get the same result either way, interestingly.

This throws about 10 errors, each of the same type "trying to mutate a frozen object", and concludes tests not run, error loading package dragnn/protos, and couldn't start build.

This is the general form of the errors:

syntaxnet>> bazel test --linkopt=-headerpad_max_install_names
  dragnn/... syntaxnet/... util/utf8/...

.

ERROR:
  /Users/XXX/Desktop/NLP/syntaxnet/models/research/syntaxnet/dragnn/protos/BUILD:35:1:
  Traceback (most recent call last): File
  "/Users/XXX/Desktop/NLP/syntaxnet/models/research/syntaxnet/dragnn/protos/BUILD",
  line 35 tf_proto_library_py(name = "data_py_pb2", srcs = ["dat..."])
  File
  "/Users/XXX/Desktop/NLP/syntaxnet/models/research/syntaxnet/syntaxnet/syntaxnet.bzl",
  line 53, in tf_proto_library_py py_proto_library(name = name, srcs =
  srcs, srcs_versi...", <5 more arguments>) File
  "/private/var/tmp/_bazel_XXX/f74e5a21c3ad09aeb110d9de15110035/external/protobuf_archive/protobuf.bzl",
  line 374, in py_proto_library py_libs += [default_runtime] trying to
  mutate a frozen object ERROR: package contains errors: dragnn/protos

... [same error for various 'name = "...pb2"' files] ...

INFO: Elapsed time: 0.709s FAILED: Build did NOT complete successfully
  (17 packages loaded) ERROR: Couldn't start the build. Unable to run
  tests

Any idea what could be doing this?  Thanks.

答:
```<code>Tried same pattern patch for cc_libs.

  if default_runtime and not default_runtime in cc_libs:
    cc_libs2 = cc_libs + [default_runtime]
  else:
    cc_libs2 = cc_libs
  if use_grpc_plugin:
    cc_libs += ["//external:grpc_lib"]

  native.cc_library(
      name=name,
      srcs=gen_srcs,
      hdrs=gen_hdrs,
      deps=cc_libs2 + deps,
      includes=includes,
      **kargs)
</code>```

Shows new error, but keeps compiling. (Ubuntu 16 on Windows System for Linux--don't ask, native tensorflow 1.4 winx64 works, but not syntaxnet).

greg@FX11:/mnt/c/code/models/research/syntaxnet$ bazel test ...
ERROR: /home/greg/.cache/bazel/_bazel_greg/adb8eb0eab8b9680449366fbebe59ec2/external/org_tensorflow/tensorflow/core/kernels/BUILD:451:1: in _transitive_hdrs rule @org_tensorflow//tensorflow/core/kernels:bounds_check_lib_gather:
Traceback (most recent call last):
        File "/home/greg/.cache/bazel/_bazel_greg/adb8eb0eab8b9680449366fbebe59ec2/external/org_tensorflow/tensorflow/core/kernels/BUILD", line 451
                _transitive_hdrs(name = 'bounds_check_lib_gather')
        File "/home/greg/.cache/bazel/_bazel_greg/adb8eb0eab8b9680449366fbebe59ec2/external/org_tensorflow/tensorflow/tensorflow.bzl", line 869, in _transitive_hdrs_impl
                set()

Just changed set() to depset() and that seems to have avoided the error.

Body:
MacOS high sierra, MBP 2016, in terminal.

I'm following the directions here:
https://github.com/tensorflow/models/tree/master/research/syntaxnet
All options for ./configure chosen as default (and all python directories double-checked.). All steps have completed cleanly until this:

bazel test ...
# On Mac, run the following:
bazel test --linkopt=-headerpad_max_install_names \
  dragnn/... syntaxnet/... util/utf8/...

I assume I'm supposed to run the latter line ("bazel test --linkopt" etc.).  But I get the same result either way, interestingly.

This throws about 10 errors, each of the same type "trying to mutate a frozen object", and concludes tests not run, error loading package dragnn/protos, and couldn't start build.

This is the general form of the errors:

syntaxnet>> bazel test --linkopt=-headerpad_max_install_names
  dragnn/... syntaxnet/... util/utf8/...

.

ERROR:
  /Users/XXX/Desktop/NLP/syntaxnet/models/research/syntaxnet/dragnn/protos/BUILD:35:1:
  Traceback (most recent call last): File
  "/Users/XXX/Desktop/NLP/syntaxnet/models/research/syntaxnet/dragnn/protos/BUILD",
  line 35 tf_proto_library_py(name = "data_py_pb2", srcs = ["dat..."])
  File
  "/Users/XXX/Desktop/NLP/syntaxnet/models/research/syntaxnet/syntaxnet/syntaxnet.bzl",
  line 53, in tf_proto_library_py py_proto_library(name = name, srcs =
  srcs, srcs_versi...", <5 more arguments>) File
  "/private/var/tmp/_bazel_XXX/f74e5a21c3ad09aeb110d9de15110035/external/protobuf_archive/protobuf.bzl",
  line 374, in py_proto_library py_libs += [default_runtime] trying to
  mutate a frozen object ERROR: package contains errors: dragnn/protos

... [same error for various 'name = "...pb2"' files] ...

INFO: Elapsed time: 0.709s FAILED: Build did NOT complete successfully
  (17 packages loaded) ERROR: Couldn't start the build. Unable to run
  tests

Any idea what could be doing this?  Thanks.

Body:
Tried same pattern patch for cc_libs.

  if default_runtime and not default_runtime in cc_libs:
    cc_libs2 = cc_libs + [default_runtime]
  else:
    cc_libs2 = cc_libs
  if use_grpc_plugin:
    cc_libs += ["//external:grpc_lib"]

  native.cc_library(
      name=name,
      srcs=gen_srcs,
      hdrs=gen_hdrs,
      deps=cc_libs2 + deps,
      includes=includes,
      **kargs)

Shows new error, but keeps compiling. (Ubuntu 16 on Windows System for Linux--don't ask, native tensorflow 1.4 winx64 works, but not syntaxnet).

greg@FX11:/mnt/c/code/models/research/syntaxnet$ bazel test ...
ERROR: /home/greg/.cache/bazel/_bazel_greg/adb8eb0eab8b9680449366fbebe59ec2/external/org_tensorflow/tensorflow/core/kernels/BUILD:451:1: in _transitive_hdrs rule @org_tensorflow//tensorflow/core/kernels:bounds_check_lib_gather:
Traceback (most recent call last):
        File "/home/greg/.cache/bazel/_bazel_greg/adb8eb0eab8b9680449366fbebe59ec2/external/org_tensorflow/tensorflow/core/kernels/BUILD", line 451
                _transitive_hdrs(name = 'bounds_check_lib_gather')
        File "/home/greg/.cache/bazel/_bazel_greg/adb8eb0eab8b9680449366fbebe59ec2/external/org_tensorflow/tensorflow/tensorflow.bzl", line 869, in _transitive_hdrs_impl
                set()

Just changed set() to depset() and that seems to have avoided the error.


问:
Google Maps only display name of place, no map layer in Android Emulator
I'm learning display google map in Android now. Just a very simple application for display google map in main activity.

Map display has no problem in real hardware(Samsung Galaxy C5). But it cannot display map layer in Android emulator.

I tried API 19, 23 and 25, same result. Please see screenshot. Anyone know why? Thanks.

Screenshot: map in api 23

Screenshot: error

Here is my AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.zhongjiefan.mapsapp">

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<permission
    android:name="com.example.zhongjiefan.mapsapp.permission.MAPS_RECEIVE"
    android:protectionLevel="signature"/>

<uses-permission android:name="com.example.zhongjiefan.mapsapp.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permissions.READ_GSERVICES"/>
<uses-feature android:glEsVersion="0x00020000"
              android:required="true" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>

    <meta-data android:name="com.google.android.maps.v2.API_KEY"
               android:value="--removed--"/>

    <meta-data android:name="com.google.android.gms.version"
               android:value="@integer/google_play_services_version"/>
</application>

</manifest>
</code>```

Here is my activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context="com.example.zhongjiefan.mapsapp.MainActivity">

    <fragment
        android:id="@+id/mapFragment"
        android:name="com.google.android.gms.maps.MapFragment"
        android:layout_width="368dp"
        android:layout_height="495dp"
        android:layout_margin="8dp"
        tools:layout_editor_absoluteY="8dp"
        tools:layout_editor_absoluteX="8dp"/>

</LinearLayout>
</code>```

Here is my MainActivity.java

```<code>package com.example.zhongjiefan.mapsapp;

import android.app.Dialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {

GoogleMap mGoogleMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(googleServicesAvailable()) {

        Toast.makeText(this, "Perfect!", Toast.LENGTH_LONG).show();
        setContentView(R.layout.activity_main);
        initMap();

    } else {

        // No google maps layout
    }
}

private void initMap() {
    MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapFragment);
    mapFragment.getMapAsync(this);
}

public boolean googleServicesAvailable() {
    GoogleApiAvailability api = GoogleApiAvailability.getInstance();
    int isAvailable = api.isGooglePlayServicesAvailable(this);

    if(isAvailable == ConnectionResult.SUCCESS) {

        return true;
    }
    else if(api.isUserResolvableError(isAvailable)) {
        Dialog dialog = api.getErrorDialog(this, isAvailable, 0);
        dialog.show();

    }else {
        Toast.makeText(this, "Can't connection to play services", Toast.LENGTH_LONG).show();
    }
    return false;
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mGoogleMap = googleMap;
}
}
</code>```

答: Still don't know the root cause. But once I changed a computer and run it. It works fine. Maybe it's caused by graphical card driver or other things.</p>

Body:
I'm learning display google map in Android now. Just a very simple application for display google map in main activity.

Map display has no problem in real hardware(Samsung Galaxy C5). But it cannot display map layer in Android emulator.

I tried API 19, 23 and 25, same result. Please see screenshot. Anyone know why? Thanks.

Screenshot: map in api 23

Screenshot: error

Here is my AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.zhongjiefan.mapsapp">

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<permission
    android:name="com.example.zhongjiefan.mapsapp.permission.MAPS_RECEIVE"
    android:protectionLevel="signature"/>

<uses-permission android:name="com.example.zhongjiefan.mapsapp.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permissions.READ_GSERVICES"/>
<uses-feature android:glEsVersion="0x00020000"
              android:required="true" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>

    <meta-data android:name="com.google.android.maps.v2.API_KEY"
               android:value="--removed--"/>

    <meta-data android:name="com.google.android.gms.version"
               android:value="@integer/google_play_services_version"/>
</application>

</manifest>

Here is my activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context="com.example.zhongjiefan.mapsapp.MainActivity">

    <fragment
        android:id="@+id/mapFragment"
        android:name="com.google.android.gms.maps.MapFragment"
        android:layout_width="368dp"
        android:layout_height="495dp"
        android:layout_margin="8dp"
        tools:layout_editor_absoluteY="8dp"
        tools:layout_editor_absoluteX="8dp"/>

</LinearLayout>

Here is my MainActivity.java

package com.example.zhongjiefan.mapsapp;

import android.app.Dialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {

GoogleMap mGoogleMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(googleServicesAvailable()) {

        Toast.makeText(this, "Perfect!", Toast.LENGTH_LONG).show();
        setContentView(R.layout.activity_main);
        initMap();

    } else {

        // No google maps layout
    }
}

private void initMap() {
    MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapFragment);
    mapFragment.getMapAsync(this);
}

public boolean googleServicesAvailable() {
    GoogleApiAvailability api = GoogleApiAvailability.getInstance();
    int isAvailable = api.isGooglePlayServicesAvailable(this);

    if(isAvailable == ConnectionResult.SUCCESS) {

        return true;
    }
    else if(api.isUserResolvableError(isAvailable)) {
        Dialog dialog = api.getErrorDialog(this, isAvailable, 0);
        dialog.show();

    }else {
        Toast.makeText(this, "Can't connection to play services", Toast.LENGTH_LONG).show();
    }
    return false;
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mGoogleMap = googleMap;
}
}


问:
gcloud command not found - while installing Google Cloud SDK
I am on a mac and am trying to install the Google Cloud SDK (including the gcloud command line utility) using this command in terminal

```<code>curl https://sdk.cloud.google.com | bash
</code>```

as seen at https://cloud.google.com/sdk/

It got all the way to the end and finished but even after I restarted my shell, the gcloud command still says it's not found.

Why isn't this installation working?

答:
You just have to execute this command as root

```<code>$ curl https://sdk.cloud.google.com | bash
</code>```

Restart the terminal and that's it. Now all commands should be executed as root

Body:
I am on a mac and am trying to install the Google Cloud SDK (including the gcloud command line utility) using this command in terminal

curl https://sdk.cloud.google.com | bash

as seen at https://cloud.google.com/sdk/

It got all the way to the end and finished but even after I restarted my shell, the gcloud command still says it's not found.

Why isn't this installation working?

Body:
You just have to execute this command as root

$ curl https://sdk.cloud.google.com | bash

Restart the terminal and that's it. Now all commands should be executed as root


问:
Copying table cells to clipboard without input tags - Javascript and html
I have this simple function that allows you to click any table cell and it copies the data to the clipboard.  The cell will also blink red to let you know it was copied. This works fine, but you'll notice there's an input tag in each cell (all the similar examples I found also used inputs or some other form tags) I don't need inputs because the data in my cells isn't going to change.  Is there a way to do this without input tags.  Would the data in a normal table cell be innerHTML Can that be copied onclick? No jQuery please.

function myFunction(itemid) {
  var copyText = document.getElementById(itemid);
  copyText.select();
  document.execCommand("Copy");
  // blink red
  document.getElementById(itemid).style.backgroundColor="#FF0000";
  setTimeout(function(){document.getElementById(itemid).style.backgroundColor="#FFFFFF";},300);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>::selection {background:none;}
input {outline:0;cursor:pointer}</code>```

<input type="text" value="Cheese" id="cell1" onclick="myFunction('cell1')">
<input type="text" value="Crackers" id="cell2" onclick="myFunction('cell2')">

<input type="text" value="Milk" id="cell3" onclick="myFunction('cell3')">
<input type="text" value="Bread" id="cell4" onclick="myFunction('cell4')">

```

答:
try this, the animation is up to you</p>

```<code>        let table = document.getElementById('tableId');

    table.addEventListener('click', (e) => {
        let target = e.target;
        if(target.localName === 'td') {
            let range = document.createRange();
            range.selectNodeContents(target);
            let sel= document.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);

            document.execCommand('copy');
            sel.removeAllRanges();
            target.classList.add('copy-animate');
            setTimeout(() => {
                target.classList.remove('copy-animate');
            }, 200);
        }
    });
</code>```

Body:
I have this simple function that allows you to click any table cell and it copies the data to the clipboard.  The cell will also blink red to let you know it was copied. This works fine, but you'll notice there's an input tag in each cell (all the similar examples I found also used inputs or some other form tags) I don't need inputs because the data in my cells isn't going to change.  Is there a way to do this without input tags.  Would the data in a normal table cell be innerHTML Can that be copied onclick? No jQuery please.

function myFunction(itemid) {
  var copyText = document.getElementById(itemid);
  copyText.select();
  document.execCommand("Copy");
  // blink red
  document.getElementById(itemid).style.backgroundColor="#FF0000";
  setTimeout(function(){document.getElementById(itemid).style.backgroundColor="#FFFFFF";},300);
}

::selection {background:none;}
input {outline:0;cursor:pointer}

<input type="text" value="Cheese" id="cell1" onclick="myFunction('cell1')">
<input type="text" value="Crackers" id="cell2" onclick="myFunction('cell2')">

<input type="text" value="Milk" id="cell3" onclick="myFunction('cell3')">
<input type="text" value="Bread" id="cell4" onclick="myFunction('cell4')">

Body:
try this, the animation is up to you

        let table = document.getElementById('tableId');

    table.addEventListener('click', (e) => {
        let target = e.target;
        if(target.localName === 'td') {
            let range = document.createRange();
            range.selectNodeContents(target);
            let sel= document.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);

            document.execCommand('copy');
            sel.removeAllRanges();
            target.classList.add('copy-animate');
            setTimeout(() => {
                target.classList.remove('copy-animate');
            }, 200);
        }
    });


问:
Don't understand why my multiplication isn't working?
I'm trying to make a temperature conversion function for a class assignment, and my function receives all of the arguments correctly but for some reason after it hits the equation to convert the number it just makes the number 0.

Here is the code so you know what I'm talking about:

```<code>void convertToCelsius(int farenheitTemperature, int temperatureType){

if (temperatureType == 1)
{

farenheitTemperature = ((5/9) * (farenheitTemperature - 32));
printf("Your temperature in Celsius is %i\n", farenheitTemperature);

}

else
{
    printf("Your temperature is already in celsius!\n");
}
}
</code>```

the main function puts the arguments in correctly, so I don't think that's the problem.

Thank you very much for any help you can give!

答:
Use type double not int for your temperature parameter.

```<code>void convertToCelsius(double farenheitTemperature, int temperatureType)
{
    if (temperatureType == 1)
    {
        farenheitTemperature = ((5.0/9.0) * (farenheitTemperature - 32.0));
        printf("Your temperature in Celsius is %f\n", farenheitTemperature);
    }
    else
    {
        printf("Your temperature is already in celsius!\n");
    }
}
</code>```

Body:
I'm trying to make a temperature conversion function for a class assignment, and my function receives all of the arguments correctly but for some reason after it hits the equation to convert the number it just makes the number 0.

Here is the code so you know what I'm talking about:

void convertToCelsius(int farenheitTemperature, int temperatureType){

if (temperatureType == 1)
{

farenheitTemperature = ((5/9) * (farenheitTemperature - 32));
printf("Your temperature in Celsius is %i\n", farenheitTemperature);

}

else
{
    printf("Your temperature is already in celsius!\n");
}
}

the main function puts the arguments in correctly, so I don't think that's the problem.

Thank you very much for any help you can give!

Body:
Use type double not int for your temperature parameter.

void convertToCelsius(double farenheitTemperature, int temperatureType)
{
    if (temperatureType == 1)
    {
        farenheitTemperature = ((5.0/9.0) * (farenheitTemperature - 32.0));
        printf("Your temperature in Celsius is %f\n", farenheitTemperature);
    }
    else
    {
        printf("Your temperature is already in celsius!\n");
    }
}


问:
Multipeerconnectivity on iOS with Xcode
Both devices advertising and browsing.
The problem occurs when trying the establish a connection.

```<code>func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {}
</code>```

Does working when trying to connect but after few seconds, it's been calling again with MCSessionState == .notConnected .

Tried both with WiFi, BT, and every combination in between...

Just added:

```<code><key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSTemporaryExceptionRequiresForwardSecrecy</key>
    <false/>
</dict>
</code>```

Did not helped much... Still getting in the console (just on the iOS 10.2 device, though...):

```<code>2017-02-06 15:17:37.858063 Advertiser[1149:316236] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
2017-02-06 15:17:39.727633 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:39.808822 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:39.948454 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:40.179569 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:40.591829 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:41.297454 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:42.547840 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:44.077537 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:45.601568 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:47.125030 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:48.110301 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [0].
2017-02-06 15:17:48.111331 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [1].
2017-02-06 15:17:48.111526 Advertiser[1149:316267] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
2017-02-06 15:17:48.111705 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [2].
2017-02-06 15:17:48.111873 Advertiser[1149:316267] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
2017-02-06 15:17:48.112042 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [3].
2017-02-06 15:17:48.113031 Advertiser[1149:316267] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
2017-02-06 15:17:48.121016 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [4].
2017-02-06 15:17:48.121321 Advertiser[1149:316267] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
2017-02-06 15:17:48.121506 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [5].
2017-02-06 15:17:48.121683 Advertiser[1149:316267] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
</code>```

(Advertiser is the name of the app)
Using iPhone 6S with 10.2 & iPhone 6 with 9.2.
Running code on Macbook Pro with macOS Sierra v10.12.2 from Xcode 8.2.1 (Swift3).

答:
I had the same problem and I found a solution. It still shows some errors but it works for me.

Try initialising MCSession as follows:

```<code>let mcSession = MCSession(peer: self.mcPeerId, securityIdentity: nil, encryptionPreference: .none)
</code>```

then implement MCSession's  certificate handler delegate method as follows:

```<code>func session(_ session: MCSession, didReceiveCertificate certificate: [Any]?, fromPeer peerID: MCPeerID, certificateHandler: @escaping (Bool) -> Void) {
    certificateHandler(true)
}
</code>```

Title: Multipeerconnectivity on iOS with Xcode

Body:
Both devices advertising and browsing.
The problem occurs when trying the establish a connection.

func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {}

Does working when trying to connect but after few seconds, it's been calling again with MCSessionState == .notConnected .

Tried both with WiFi, BT, and every combination in between...

Just added:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSTemporaryExceptionRequiresForwardSecrecy</key>
    <false/>
</dict>

Did not helped much... Still getting in the console (just on the iOS 10.2 device, though...):

2017-02-06 15:17:37.858063 Advertiser[1149:316236] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
2017-02-06 15:17:39.727633 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:39.808822 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:39.948454 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:40.179569 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:40.591829 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:41.297454 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:42.547840 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:44.077537 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:45.601568 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:47.125030 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:48.110301 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [0].
2017-02-06 15:17:48.111331 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [1].
2017-02-06 15:17:48.111526 Advertiser[1149:316267] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
2017-02-06 15:17:48.111705 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [2].
2017-02-06 15:17:48.111873 Advertiser[1149:316267] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
2017-02-06 15:17:48.112042 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [3].
2017-02-06 15:17:48.113031 Advertiser[1149:316267] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
2017-02-06 15:17:48.121016 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [4].
2017-02-06 15:17:48.121321 Advertiser[1149:316267] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
2017-02-06 15:17:48.121506 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [5].
2017-02-06 15:17:48.121683 Advertiser[1149:316267] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)

(Advertiser is the name of the app)
Using iPhone 6S with 10.2 & iPhone 6 with 9.2.
Running code on Macbook Pro with macOS Sierra v10.12.2 from Xcode 8.2.1 (Swift3).

Body:
I had the same problem and I found a solution. It still shows some errors but it works for me.

Try initialising MCSession as follows:

let mcSession = MCSession(peer: self.mcPeerId, securityIdentity: nil, encryptionPreference: .none)

then implement MCSession's  certificate handler delegate method as follows:

func session(_ session: MCSession, didReceiveCertificate certificate: [Any]?, fromPeer peerID: MCPeerID, certificateHandler: @escaping (Bool) -> Void) {
    certificateHandler(true)
}