问:
WebRTC video works locally but not remotely
There's quite a bit of code involved, so I threw what I had into a temporary github repo:

https://github.com/stevendesu/webrtc-failure

I'm learning WebRTC and long-term want to do some fancy stuff, but for now I'm starting simple: send a video from one computer to another. Unfortunately this failed. Here's what I've set up so far...

On a development server I own I installed coturn to act as a STUN/TURN server

I created two pages: broadcast.html and watch.html. The former creates a media stream and (using Socket.IO) sends the connection details to a signaling server. The latter gets the connection details from the signaling server and attempts to watch the stream

After running npm install you can npm start to run the server and access it at localhost:2017.

So here's what works:

After opening broadcast.html you are prompted for a broadcast ID. You can type anything here, but I usually just do an incrementing number - so I start with "1"

After entering a broadcast ID, and a short delay, you see your webcam feed on the screen. Looking at the console you can see several messages have been exchanged with the Socket.IO server

If you open watch.html in a new tab, you are prompted for a broadcast ID. Enter the same ID as before

After entering the ID, and a short delay, you will see your webcam feed on the new tab. Looking at the console you can see that the earlier ICE candidates and offer details were sent by the Socket.IO server and the watcher responded with an answer

Returning to the broadcast tab, you can verify that the answer was received and processed. A connection has now been established

For bonus points, the pc variable is in the global scope (PeerConnection) so in the console you can establish an RTCDataChannel and send messages between the tabs directly (bypassing the Socket.IO server)

Here's what doesn't work:

For now (and I know why this is, so it's not a concern) only the FIRST person to enter an ID into the watch.html page can actually see the broadcast. It's not "broadcast", it's just peer-to-peer, and once one connection has been established then future connections fail

My issue: if I open watch.html from a different computer or device (either on the same network or a different network) then the video never plays

In the latter case if you look at the console you'll see the offer and ice candidates are delivered to the watcher, the watcher generates an answer, the answer is sent back to the broadcaster, and the watcher sees a media stream added to the PeerConnection. This media stream is converted to a blob URL and assigned as the source of the video element.

I'm at a point where I don't know how to progress. I don't know why the video isn't showing up.

答:
your watch.js does not emit ice candidates. That is one possible cause. If that doesn't help you can use chrome://webrtc-internals to figure out what is going on -- see here for a description of how to interpret what is going on.

You might also want to look into modernizing your code. https://webrtc.github.io/samples/src/content/peerconnection/pc1/ is a fairly simple example of modern WebRTC code using promises and other things like using srcObject instead of the deprecated URL.createObjectURL.


来源: stackexchange

问:
How to add another textarea when inner text of first textarea exceed one page
Consider we're going to create a page containing a textarea for typing an article. the size of textarea is set to an A5 paper size. For long Texts when User types and completes the first textarea, It's required to add another textarea following to the first textarea to allow user continue typing in next page(something like MS word).
What's your suggestion?

.A5 {
  width: 148mm;
  padding: 1cm;
  margin: 1px;
  box-sizing: border-box;
  height: 210mm;
  border: solid 1px;
  resize: none;
  display: block;
}

@page {
  size: A5;
  margin: 0;
  padding: 0;
}

@media print {
  .A5 {
    visibility: visible;
    position: fixed;
    top:0;
    left:0;
    z-index: 99;
    border:none;
  }
  body> :not(.A5){
    color: red;
    display:none;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<h1>
Paper Print Test
</h1>
<input type="button" value="print" onclick="window.print()"/>
<textarea class="A5">
  Article Text
</textarea></code>```

答:
It might be better to avoid using textareas for this one and just use DIVs. It's a lot more flexible. You can create a pages DIV and simply add an 'absolute' positioned line every certain amount of distance, because you know the exact dimensions.

I've been looking at how Word online does this. They seem to use a DIV approach as well, but more complicated.

ContentLicense: CC BY-SA 3.0

Body:
Consider we're going to create a page containing a textarea for typing an article. the size of textarea is set to an A5 paper size. For long Texts when User types and completes the first textarea, It's required to add another textarea following to the first textarea to allow user continue typing in next page(something like MS word).
What's your suggestion?

.A5 {
  width: 148mm;
  padding: 1cm;
  margin: 1px;
  box-sizing: border-box;
  height: 210mm;
  border: solid 1px;
  resize: none;
  display: block;
}

@page {
  size: A5;
  margin: 0;
  padding: 0;
}

@media print {
  .A5 {
    visibility: visible;
    position: fixed;
    top:0;
    left:0;
    z-index: 99;
    border:none;
  }
  body> :not(.A5){
    color: red;
    display:none;
  }
}

Paper Print Test

<input type="button" value="print" onclick="window.print()"/>
<textarea class="A5">
  Article Text
</textarea>


问:
How to create a class which uses member functions defined in another class C++
I'm new to object oriented programming and am struggling a bit with how best to write classes.

I am trying to abstract the idea of sorting to objects that are not just lists of numbers. I have an abstract base class, SortableContainer, which contains all the necessary virtual functions for comparing and swapping elements, along with some overloaded operators. I then have two classes derived from that, MVector and CoordinateArray. Both of these derived classes have proper definitions for all the virtual functions in the base class. Everything up to this point has worked just fine. MVector just stores vector-like objects and CoordinateArray stores vectors of coordinates onto which a notion of 'less than' has been defined.

My problem now is that I have created a new class, Life, which I want to use to implement the game of life using a CoordinateArray object to store the alive cells. The outline of my Life class looks like this:

```<code>class Life
{
public:
   CoordinateArray LiveCells;

   Life();
};
</code>```

When I create a Life object and initialise it with the coordinates of some alive cells, none of the member functions defined in the CoordinateArray derived class will work. How can I fix this? Do I have to derive the Life class from the SortableContainer class and then override all the pure virtual functions? Any help or direction to help will be much appreciated.

答:
In order to initialize co-ordinates of some live cells declare the class CoordinateArray LiveCells public to Life</p>

```<code>class Life::public CoordinateArray{ }
</code>```

Body:
I'm new to object oriented programming and am struggling a bit with how best to write classes.

I am trying to abstract the idea of sorting to objects that are not just lists of numbers. I have an abstract base class, SortableContainer, which contains all the necessary virtual functions for comparing and swapping elements, along with some overloaded operators. I then have two classes derived from that, MVector and CoordinateArray. Both of these derived classes have proper definitions for all the virtual functions in the base class. Everything up to this point has worked just fine. MVector just stores vector-like objects and CoordinateArray stores vectors of coordinates onto which a notion of 'less than' has been defined.

My problem now is that I have created a new class, Life, which I want to use to implement the game of life using a CoordinateArray object to store the alive cells. The outline of my Life class looks like this:

class Life
{
public:
   CoordinateArray LiveCells;

   Life();
};

When I create a Life object and initialise it with the coordinates of some alive cells, none of the member functions defined in the CoordinateArray derived class will work. How can I fix this? Do I have to derive the Life class from the SortableContainer class and then override all the pure virtual functions? Any help or direction to help will be much appreciated.

Body:
In order to initialize co-ordinates of some live cells declare the class CoordinateArray LiveCells public to Life

class Life::public CoordinateArray{ }


问:
Why am I getting errors with my JavaScript?
I am trying to practice JavaScript with basic DOM manipulation but I keep getting 2 errors:

1.SyntaxError: missing ; before statement

2.TypeError: size is not a function

function size() {
  var height = document.body.getElementById('hover1').style.height: 500 px;
  var width = document.body.getElementById('hover1').style.width: 500 px;
}
console.log(hover);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <title>javascript practice</title>
  <meta charset="utf-8" />
  <style>
    body {
      margin: 7em auto;
      background-color: green;
      width: 90%;
    }

    #size1 {
      background-color: blue;
      width: 150px;
      height: 150px;
      margin: 3em auto;
    }
  </style>
</head>
<body>
  <div id="size1"></div>
  <input type="button" value="size" onclick="size();">
</body></code>```

答:
your error is here:

```<code>var height = document.body.getElementById('hover1').style.height: 500px;
var width = document.body.getElementById('hover1').style.width: 500px;
// -------------------^  and -------------------------------------^
</code>```

replace those lines with these:

```<code>var height = document.getElementById('hover1').style.height;
var width = document.getElementById('hover1').style.width;
</code>```

Body:
I am trying to practice JavaScript with basic DOM manipulation but I keep getting 2 errors:

1.SyntaxError: missing ; before statement

2.TypeError: size is not a function

function size() {
  var height = document.body.getElementById('hover1').style.height: 500 px;
  var width = document.body.getElementById('hover1').style.width: 500 px;
}
console.log(hover);

<!DOCTYPE html>

  <title>javascript practice</title>
  <meta charset="utf-8" />

  <input type="button" value="size" onclick="size();">

Body:
your error is here:

var height = document.body.getElementById('hover1').style.height: 500px;
var width = document.body.getElementById('hover1').style.width: 500px;
// -------------------^  and -------------------------------------^

replace those lines with these:

var height = document.getElementById('hover1').style.height;
var width = document.getElementById('hover1').style.width;


问:
Haskell Use guarded equation to create type
I want to create a type called TwoValued and it contains two values: a and b, and I'd like to make sure that a <= b

```<code>data TwoValued a b | a <= b = ValuePair a b
                   | otherwise = ValuePair b a
</code>```

But it's not working, I think guarded equation is not allowed here, so is there any other way to achieve what I want? Thanks.

答:
As far as I know, you can not define logic in a constructor. To put it bold, a constructor is used to discriminate between values, and to hold parameters.

You can however hide the constructor(s), and define functions to perform the construction. For example:

```<code>module Foo(TwoValued(), <b>twoValued</b>, firstValue, secondValue)

data TwoValued a = ValuePair { firstValue :: a, secondValue :: a}

<b>twoValued :: Ord a => a -> a -> TwoValued a
twoValued a b | a <= b = ValuePair a b
              | otherwise = ValuePair b a</b></code>```

So we define a data structure TwoValued and export it without the constructor (we write module Foo(TwoValued()), note module Foo(TwoValued(..))) as well as a function twoValued that acts like a constructor.

We can also export the getters firstValue :: TwoValued a -> a and secondValue :: TwoValued a -> a such that other modules can obtain the parameters.

ContentLicense: CC BY-SA 4.0

Body:
I want to create a type called TwoValued and it contains two values: a and b, and I'd like to make sure that a <= b

data TwoValued a b | a <= b = ValuePair a b
                   | otherwise = ValuePair b a

But it's not working, I think guarded equation is not allowed here, so is there any other way to achieve what I want? Thanks.

Body:
As far as I know, you can not define logic in a constructor. To put it bold, a constructor is used to discriminate between values, and to hold parameters.

You can however hide the constructor(s), and define functions to perform the construction. For example:

module Foo(TwoValued(), twoValued, firstValue, secondValue)

data TwoValued a = ValuePair { firstValue :: a, secondValue :: a}

twoValued :: Ord a => a -> a -> TwoValued a
twoValued a b | a <= b = ValuePair a b
              | otherwise = ValuePair b a

So we define a data structure TwoValued and export it without the constructor (we write module Foo(TwoValued()), note module Foo(TwoValued(..))) as well as a function twoValued that acts like a constructor.

We can also export the getters firstValue :: TwoValued a -> a and secondValue :: TwoValued a -> a such that other modules can obtain the parameters.


问:
Dynamically create .pdf file on server
I need to retrieve and then display a pdf file. I have working code that retrieves an image from a database, converts to .pdf, and returns that as JSON. I can display this just fine in chrome by making it into a blob, but because IE refuses to support data URIs, I figure I could generate a temporary pdf file on the server and then link to it like this, as suggested elsewhere on the site:

```<code><iframe style="width: 100%; height: 100%;" frameborder="0" scrolling="no" id="myFrame">
    <p>It appears your web browser doesn't support iframes.</p>
</iframe>
</code>```

And then set the src attribute in .js file:

```<code> $('#myFrame').attr('src', 'http://www.example.com/tempPDFname.pdf');
</code>```

How would I generate this file and make it available on server (C#) so I can set the src attribute?

答: "GhostScript" may help you. Please check the linkes How to use Ghostscript for converting PDF to Image and https://ghostscriptnet.codeplex.com/</p>

Title: Dynamically create .pdf file on server

Body:
I need to retrieve and then display a pdf file. I have working code that retrieves an image from a database, converts to .pdf, and returns that as JSON. I can display this just fine in chrome by making it into a blob, but because IE refuses to support data URIs, I figure I could generate a temporary pdf file on the server and then link to it like this, as suggested elsewhere on the site:

It appears your web browser doesn't support iframes.

And then set the src attribute in .js file:

 $('#myFrame').attr('src', 'http://www.example.com/tempPDFname.pdf');

How would I generate this file and make it available on server (C#) so I can set the src attribute?


问:
Why is setting onClickListener working once?
I want to migrate a very solid project structure that I use to Kotlin. I first tried the basics: Activities and Fragment transactions. It appears so easy and simple:

```<code>class MainActivity : AppCompatActivity(), SomeInterface {
     override fun onCreate(savedInstanceState: Bundle?) {
         setContentView(R.layout.activity_main)

         val mainFragment = supportFragmentManager.findFragmentById(R.id.fragment_main) as MainActionsFragment?
                    ?: MainActionsFragment.newInstance()
         supportFragmentManager.inTransaction {
              add(R.id.container_main, mainFragment)
         }
    }

    private val anotherFragment by lazy {
    supportFragmentManager.findFragmentById(R.id.another_fragment) as AnotherFragment?
            ?: AnotherFragment.newInstance()
    }

    override fun myInterfaceMethod() {
        replaceFragment(anotherFragment, R.id.container_main)
    }
}

class MainActionsFragment : Fragment() {
    val btnSale: Button by bindView(R.id.btn_sale)
    val btnVisit: Button by bindView(R.id.btn_visit)

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater!!.inflate(R.layout.fragment_main, container, false)
    }

    override fun onResume() {
        super.onResume()

        btnSale.setOnClickListener{ _ ->
            listener.requestAction(SaleType.SALE)
        }

        btnVisit.setOnClickListener{ _ ->
            listener.requestAction(SaleType.VISIT)
        }
    }
}
</code>```

Extensions.kt

```<code>fun AppCompatActivity.replaceFragment(fragment: Fragment, @IdRes frameId: Int) {
    supportFragmentManager.inTransaction {
        replace(frameId, fragment)
                .addToBackStack(fragment.tag)
    }
}

inline fun FragmentManager.inTransaction(func: FragmentTransaction.() -> FragmentTransaction) {
    beginTransaction()
            .func()
            .commit()
}
</code>```

Now, MainActionsFragment holds two buttons. Everything works as expected, the first click on either one takes me to the desired fragment. However, once I press the back button and I see my two buttons again, their click listener is gone. This is pretty much the standard way of doings things translated to Kotlin, nothing fancy besides its cool new features. I tried moving setting the onClickListeners to onCreateView() but it crashes:

Caused by: kotlin.KotlinNullPointerException
                                                                                at kotterknife.ButterKnifeKt$viewFinder$7.invoke(ButterKnife.kt:95)
                                                                                at kotterknife.ButterKnifeKt$viewFinder$7.invoke(ButterKnife.kt)
                                                                                at kotterknife.ButterKnifeKt$required$1.invoke(ButterKnife.kt:104)
                                                                                at kotterknife.ButterKnifeKt$required$1.invoke(ButterKnife.kt)
                                                                                at kotterknife.Lazy.getValue(ButterKnife.kt:125)

So, in spite of Kotlin being so cool, I'm having trouble doing the basics and I'm getting disheartened to migrate. Am I really doing things so wrong? Or how come setting a simple click listener is so frustrating?

Thank you.

答: Solution: solved it by getting rid of KotterKnife and ButterKnife and use android's findViewById. I guess one of the advantages of the language and the framework's progress make some libraries obsolete or unnecessary.

Body:
I want to migrate a very solid project structure that I use to Kotlin. I first tried the basics: Activities and Fragment transactions. It appears so easy and simple:

class MainActivity : AppCompatActivity(), SomeInterface {
     override fun onCreate(savedInstanceState: Bundle?) {
         setContentView(R.layout.activity_main)

         val mainFragment = supportFragmentManager.findFragmentById(R.id.fragment_main) as MainActionsFragment?
                    ?: MainActionsFragment.newInstance()
         supportFragmentManager.inTransaction {
              add(R.id.container_main, mainFragment)
         }
    }

    private val anotherFragment by lazy {
    supportFragmentManager.findFragmentById(R.id.another_fragment) as AnotherFragment?
            ?: AnotherFragment.newInstance()
    }

    override fun myInterfaceMethod() {
        replaceFragment(anotherFragment, R.id.container_main)
    }
}

class MainActionsFragment : Fragment() {
    val btnSale: Button by bindView(R.id.btn_sale)
    val btnVisit: Button by bindView(R.id.btn_visit)

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater!!.inflate(R.layout.fragment_main, container, false)
    }

    override fun onResume() {
        super.onResume()

        btnSale.setOnClickListener{ _ ->
            listener.requestAction(SaleType.SALE)
        }

        btnVisit.setOnClickListener{ _ ->
            listener.requestAction(SaleType.VISIT)
        }
    }
}

Extensions.kt

fun AppCompatActivity.replaceFragment(fragment: Fragment, @IdRes frameId: Int) {
    supportFragmentManager.inTransaction {
        replace(frameId, fragment)
                .addToBackStack(fragment.tag)
    }
}

inline fun FragmentManager.inTransaction(func: FragmentTransaction.() -> FragmentTransaction) {
    beginTransaction()
            .func()
            .commit()
}

Now, MainActionsFragment holds two buttons. Everything works as expected, the first click on either one takes me to the desired fragment. However, once I press the back button and I see my two buttons again, their click listener is gone. This is pretty much the standard way of doings things translated to Kotlin, nothing fancy besides its cool new features. I tried moving setting the onClickListeners to onCreateView() but it crashes:

Caused by: kotlin.KotlinNullPointerException
                                                                                at kotterknife.ButterKnifeKt$viewFinder$7.invoke(ButterKnife.kt:95)
                                                                                at kotterknife.ButterKnifeKt$viewFinder$7.invoke(ButterKnife.kt)
                                                                                at kotterknife.ButterKnifeKt$required$1.invoke(ButterKnife.kt:104)
                                                                                at kotterknife.ButterKnifeKt$required$1.invoke(ButterKnife.kt)
                                                                                at kotterknife.Lazy.getValue(ButterKnife.kt:125)

So, in spite of Kotlin being so cool, I'm having trouble doing the basics and I'm getting disheartened to migrate. Am I really doing things so wrong? Or how come setting a simple click listener is so frustrating?

Thank you.


问:
bash: append newline when redirecting file
Here is how I read a file row by row:

```<code>while read ROW
do
...
done < file
</code>```

I don't use the other syntax

```<code>cat file | while read ROW
do
...
done
</code>```

because the pipe creates a subshell and makes me lose the environment variables.
The problem arises if the file doesn't end with a newline: last line is not read. It is easy to solve this in the latter syntax, by echoing just a newline:

```<code>(cat file; echo) | while read ROW
do
...
done
</code>```

How do I do the same in the former syntax, without opening a subshell nor creating a temporary file (the list is quite big)?

答:
A way that works in all shells is the following:

```<code>#!/bin/sh

willexit=0
while [ $willexit == 0 ] ; do
read ROW || willexit=1
...
done < file
</code>```

A direct while read will exit as soon as read encounters the EOF, so the last line will not be processed. By checking the return value outside the while, we can process the last line. An additional test for the emptiness of $ROW should be added after the read though, since otherwise a file whose last line ends with a newline will generate a spurious execution with an empty line, so make it

```<code>#!/bin/sh

willexit=0
while [ $willexit == 0 ] ; do
read ROW || willexit=1
if [ -n "$ROW"] ; then
  ...
fi
done < file
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here is how I read a file row by row:

while read ROW
do
...
done < file

I don't use the other syntax

cat file | while read ROW
do
...
done

because the pipe creates a subshell and makes me lose the environment variables.
The problem arises if the file doesn't end with a newline: last line is not read. It is easy to solve this in the latter syntax, by echoing just a newline:

(cat file; echo) | while read ROW
do
...
done

How do I do the same in the former syntax, without opening a subshell nor creating a temporary file (the list is quite big)?

Body:
A way that works in all shells is the following:

#!/bin/sh

willexit=0
while [ $willexit == 0 ] ; do
read ROW || willexit=1
...
done < file

A direct while read will exit as soon as read encounters the EOF, so the last line will not be processed. By checking the return value outside the while, we can process the last line. An additional test for the emptiness of $ROW should be added after the read though, since otherwise a file whose last line ends with a newline will generate a spurious execution with an empty line, so make it

#!/bin/sh

willexit=0
while [ $willexit == 0 ] ; do
read ROW || willexit=1
if [ -n "$ROW"] ; then
  ...
fi
done < file


问:
Error in malloc while trying to create a thread
Hi everyone i post only the core of the code which create probleam and which work with threads.

```<code>#define HR_OFF h_r-1
pthread_t *threads = NULL;
int h_r = 1;
int foo(int handler)
{
    // if everything is empty alloc resources
    if (threads == NULL) {
        threads = (pthread_t*)malloc(sizeof(pthread_t));
        // stuff with other variables
        h_r++;
    }
    else {
        // stuff with other variables
        threads = (pthread_t*)realloc(threads, sizeof(pthread_t) * h_r);
        h_r++;
    }

    // stuff with other variables
    register unsigned int counter = 0;
    while (pthread_create(&threads[HR_OFF], NULL, (void*)&foo2, NULL) != 0) {
        if (counter == MAX_TRYING) {
            fprintf(stderr, "THREAD_ERROR_C occurs \n");
            return THREAD_ERROR_C;
        }
    }
    return 0;
}

int foo2(void *data)
{
    // stuff with other variables
}
</code>```

As we can see foo function create new thread and reallocate memory to store the pthread_t. Then it try to create a new thread with pthread_create as NULL as attr and arg and as function pointer a pointer to foo2;

Now the problem is that when i execute the code i have error with memory allocation when pthread_create is called that create this error message:

```<code>  Program received signal SIGABRT, Aborted.
__GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51
      ../sysdeps/unix/sysv/linux/raise.c: File o directory non esistente.
</code>```

and if a print backtrace using gdb

```<code>#0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51
#1  0x00007ffff78513fa in __GI_abort () at abort.c:89
#2  0x00007ffff78939c8 in __malloc_assert (
    assertion=assertion@entry=0x7ffff7983088 "(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)", file=file@entry=0x7ffff797f867 "malloc.c", line=line@entry=2406, function=function@entry=0x7ffff79838d0 <__func__.11275> "sysmalloc") at malloc.c:301
#3  0x00007ffff7895546 in sysmalloc (nb=nb@entry=288, av=0x7ffff7bb6b00 <main_arena>) at malloc.c:2403
#4  0x00007ffff789642d in _int_malloc (av=av@entry=0x7ffff7bb6b00 <main_arena>, bytes=bytes@entry=272) at malloc.c:3865
#5  0x00007ffff7898b4b in __libc_calloc (n=<optimized out>, elem_size=<optimized out>) at malloc.c:3274
#6  0x00007ffff7deaf42 in allocate_dtv (result=result@entry=0x7ffff781c700) at dl-tls.c:322
#7  0x00007ffff7deb8ce in __GI__dl_allocate_tls (mem=mem@entry=0x7ffff781c700) at dl-tls.c:539
#8  0x00007ffff7bc400c in allocate_stack (stack=<synthetic pointer>, pdp=<synthetic pointer>, attr=0x7fffffffe4b0) at allocatestack.c:580
---Type <return> to continue, or q <return> to quit---
#9  __pthread_create_2_1 (newthread=0x55555575b4c8, attr=<optimized out>, start_routine=0x5555555564fd <pthread_fetcher_function>, arg=0x0) at pthread_create.c:539
</code>```

How can i solve this problem, where is the problem.

Thanks to all for the patience and sorry for my english

答: Your thread allocation code is pointless because you only have 1 thread handle and accessing it threads[HR_OFF] is probably out of bounds. Casting (void) * &foo2 is wrong too, because foo2 has a proper signature like it should. Also retrying failed thread creation inside of loop is not a good idea either. Note that this loop is actually endless because you never increment counter. You should at least check failure reason before deciding to retry.

Body:
Hi everyone i post only the core of the code which create probleam and which work with threads.

#define HR_OFF h_r-1
pthread_t *threads = NULL;
int h_r = 1;
int foo(int handler)
{
    // if everything is empty alloc resources
    if (threads == NULL) {
        threads = (pthread_t*)malloc(sizeof(pthread_t));
        // stuff with other variables
        h_r++;
    }
    else {
        // stuff with other variables
        threads = (pthread_t*)realloc(threads, sizeof(pthread_t) * h_r);
        h_r++;
    }

    // stuff with other variables
    register unsigned int counter = 0;
    while (pthread_create(&threads[HR_OFF], NULL, (void*)&foo2, NULL) != 0) {
        if (counter == MAX_TRYING) {
            fprintf(stderr, "THREAD_ERROR_C occurs \n");
            return THREAD_ERROR_C;
        }
    }
    return 0;
}

int foo2(void *data)
{
    // stuff with other variables
}

As we can see foo function create new thread and reallocate memory to store the pthread_t. Then it try to create a new thread with pthread_create as NULL as attr and arg and as function pointer a pointer to foo2;

Now the problem is that when i execute the code i have error with memory allocation when pthread_create is called that create this error message:

  Program received signal SIGABRT, Aborted.
__GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51
      ../sysdeps/unix/sysv/linux/raise.c: File o directory non esistente.

and if a print backtrace using gdb

#0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51
#1  0x00007ffff78513fa in __GI_abort () at abort.c:89
#2  0x00007ffff78939c8 in __malloc_assert (
    assertion=assertion@entry=0x7ffff7983088 "(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)", file=file@entry=0x7ffff797f867 "malloc.c", line=line@entry=2406, function=function@entry=0x7ffff79838d0 <__func__.11275> "sysmalloc") at malloc.c:301
#3  0x00007ffff7895546 in sysmalloc (nb=nb@entry=288, av=0x7ffff7bb6b00 <main_arena>) at malloc.c:2403
#4  0x00007ffff789642d in _int_malloc (av=av@entry=0x7ffff7bb6b00 <main_arena>, bytes=bytes@entry=272) at malloc.c:3865
#5  0x00007ffff7898b4b in __libc_calloc (n=<optimized out>, elem_size=<optimized out>) at malloc.c:3274
#6  0x00007ffff7deaf42 in allocate_dtv (result=result@entry=0x7ffff781c700) at dl-tls.c:322
#7  0x00007ffff7deb8ce in __GI__dl_allocate_tls (mem=mem@entry=0x7ffff781c700) at dl-tls.c:539
#8  0x00007ffff7bc400c in allocate_stack (stack=<synthetic pointer>, pdp=<synthetic pointer>, attr=0x7fffffffe4b0) at allocatestack.c:580
---Type <return> to continue, or q <return> to quit---
#9  __pthread_create_2_1 (newthread=0x55555575b4c8, attr=<optimized out>, start_routine=0x5555555564fd <pthread_fetcher_function>, arg=0x0) at pthread_create.c:539

How can i solve this problem, where is the problem.

Thanks to all for the patience and sorry for my english


问:
Alternative to Gatling
I’ve been having issues lately because my dependencies has been updated to use netty 4.1 and Gatling has not been updated for a while, and still work only on Netty 4.0.

Anybody knows any alternative to Gatling to create similar Simulations and scenarios for the performance test to be run automatically in my Maven life cycle?

答:
Here's also a benchmark comparison of different tools.

If you are javascript/Ecma familiar k6 does the job.

Title: Alternative to Gatling


问:
Use of try/except for input validation?
I am trying to validate user input to check that, when they enter their name, it is more than 2 characters and is alphabetic. I am attempting to do this using try/except as I have been told that it is the best loop for user validation. Unfortunately if the user enters characters that are not alphabetic, nothing happens, and the program proceeds like normal. I also do not know how to check if the input is longer than 2 characters in the try/except loop as it is very new to me. Any help is much appreciated.</p>

```<code>    list = []
    def users_name():
      while True:
        try:
          name = str(input("Please enter your first name: "))
          list.append(name)
          break
        except TypeError:
          print("Letters only please.")
          continue
        except EOFError:
          print("Please input something....")
          continue

    users_name()
</code>```

答:
You program will continue to run because of the continue clause in the catch block.

You can also check to see if the length of what they entered is longer than two characters.

```<code>list = []
def users_name():
  while True: # Never ending loop
    try:
      name = str(input("Please enter your first name: "))
      if (len(name) > 2)
          list.append(name)
      break
    except TypeError:
      print("Letters only please.")
      continue # This causes it to continue
    except EOFError:
      print("Please input something....")
      continue # This causes it to continue

users_name()
</code>```

Also, you might want to stop the loop somehow. Maybe put in a break clause when you insert into the array?

```<code>if(len(name) > 2)
    list.append(name)
    break
...
</code>```

To check if the input is a digit or an alphabet character use isdigit() or isalpha()

```<code>if a.isalpha():
    #do something
elif a.isdigit():
    #do something
</code>```

Your code will then look like this:

```<code>list = []
def users_name():
while True: # Never ending loop
  try:
    name = str(input("Please enter your first name: "))
    if (len(name) > 2 && name.isalpha()):
        list.append(name)
        break
    else:
        raise TypeError
  except TypeError:
    print("Letters only please.")
    continue # This causes it to continue
  except EOFError:
    print("Please input something....")
    continue # This causes it to continue

users_name()
</code>```

Also if you are using Python < 3 consider using raw_input(). input() will actually evaluate the input as Python code.

Title: Use of try/except for input validation?

Body:
I am trying to validate user input to check that, when they enter their name, it is more than 2 characters and is alphabetic. I am attempting to do this using try/except as I have been told that it is the best loop for user validation. Unfortunately if the user enters characters that are not alphabetic, nothing happens, and the program proceeds like normal. I also do not know how to check if the input is longer than 2 characters in the try/except loop as it is very new to me. Any help is much appreciated.

    list = []
    def users_name():
      while True:
        try:
          name = str(input("Please enter your first name: "))
          list.append(name)
          break
        except TypeError:
          print("Letters only please.")
          continue
        except EOFError:
          print("Please input something....")
          continue

    users_name()

Body:
You program will continue to run because of the continue clause in the catch block.

You can also check to see if the length of what they entered is longer than two characters.

list = []
def users_name():
  while True: # Never ending loop
    try:
      name = str(input("Please enter your first name: "))
      if (len(name) > 2)
          list.append(name)
      break
    except TypeError:
      print("Letters only please.")
      continue # This causes it to continue
    except EOFError:
      print("Please input something....")
      continue # This causes it to continue

users_name()

Also, you might want to stop the loop somehow. Maybe put in a break clause when you insert into the array?

if(len(name) > 2)
    list.append(name)
    break
...

To check if the input is a digit or an alphabet character use isdigit() or isalpha()

if a.isalpha():
    #do something
elif a.isdigit():
    #do something

Your code will then look like this:

list = []
def users_name():
while True: # Never ending loop
  try:
    name = str(input("Please enter your first name: "))
    if (len(name) > 2 && name.isalpha()):
        list.append(name)
        break
    else:
        raise TypeError
  except TypeError:
    print("Letters only please.")
    continue # This causes it to continue
  except EOFError:
    print("Please input something....")
    continue # This causes it to continue

users_name()

Also if you are using Python < 3 consider using raw_input(). input() will actually evaluate the input as Python code.


问:
Group by sum and find min max of date from the group
I have a table as below.

```<code>                                           msno      date  num_25  num_50  num_75  num_985  num_100  num_unq
1  PNxIsSLWOJDCm7pNPFzRO/6Mmg2WeZA2nf6hw6t1x3g=  20151201       3       3       2        0        8       11
2  PNxIsSLWOJDCm7pNPFzRO/6Mmg2WeZA2nf6hw6t1x3g=  20160628       0       0       1        1        1        3
3  PNxIsSLWOJDCm7pNPFzRO/6Mmg2WeZA2nf6hw6t1x3g=  20170106       2       1       0        0       35       34
4  KXF9c/T66LZIzFq+xS64icWMhDQE6miCZAtdXRjZHX8=  20150803       0       0       0        0       16       11
5  KXF9c/T66LZIzFq+xS64icWMhDQE6miCZAtdXRjZHX8=  20160527       4       3       0        2        2       11
6  KXF9c/T66LZIzFq+xS64icWMhDQE6miCZAtdXRjZHX8=  20160808      14       3       4        1       15       31
</code>```

I wish to group them up by summing up the num_(25 until unq) and then determine the earliest date and latest date occur in the identical msno.

```<code>df = df_user_logs_v2.drop('date', axis=1).groupby('msno', as_index=False).sum()
</code>```

The code above can sum up all the values but the date have to be dropped. I wish to retain the min and max of the date, along with number of row count.

Expected Output for the first msno:

```<code>                                          msno  num_25_sum  num_50_sum  num_75_sum  num_985_sum  num_100_sum  num_unq_sum date_earliest date_latest count
1 PNxIsSLWOJDCm7pNPFzRO/6Mmg2WeZA2nf6hw6t1x3g=           5           4           3            1           44           48      20151201    20170106     3
</code>```

答:
Let's try this:

```<code>d = dict((i,'sum') for i in df.columns[2:])
d['date'] = ['min','max']
d['msno'] = 'count'
df_out = df.groupby('msno').agg(d)
df_out.columns = df_out.columns.map('_'.join)

df_out
</code>```

Output:

```<code>                                              msno_count  date_min  date_max  \
msno
KXF9c/T66LZIzFq+xS64icWMhDQE6miCZAtdXRjZHX8=           3  20150803  20160808
PNxIsSLWOJDCm7pNPFzRO/6Mmg2WeZA2nf6hw6t1x3g=           3  20151201  20170106

                                              num_75_sum  num_50_sum  \
msno
KXF9c/T66LZIzFq+xS64icWMhDQE6miCZAtdXRjZHX8=           4           6
PNxIsSLWOJDCm7pNPFzRO/6Mmg2WeZA2nf6hw6t1x3g=           3           4

                                              num_985_sum  num_25_sum  \
msno
KXF9c/T66LZIzFq+xS64icWMhDQE6miCZAtdXRjZHX8=            3          18
PNxIsSLWOJDCm7pNPFzRO/6Mmg2WeZA2nf6hw6t1x3g=            1           5

                                              num_100_sum  num_unq_sum
msno
KXF9c/T66LZIzFq+xS64icWMhDQE6miCZAtdXRjZHX8=           33           53
PNxIsSLWOJDCm7pNPFzRO/6Mmg2WeZA2nf6hw6t1x3g=           44           48
</code>```

Body:
I have a table as below.

                                           msno      date  num_25  num_50  num_75  num_985  num_100  num_unq
1  PNxIsSLWOJDCm7pNPFzRO/6Mmg2WeZA2nf6hw6t1x3g=  20151201       3       3       2        0        8       11
2  PNxIsSLWOJDCm7pNPFzRO/6Mmg2WeZA2nf6hw6t1x3g=  20160628       0       0       1        1        1        3
3  PNxIsSLWOJDCm7pNPFzRO/6Mmg2WeZA2nf6hw6t1x3g=  20170106       2       1       0        0       35       34
4  KXF9c/T66LZIzFq+xS64icWMhDQE6miCZAtdXRjZHX8=  20150803       0       0       0        0       16       11
5  KXF9c/T66LZIzFq+xS64icWMhDQE6miCZAtdXRjZHX8=  20160527       4       3       0        2        2       11
6  KXF9c/T66LZIzFq+xS64icWMhDQE6miCZAtdXRjZHX8=  20160808      14       3       4        1       15       31

I wish to group them up by summing up the num_(25 until unq) and then determine the earliest date and latest date occur in the identical msno.

df = df_user_logs_v2.drop('date', axis=1).groupby('msno', as_index=False).sum()

The code above can sum up all the values but the date have to be dropped. I wish to retain the min and max of the date, along with number of row count.

Expected Output for the first msno:

                                          msno  num_25_sum  num_50_sum  num_75_sum  num_985_sum  num_100_sum  num_unq_sum date_earliest date_latest count
1 PNxIsSLWOJDCm7pNPFzRO/6Mmg2WeZA2nf6hw6t1x3g=           5           4           3            1           44           48      20151201    20170106     3

Body:
Let's try this:

d = dict((i,'sum') for i in df.columns[2:])
d['date'] = ['min','max']
d['msno'] = 'count'
df_out = df.groupby('msno').agg(d)
df_out.columns = df_out.columns.map('_'.join)

df_out

Output:

                                              msno_count  date_min  date_max  \
msno
KXF9c/T66LZIzFq+xS64icWMhDQE6miCZAtdXRjZHX8=           3  20150803  20160808
PNxIsSLWOJDCm7pNPFzRO/6Mmg2WeZA2nf6hw6t1x3g=           3  20151201  20170106

                                              num_75_sum  num_50_sum  \
msno
KXF9c/T66LZIzFq+xS64icWMhDQE6miCZAtdXRjZHX8=           4           6
PNxIsSLWOJDCm7pNPFzRO/6Mmg2WeZA2nf6hw6t1x3g=           3           4

                                              num_985_sum  num_25_sum  \
msno
KXF9c/T66LZIzFq+xS64icWMhDQE6miCZAtdXRjZHX8=            3          18
PNxIsSLWOJDCm7pNPFzRO/6Mmg2WeZA2nf6hw6t1x3g=            1           5

                                              num_100_sum  num_unq_sum
msno
KXF9c/T66LZIzFq+xS64icWMhDQE6miCZAtdXRjZHX8=           33           53
PNxIsSLWOJDCm7pNPFzRO/6Mmg2WeZA2nf6hw6t1x3g=           44           48


问:
How to filter data with hidden data?
In my klipfolio data source I have a field version-name. The data in there is numeric and alpha. I only want to see the numeric version. So I created a hidden data which will evaluate to true when the first digit is numeric (this rule is valid in my case):

```<code>IN( LEFT( @/issues/fields/fixVersions/name;, 1), ARRAY( 0, CUMULATIVE(REPEAT(1,9))))
</code>```

but the hidden data does not change my output? Do I need to apply this somewhere to get the current result filtered?

答: If you want a hidden data slot to act as a filter, right click on the hidden data slot -> Filter... then in the Members tab, select "True". This will filter out all the records that do not have a digit as the first value in the string.</p>

Title: How to filter data with hidden data?

Body:
In my klipfolio data source I have a field version-name. The data in there is numeric and alpha. I only want to see the numeric version. So I created a hidden data which will evaluate to true when the first digit is numeric (this rule is valid in my case):

IN( LEFT( @/issues/fields/fixVersions/name;, 1), ARRAY( 0, CUMULATIVE(REPEAT(1,9))))

but the hidden data does not change my output? Do I need to apply this somewhere to get the current result filtered?


问:
html button, the value="submit" is not showing up?
I am looking for the value="submit" to show up in the middle of the button.  I am not seeing any text, not sure why?    </p>

```<code><button type="button" class="button btn_big_blue" value="Submit"></button>

.button{
    display: block;
    width: 137px;
    height:    44px;
    text-align:center;
    line-height: 40px;
    font-size: 18px;
    font-weight: bold;
    text-decoration: none;
    color:#fff;
    border:none;
    cursor: pointer;
}

.button.btn_big_blue {
    background: url(/img/btn_big_blue.png) no-repeat;
    color: #fff;
}
</code>```

答:
when you use the button tag, you put the text you want to be in the button between the opening and closing tag.

```<code><button>Submit</button>
</code>```

the value="Submit" is only for <input type="button">

Body:
I am looking for the value="submit" to show up in the middle of the button.  I am not seeing any text, not sure why?

<button type="button" class="button btn_big_blue" value="Submit"></button>

.button{
    display: block;
    width: 137px;
    height:    44px;
    text-align:center;
    line-height: 40px;
    font-size: 18px;
    font-weight: bold;
    text-decoration: none;
    color:#fff;
    border:none;
    cursor: pointer;
}

.button.btn_big_blue {
    background: url(/img/btn_big_blue.png) no-repeat;
    color: #fff;
}

Body:
when you use the button tag, you put the text you want to be in the button between the opening and closing tag.

<button>Submit</button>

the value="Submit" is only for <input type="button">


问:
Delphi apps won't tether on Windows 10
How do I get Windows 10 or its firewall to allow my Delphi 10.2 tethering app to get access to the internet?

When either the desktop or the mobile app is run on Windows 10, there is no request for permission from the firewall and tethering fails.

In contrast, the Delphi mobile Photowall tethering example runs fine on Android and iPad, tethering with the matching desktop application on Windows 7 and MacOS. On Windows 7 and Macintosh, the firewall asks for permission when the app is run.

答:
The Windows 10 machine in question automatically installed McAfee internet. I uninstalled McAfee and the Delphi tethering apps immediately triggered Firewall exception request and then worked properly.

Even though I added the Delphi tethering apps to the Windows firewall exception list, McAfee apparently still blocked the apps. The Delphi apps never raised an error when blocked.

Title: Delphi apps won't tether on Windows 10


问:
How to display multiple routes in one page using Ember js?
I'm new to Ember and I'm stuck with an issue that I cannot solve. I have two routes - home and lhstree. When /home is called, I need both the routes to be rendered ie. lhstree should be rendered within home template. For this purpose, I used named outlet. That worked fine.
But the problem is, I need to supply data to the lhstree template. But the model hook for the lhstree template is never called. I even tried adding alert messages in the model hook, but that too is never executed. The below is my code. Any help is appreciated.

router.js:

```<code>Router.map(function() {
 this.route('home');
 this.route('lhstree');
});
</code>```

home.hbs:

```<code><html>
<head>
</head>
<body>
    Home hbs rendering
    {{outlet 'lhstree'}}
</body>
</html>
</code>```

home.js:

```<code>export default Route.extend({
    renderTemplate:function()
    {
        this.render();
        this.render('lhstree',{outlet:'lhstree',into:'home'});
    }
});
</code>```

lhstree.hbs:

```<code><ul>
  {{#each model as |player|}}
    <li>{{player}}</li>
  {{/each}}
</ul>
</code>```

lhstree.js:

```<code>model() //THIS MODEL IS NEVER CALLED
{
  return ['Player1', 'Player2'];
}
</code>```

As I mentioned, the model hook of lhstree route is never called. So, the player names Player1 and Player2 are never displayed when home template is rendered.

答:
Theres two different ways to approach this problem:

If lhstree is ALWAYS going to be on the home page, don't use a route for it.  You could build it as a component, and pass attributes down to it from the parent (so get the data you need for lhstree in the Home model route).  So your outlet would be replaced by:

```<code>{{lhstree-component model=model.lhsStuff}}
</code>```

Make lhstree a sub route of Home.  That way when someone goes to home/lhstree Ember will render the lhstree template into the outlet within the Home template, and will call both models.  To do this, set up your routes like:

```<code>Router.map(function() {
  this.route('home', function() {
    this.route('lhstree');
  });
});
</code>```

Body:
I'm new to Ember and I'm stuck with an issue that I cannot solve. I have two routes - home and lhstree. When /home is called, I need both the routes to be rendered ie. lhstree should be rendered within home template. For this purpose, I used named outlet. That worked fine.
But the problem is, I need to supply data to the lhstree template. But the model hook for the lhstree template is never called. I even tried adding alert messages in the model hook, but that too is never executed. The below is my code. Any help is appreciated.

router.js:

Router.map(function() {
 this.route('home');
 this.route('lhstree');
});

home.hbs:

    Home hbs rendering
    {{outlet 'lhstree'}}

home.js:

export default Route.extend({
    renderTemplate:function()
    {
        this.render();
        this.render('lhstree',{outlet:'lhstree',into:'home'});
    }
});

lhstree.hbs:

  {{#each model as |player|}}

{{player}}

  {{/each}}

lhstree.js:

model() //THIS MODEL IS NEVER CALLED
{
  return ['Player1', 'Player2'];
}

As I mentioned, the model hook of lhstree route is never called. So, the player names Player1 and Player2 are never displayed when home template is rendered.

Body:
Theres two different ways to approach this problem:

If lhstree is ALWAYS going to be on the home page, don't use a route for it.  You could build it as a component, and pass attributes down to it from the parent (so get the data you need for lhstree in the Home model route).  So your outlet would be replaced by:

{{lhstree-component model=model.lhsStuff}}

Make lhstree a sub route of Home.  That way when someone goes to home/lhstree Ember will render the lhstree template into the outlet within the Home template, and will call both models.  To do this, set up your routes like:

Router.map(function() {
  this.route('home', function() {
    this.route('lhstree');
  });
});


问:
Unit testing side outputs
I'm unit testing a ParDo function with Apache Beam that has 1 main output and 1 sideoutput:

```<code>public class GetPubsubMessageDoFn extends DoFn<PubsubMessage, PubsubPayload.PubsubPayloadDTO> {

  @ProcessElement
  public void processContext(ProcessContext processContext) {
    PubsubPayload pubsubPayload = new PubsubPayload(processContext.element());
    processContext.output(pubsubPayload.getPayload()); //main output
    processContext.output(ORIGIN_PATH_TUPLE_TAG, GCSUtils.toGSURL(pubsubPayload.getPayload().bucket, pubsubPayload.getPayload().name)); //side output
  }
}
</code>```

I set up a unit test class for testing the main - and side outputs:

```<code> public class GetPubsubMessageDoFnTest {

      private DoFnTester<PubsubMessage, PubsubPayloadDTO> getPubsubMessageDoFn;
      private Injector injector;
      private final TupleTagList tags = TupleTagList.of(PUBSUB_PAYLOAD_DTO_TUPLE_TAG).and(ORIGIN_PATH_TUPLE_TAG);

      @Before
      public void setup() {
        injector = Guice.createInjector(new GetPubsubMessageTestModule());
        this.getPubsubMessageDoFn = DoFnTester.of(injector.getInstance(GetPubsubMessageDoFn.class));
        this.getPubsubMessageDoFn.setOutputTags(tags); //Does not compile
      }

  //Tests
</code>```

According to the documentation I should be able to set the side output using  setOutputTags(tags) only that function does not exist on the DoFnTester class. I'm using the Google Cloud Dataflow dependency version 2.1.0, which does use a subset of Apache Beam's features, but even looking at the Apache Beam reference documentation for DoFnTester setOutputTags isn't listed (even though it's mentioned again in the intro).

答:
These methods are not available in 2.1.0. In fact, DoFnTester is being deprecated, see https://issues.apache.org/jira/browse/BEAM-3159.

The advice is to use TestPipeline with the DirectRunner to test a ParDo on their DoFn. You can carefully control the flow of input with TestStream. See a nice blog on this topic.

Title: Unit testing side outputs

Body:
I'm unit testing a ParDo function with Apache Beam that has 1 main output and 1 sideoutput:

public class GetPubsubMessageDoFn extends DoFn<PubsubMessage, PubsubPayload.PubsubPayloadDTO> {

  @ProcessElement
  public void processContext(ProcessContext processContext) {
    PubsubPayload pubsubPayload = new PubsubPayload(processContext.element());
    processContext.output(pubsubPayload.getPayload()); //main output
    processContext.output(ORIGIN_PATH_TUPLE_TAG, GCSUtils.toGSURL(pubsubPayload.getPayload().bucket, pubsubPayload.getPayload().name)); //side output
  }
}

I set up a unit test class for testing the main - and side outputs:

 public class GetPubsubMessageDoFnTest {

      private DoFnTester<PubsubMessage, PubsubPayloadDTO> getPubsubMessageDoFn;
      private Injector injector;
      private final TupleTagList tags = TupleTagList.of(PUBSUB_PAYLOAD_DTO_TUPLE_TAG).and(ORIGIN_PATH_TUPLE_TAG);

      @Before
      public void setup() {
        injector = Guice.createInjector(new GetPubsubMessageTestModule());
        this.getPubsubMessageDoFn = DoFnTester.of(injector.getInstance(GetPubsubMessageDoFn.class));
        this.getPubsubMessageDoFn.setOutputTags(tags); //Does not compile
      }

  //Tests

According to the documentation I should be able to set the side output using  setOutputTags(tags) only that function does not exist on the DoFnTester class. I'm using the Google Cloud Dataflow dependency version 2.1.0, which does use a subset of Apache Beam's features, but even looking at the Apache Beam reference documentation for DoFnTester setOutputTags isn't listed (even though it's mentioned again in the intro).


问:
Migration of NSSQLite to Seam3 storage type fails with EXC_BAD_ACCESS
I'm still trying to setup proper migration of existing NSSQLiteStore to SMStore.Type (Seam3) and getting strange issue. Cannot understand why it happens. I have raised the same for Paul on github, but probably somebody will noticed the cause in my code and will be able to help, while Paul is busy.

What do I have:
App running on iOS 10+ with NSSQLiteStore located in default folder.

Steps of testing:

Remove new store (if exists) and it's supporting files located in new path:
file:///Users/dj-glock/Library/Developer/CoreSimulator/Devices/3708F142-3BD0-4C70-8515-217B7785D285/data/Containers/Data/Application/29B60BBC-0D17-4D6C-8107-0135C45B20BA/Documents/CafeManagerSeam3.sqlite

Run app. App should check if new store exists. If not - perform migration from default one.

App tries to migrate store and fails with EXC_BAD_ACCESS.
But in the same time I can see that new store appeared in new path and if I run app once again, it uses new store with no visible issues.

My code:

```<code>@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    var window: UIWindow?
    var smStore: SMStore?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        if #available(iOS 10.0, *) {
        let storeDescriptionType = AppDelegate.persistentContainer.persistentStoreCoordinator.persistentStores.first?.type
            if storeDescriptionType == SMStore.type {
                print("Store is SMStore")
                print()
                self.smStore = AppDelegate.persistentContainer.persistentStoreCoordinator.persistentStores.first as? SMStore
            }
        } else {
            let storeDescriptionType = AppDelegate.managedObjectContext.persistentStoreCoordinator?.persistentStores.first?.type
            if storeDescriptionType == SMStore.type {
                print("Store is SMStore")
                print()
                self.smStore = AppDelegate.managedObjectContext.persistentStoreCoordinator?.persistentStores.first as? SMStore
            }
        }
...
    // MARK: - Core Data stack for iOS 10+
    @available(iOS 10.0, *)
    static var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "CafeManager")
        let persistentStoreCoordinator = container.persistentStoreCoordinator

        //MARK: Initializing Seam3
        SMStore.registerStoreClass()
        SMStore.syncAutomatically = true

        //MARK: Preparing URL
        let applicationDocumentsDirectory: URL = {
            let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
            return urls[urls.count-1]
        }()
        let newURL = applicationDocumentsDirectory.appendingPathComponent("CafeManagerSeam3.sqlite")

        //MARK: Check if SQLite store has been already migrated by checking if CafeManagerSeam3.sqlite exists.
        let seamStoreExists = FileManager.default.fileExists(atPath: newURL.path)

        if seamStoreExists {
            //If exists, then use it because it has been already migrated to Seam3 storage
            print("Already migrated, using \(newURL)")

            let storeDescription = NSPersistentStoreDescription(url: newURL)
            storeDescription.type = SMStore.type
            storeDescription.setOption("iCloud.iGlock.CafeManager.com" as NSString, forKey: SMStore.SMStoreContainerOption)
            storeDescription.setOption(NSNumber(value:SMSyncConflictResolutionPolicy.clientTellsWhichWins.rawValue), forKey:SMStore.SMStoreSyncConflictResolutionPolicyOption)
            container.persistentStoreDescriptions=[storeDescription]

            container.loadPersistentStores(completionHandler: { (storeDescription, error) in
                if let error = error as NSError? {
                    fatalError("Unresolved error \(error), \(error.userInfo)")
                }
            })
            return container

        } else {
            //If does not exist, then migrate old storage to Seam3.
            print("Not yet migrated, migrating to \(newURL)")

            //Loadig default store
            container.loadPersistentStores(completionHandler: { (storeDescription, error) in
                if let error = error as NSError? {
                    fatalError("Failed to load default store \(error), \(error.userInfo)")
                }
            })
            let defaultPersistentStore = container.persistentStoreCoordinator.persistentStores.last
            print("Default store is located here: \(defaultPersistentStore!.url!)")

            //Adding new Seam3 store
            do {
                try persistentStoreCoordinator.addPersistentStore(ofType: SMStore.type, configurationName: nil, at: newURL, options: nil)
                print("Seam store was added to the new url: \(newURL)")
            } catch {
                fatalError("Failed to add new Seam store: \(error)")
            }

            //Migrating default store to new Seam store
            do {
                try persistentStoreCoordinator.migratePersistentStore(defaultPersistentStore!, to: newURL, options: nil, withType:SMStore.type)
                //Removing old store
                if defaultPersistentStore != nil {
                    do {
                        try persistentStoreCoordinator.remove(defaultPersistentStore!)
                    } catch {
                        fatalError("Failed to remove default store \(error)")
                    }
                }
            }
            catch {
                fatalError("Failed to migrate to Seam store: \(error)")
            }

            //Setting additional parameters to Seam store to make it able to use CloudKit
            let storeDescription = NSPersistentStoreDescription(url: newURL)
            storeDescription.type = SMStore.type
            storeDescription.setOption("iCloud.iGlock.CafeManager.com" as NSString, forKey: SMStore.SMStoreContainerOption)
            storeDescription.setOption(NSNumber(value:SMSyncConflictResolutionPolicy.clientTellsWhichWins.rawValue), forKey:SMStore.SMStoreSyncConflictResolutionPolicyOption)
            container.persistentStoreDescriptions=[storeDescription]

            return container
        }
</code>```

Output:

```<code>CoreData: annotation:  Failed to load optimized model at path '/Users/dj-glock/Library/Developer/CoreSimulator/Devices/3708F142-3BD0-4C70-8515-217B7785D285/data/Containers/Bundle/Application/3E4EB624-227E-4BD0-99F1-AA975D86BDA8/CafeManager.app/CafeManager.momd/CafeManager v2.omo'
Not yet migrated, migrating to file:///Users/dj-glock/Library/Developer/CoreSimulator/Devices/3708F142-3BD0-4C70-8515-217B7785D285/data/Containers/Data/Application/100FB44C-C881-44C1-9D03-454FEBDB092B/Documents/CafeManagerSeam3.sqlite
Default store is located here: file:///Users/dj-glock/Library/Developer/CoreSimulator/Devices/3708F142-3BD0-4C70-8515-217B7785D285/data/Containers/Data/Application/100FB44C-C881-44C1-9D03-454FEBDB092B/Library/Application%20Support/CafeManager.sqlite
Seam store was added to the new url: file:///Users/dj-glock/Library/Developer/CoreSimulator/Devices/3708F142-3BD0-4C70-8515-217B7785D285/data/Containers/Data/Application/100FB44C-C881-44C1-9D03-454FEBDB092B/Documents/CafeManagerSeam3.sqlite
2017-10-31 17:49:47.762 CafeManager[52561:7472303] Access to CloudKit has not been verified by calling verifyCloudKitConnection
(lldb) po self
error: Trying to put the stack in unreadable memory at: 0x7ffee595ef80.
(lldb)
What am I doing wrong? Is it my misunderstanding of CoreData stack or something else?
</code>```

Output when I rerun app after it's crash:

```<code>objc[52621]: Class _NSZombie_OS_xpc_endpoint is implemented in both ?? (0x618000048340) and ?? (0x600000047290). One of the two will be used. Which one is undefined.
CoreData: annotation:  Failed to load optimized model at path '/Users/dj-glock/Library/Developer/CoreSimulator/Devices/3708F142-3BD0-4C70-8515-217B7785D285/data/Containers/Bundle/Application/0B098A31-C927-44C0-87C2-2F2B944DF66C/CafeManager.app/CafeManager.momd/CafeManager v2.omo'
Already migrated, using file:///Users/dj-glock/Library/Developer/CoreSimulator/Devices/3708F142-3BD0-4C70-8515-217B7785D285/data/Containers/Data/Application/932E6B3A-65B1-44F1-920B-DCE5F242C9C7/Documents/CafeManagerSeam3.sqlite
Store is SMStore

Sync Started
No more records coming
Sync Performed
Sync performed successfully
//some test insert that was loaded to Cloud.
Sync Started
No more records coming
Sync Performed
Sync performed successfully
</code>```

答:
Error was solved. Used example from Paul.</p>

```<code>{
            // If does not exist, then migrate old storage to Seam3.
            print("Not yet migrated, migrating to \(newURL)")
            SMStore.syncAutomatically = false

            // Loadig default store
            container.loadPersistentStores(completionHandler: { (storeDescription, error) in
                if let error = error as NSError? {
                    fatalError("Failed to load default store \(error), \(error.userInfo)")
                }
            })
            let defaultPersistentStore = container.persistentStoreCoordinator.persistentStores.last
            print("Default store is located here: \(defaultPersistentStore!.url!)")

            //Migrating default store to new Seam store
            do {
                try persistentStoreCoordinator.migratePersistentStore(defaultPersistentStore!, to: newURL, options: nil, withType:SMStore.type)
            }
            catch {
                fatalError("Failed to migrate to Seam store: \(error)")
            }

            //Setting additional parameters to Seam store to make it able to use CloudKit
            let storeDescription = NSPersistentStoreDescription(url: newURL)
            storeDescription.type = SMStore.type
            storeDescription.setOption("iCloud.iGlock.CafeManager.com" as NSString, forKey: SMStore.SMStoreContainerOption)
            storeDescription.setOption(NSNumber(value:SMSyncConflictResolutionPolicy.clientTellsWhichWins.rawValue), forKey:SMStore.SMStoreSyncConflictResolutionPolicyOption)
            container.persistentStoreDescriptions=[storeDescription]
            SMStore.syncAutomatically = true
            return container
        }
</code>```

Body:
I'm still trying to setup proper migration of existing NSSQLiteStore to SMStore.Type (Seam3) and getting strange issue. Cannot understand why it happens. I have raised the same for Paul on github, but probably somebody will noticed the cause in my code and will be able to help, while Paul is busy.

What do I have:
App running on iOS 10+ with NSSQLiteStore located in default folder.

Steps of testing:

Remove new store (if exists) and it's supporting files located in new path:
file:///Users/dj-glock/Library/Developer/CoreSimulator/Devices/3708F142-3BD0-4C70-8515-217B7785D285/data/Containers/Data/Application/29B60BBC-0D17-4D6C-8107-0135C45B20BA/Documents/CafeManagerSeam3.sqlite

Run app. App should check if new store exists. If not - perform migration from default one.

App tries to migrate store and fails with EXC_BAD_ACCESS.
But in the same time I can see that new store appeared in new path and if I run app once again, it uses new store with no visible issues.

My code:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    var window: UIWindow?
    var smStore: SMStore?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        if #available(iOS 10.0, *) {
        let storeDescriptionType = AppDelegate.persistentContainer.persistentStoreCoordinator.persistentStores.first?.type
            if storeDescriptionType == SMStore.type {
                print("Store is SMStore")
                print()
                self.smStore = AppDelegate.persistentContainer.persistentStoreCoordinator.persistentStores.first as? SMStore
            }
        } else {
            let storeDescriptionType = AppDelegate.managedObjectContext.persistentStoreCoordinator?.persistentStores.first?.type
            if storeDescriptionType == SMStore.type {
                print("Store is SMStore")
                print()
                self.smStore = AppDelegate.managedObjectContext.persistentStoreCoordinator?.persistentStores.first as? SMStore
            }
        }
...
    // MARK: - Core Data stack for iOS 10+
    @available(iOS 10.0, *)
    static var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "CafeManager")
        let persistentStoreCoordinator = container.persistentStoreCoordinator

        //MARK: Initializing Seam3
        SMStore.registerStoreClass()
        SMStore.syncAutomatically = true

        //MARK: Preparing URL
        let applicationDocumentsDirectory: URL = {
            let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
            return urls[urls.count-1]
        }()
        let newURL = applicationDocumentsDirectory.appendingPathComponent("CafeManagerSeam3.sqlite")

        //MARK: Check if SQLite store has been already migrated by checking if CafeManagerSeam3.sqlite exists.
        let seamStoreExists = FileManager.default.fileExists(atPath: newURL.path)

        if seamStoreExists {
            //If exists, then use it because it has been already migrated to Seam3 storage
            print("Already migrated, using \(newURL)")

            let storeDescription = NSPersistentStoreDescription(url: newURL)
            storeDescription.type = SMStore.type
            storeDescription.setOption("iCloud.iGlock.CafeManager.com" as NSString, forKey: SMStore.SMStoreContainerOption)
            storeDescription.setOption(NSNumber(value:SMSyncConflictResolutionPolicy.clientTellsWhichWins.rawValue), forKey:SMStore.SMStoreSyncConflictResolutionPolicyOption)
            container.persistentStoreDescriptions=[storeDescription]

            container.loadPersistentStores(completionHandler: { (storeDescription, error) in
                if let error = error as NSError? {
                    fatalError("Unresolved error \(error), \(error.userInfo)")
                }
            })
            return container

        } else {
            //If does not exist, then migrate old storage to Seam3.
            print("Not yet migrated, migrating to \(newURL)")

            //Loadig default store
            container.loadPersistentStores(completionHandler: { (storeDescription, error) in
                if let error = error as NSError? {
                    fatalError("Failed to load default store \(error), \(error.userInfo)")
                }
            })
            let defaultPersistentStore = container.persistentStoreCoordinator.persistentStores.last
            print("Default store is located here: \(defaultPersistentStore!.url!)")

            //Adding new Seam3 store
            do {
                try persistentStoreCoordinator.addPersistentStore(ofType: SMStore.type, configurationName: nil, at: newURL, options: nil)
                print("Seam store was added to the new url: \(newURL)")
            } catch {
                fatalError("Failed to add new Seam store: \(error)")
            }

            //Migrating default store to new Seam store
            do {
                try persistentStoreCoordinator.migratePersistentStore(defaultPersistentStore!, to: newURL, options: nil, withType:SMStore.type)
                //Removing old store
                if defaultPersistentStore != nil {
                    do {
                        try persistentStoreCoordinator.remove(defaultPersistentStore!)
                    } catch {
                        fatalError("Failed to remove default store \(error)")
                    }
                }
            }
            catch {
                fatalError("Failed to migrate to Seam store: \(error)")
            }

            //Setting additional parameters to Seam store to make it able to use CloudKit
            let storeDescription = NSPersistentStoreDescription(url: newURL)
            storeDescription.type = SMStore.type
            storeDescription.setOption("iCloud.iGlock.CafeManager.com" as NSString, forKey: SMStore.SMStoreContainerOption)
            storeDescription.setOption(NSNumber(value:SMSyncConflictResolutionPolicy.clientTellsWhichWins.rawValue), forKey:SMStore.SMStoreSyncConflictResolutionPolicyOption)
            container.persistentStoreDescriptions=[storeDescription]

            return container
        }

Output:

CoreData: annotation:  Failed to load optimized model at path '/Users/dj-glock/Library/Developer/CoreSimulator/Devices/3708F142-3BD0-4C70-8515-217B7785D285/data/Containers/Bundle/Application/3E4EB624-227E-4BD0-99F1-AA975D86BDA8/CafeManager.app/CafeManager.momd/CafeManager v2.omo'
Not yet migrated, migrating to file:///Users/dj-glock/Library/Developer/CoreSimulator/Devices/3708F142-3BD0-4C70-8515-217B7785D285/data/Containers/Data/Application/100FB44C-C881-44C1-9D03-454FEBDB092B/Documents/CafeManagerSeam3.sqlite
Default store is located here: file:///Users/dj-glock/Library/Developer/CoreSimulator/Devices/3708F142-3BD0-4C70-8515-217B7785D285/data/Containers/Data/Application/100FB44C-C881-44C1-9D03-454FEBDB092B/Library/Application%20Support/CafeManager.sqlite
Seam store was added to the new url: file:///Users/dj-glock/Library/Developer/CoreSimulator/Devices/3708F142-3BD0-4C70-8515-217B7785D285/data/Containers/Data/Application/100FB44C-C881-44C1-9D03-454FEBDB092B/Documents/CafeManagerSeam3.sqlite
2017-10-31 17:49:47.762 CafeManager[52561:7472303] Access to CloudKit has not been verified by calling verifyCloudKitConnection
(lldb) po self
error: Trying to put the stack in unreadable memory at: 0x7ffee595ef80.
(lldb)
What am I doing wrong? Is it my misunderstanding of CoreData stack or something else?

Output when I rerun app after it's crash:

objc[52621]: Class _NSZombie_OS_xpc_endpoint is implemented in both ?? (0x618000048340) and ?? (0x600000047290). One of the two will be used. Which one is undefined.
CoreData: annotation:  Failed to load optimized model at path '/Users/dj-glock/Library/Developer/CoreSimulator/Devices/3708F142-3BD0-4C70-8515-217B7785D285/data/Containers/Bundle/Application/0B098A31-C927-44C0-87C2-2F2B944DF66C/CafeManager.app/CafeManager.momd/CafeManager v2.omo'
Already migrated, using file:///Users/dj-glock/Library/Developer/CoreSimulator/Devices/3708F142-3BD0-4C70-8515-217B7785D285/data/Containers/Data/Application/932E6B3A-65B1-44F1-920B-DCE5F242C9C7/Documents/CafeManagerSeam3.sqlite
Store is SMStore

Sync Started
No more records coming
Sync Performed
Sync performed successfully
//some test insert that was loaded to Cloud.
Sync Started
No more records coming
Sync Performed
Sync performed successfully

Body:
Error was solved. Used example from Paul.

{
            // If does not exist, then migrate old storage to Seam3.
            print("Not yet migrated, migrating to \(newURL)")
            SMStore.syncAutomatically = false

            // Loadig default store
            container.loadPersistentStores(completionHandler: { (storeDescription, error) in
                if let error = error as NSError? {
                    fatalError("Failed to load default store \(error), \(error.userInfo)")
                }
            })
            let defaultPersistentStore = container.persistentStoreCoordinator.persistentStores.last
            print("Default store is located here: \(defaultPersistentStore!.url!)")

            //Migrating default store to new Seam store
            do {
                try persistentStoreCoordinator.migratePersistentStore(defaultPersistentStore!, to: newURL, options: nil, withType:SMStore.type)
            }
            catch {
                fatalError("Failed to migrate to Seam store: \(error)")
            }

            //Setting additional parameters to Seam store to make it able to use CloudKit
            let storeDescription = NSPersistentStoreDescription(url: newURL)
            storeDescription.type = SMStore.type
            storeDescription.setOption("iCloud.iGlock.CafeManager.com" as NSString, forKey: SMStore.SMStoreContainerOption)
            storeDescription.setOption(NSNumber(value:SMSyncConflictResolutionPolicy.clientTellsWhichWins.rawValue), forKey:SMStore.SMStoreSyncConflictResolutionPolicyOption)
            container.persistentStoreDescriptions=[storeDescription]
            SMStore.syncAutomatically = true
            return container
        }


问:
How to Convert between Interface derived types?
In the most simplest for here is what I want to do:

```<code>interface InterfaceA
{
    string var1 { get; set; }
    string var2 { get; set; }
}

public class DerivedA : InterfaceA
{
    public string var1 { get; set; }
    public string var2 { get; set; }
}

public class DerivedB : InterfaceA
{
    public string var1 { get; set; }
    public string var2 { get; set; }
}

public class DoEverything
{
    InterfaceA A = new DerivedA();
    InterfaceA B = new DerivedB();

    A.var1 = "Test1";
    A.var2 = "Test2";

    B = ConvertObject<DerivedB>(A);

    write(B.var1 + ", " + B.var2);

    // This doesn't work, I would like it to though.
    public T ConvertObject<T>(object obj)
    {
        T result = (T)typeof(T).GetConstructor(new Type[] { }).Invoke(new object[] { });

        foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
        {
            if (propertyInfo.CanRead)
            {
                try
                {
                    object value = propertyInfo.GetValue(obj, null);
                    propertyInfo.SetValue(result, value, null);
                }
                catch { }
            }
        }

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

Right now I have to manually convert each property in my objects and when a new property is added I have to remember to go the conversion methods and add it. I would much prefer that this be done automatically.

Any help would be greatly appreciated.

thanks in advance

答: You need to implement operator overloading for both derived classes:</p>

Body:
In the most simplest for here is what I want to do:

interface InterfaceA
{
    string var1 { get; set; }
    string var2 { get; set; }
}

public class DerivedA : InterfaceA
{
    public string var1 { get; set; }
    public string var2 { get; set; }
}

public class DerivedB : InterfaceA
{
    public string var1 { get; set; }
    public string var2 { get; set; }
}

public class DoEverything
{
    InterfaceA A = new DerivedA();
    InterfaceA B = new DerivedB();

    A.var1 = "Test1";
    A.var2 = "Test2";

    B = ConvertObject<DerivedB>(A);

    write(B.var1 + ", " + B.var2);

    // This doesn't work, I would like it to though.
    public T ConvertObject<T>(object obj)
    {
        T result = (T)typeof(T).GetConstructor(new Type[] { }).Invoke(new object[] { });

        foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
        {
            if (propertyInfo.CanRead)
            {
                try
                {
                    object value = propertyInfo.GetValue(obj, null);
                    propertyInfo.SetValue(result, value, null);
                }
                catch { }
            }
        }

        return result;
    }
}

Right now I have to manually convert each property in my objects and when a new property is added I have to remember to go the conversion methods and add it. I would much prefer that this be done automatically.

Any help would be greatly appreciated.

thanks in advance


问:
What happens when async code attempts to resume on a thread that is already executing?
I feel that the answer to this is due to me having an incorrect concept of how threads work, but here goes.

```<code>private void button1_Click(object sender, EventArgs e)
{
  this.TestMethodAsync();   // No await, i.e. fire and forget

  // ** Some code here to perform long running calculation (1) **
}

private async Task TestMethodAsync()
{
  // Some synchronous stuff

  await Task.Delay(1000);

  // ** Some code here to perform long running calculation (2) **
}
</code>```

First of all, I would not "fire and forget" an asynchronous method like this (I would use Task.Run) but I've come across code that does, and I'm trying to understand what the effect is.

In a WinForms application, which uses a WindowsFormsSynchronizationContext, my understanding of async and await tells me that when I click button1, the method will start synchronously on the UI thread. It will call TestMethodAsync and run synchronously until it reaches the await. It will then capture the context, start the Task.Delay task, and yield control to the caller. Since we are not awaiting this call, button1_Click will continue on the UI thread and start performing calculation (1).

At some point, Task.Delay(1000) will complete. A continuation will then run the remainder of the TestMethodAsync method using the captured context, which in this case means that the continuation will be run on the  UI thread. This will now start performing calculation (2).

We now have two separate sections of code wanting to run on the same thread (the UI thread) at the same time. My investigations into this seem to suggest that the thread switches back and forth between the two sections of code in order to perform them both.

QUESTION:

I'm confused about exactly what is going on here. How is it possible to resume on a thread that is already running other code? What forces the thread to switch between the two sections of code that want to run? In general, what happens when you attempt to resume on a thread that is already running some other code?

(I suppose this isn't any different to how my click event runs on the UI thread in the first place, in as much as I know it runs on the UI thread, and I know the UI thread is also doing other stuff, but I've not really thought about it like this before.)

答:
This is the secret that you do not understand: I give you the Windows Message Loop

```<code>int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    MSG msg;
    BOOL bRet;
    while(TRUE)
    {
        bRet = GetMessage(&msg, NULL, 0, 0);
        if (bRet <= 0) break;
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return msg.wParam;
}
</code>```

This is the actual "main" of your application; you just don't see it because it is hidden behind the scenes.

A simpler loop could not be imagined. It gets a message from the queue. If there are no more messages then the program must be done. If there was a message then it runs the standard message translations and dispatches the message, and then keeps on running.

How is it possible to resume on a thread that is already running other code?

It isn't. "Resuming on a thread that is running other code" is actually putting a message in the queue.  That "other code" is being synchronously called by DispatchMessage. When it is done, it returns to the loop, the queue is polled, and the message indicates what code needs to be dispatched next. That then runs synchronously until it returns back to the loop.

What forces the thread to switch between the two sections of code that want to run?

Nothing. That doesn't happen.

In general, what happens when you attempt to resume on a thread that is already running some other code?

The message that describes what continuation needs to be run is queued up.

I suppose this isn't any different to how my click event runs on the UI thread in the first place, in as much as I know it runs on the UI thread, and I know the UI thread is also doing other stuff, but I've not really thought about it like this before.

Start thinking about it.

Click events are exactly the same. Your program is doing something; you click the mouse; the click hander does not interrupt the UI thread and start running new work on it. Rather, the message is queued up, and when your UI thread control returns to the message loop, the click is eventually processed; DispatchMessage causes Button1_OnClick to be invoked via some mechanism in Windows Forms.  That's what WinForms is; a mechanism for translating Windows messages into calls to C# methods.

But you already knew that.  You know that when an event-driven program does a long-running synchronous operation, that the UI freezes, but that click events are processed eventually.  How did you think that happened?  You must have understood at some level that they were being queued up for processing later, right?

Exercise:  What does DoEvents do?

Exercise:  Given what you now know: what could possibly go wrong if you call DoEvents in a loop to unblock your UI?

Exercise: How is await different from DoEvents in a GUI application?

Body:
I feel that the answer to this is due to me having an incorrect concept of how threads work, but here goes.

private void button1_Click(object sender, EventArgs e)
{
  this.TestMethodAsync();   // No await, i.e. fire and forget

  // ** Some code here to perform long running calculation (1) **
}

private async Task TestMethodAsync()
{
  // Some synchronous stuff

  await Task.Delay(1000);

  // ** Some code here to perform long running calculation (2) **
}

First of all, I would not "fire and forget" an asynchronous method like this (I would use Task.Run) but I've come across code that does, and I'm trying to understand what the effect is.

In a WinForms application, which uses a WindowsFormsSynchronizationContext, my understanding of async and await tells me that when I click button1, the method will start synchronously on the UI thread. It will call TestMethodAsync and run synchronously until it reaches the await. It will then capture the context, start the Task.Delay task, and yield control to the caller. Since we are not awaiting this call, button1_Click will continue on the UI thread and start performing calculation (1).

At some point, Task.Delay(1000) will complete. A continuation will then run the remainder of the TestMethodAsync method using the captured context, which in this case means that the continuation will be run on the  UI thread. This will now start performing calculation (2).

We now have two separate sections of code wanting to run on the same thread (the UI thread) at the same time. My investigations into this seem to suggest that the thread switches back and forth between the two sections of code in order to perform them both.

QUESTION:

I'm confused about exactly what is going on here. How is it possible to resume on a thread that is already running other code? What forces the thread to switch between the two sections of code that want to run? In general, what happens when you attempt to resume on a thread that is already running some other code?

(I suppose this isn't any different to how my click event runs on the UI thread in the first place, in as much as I know it runs on the UI thread, and I know the UI thread is also doing other stuff, but I've not really thought about it like this before.)

Body:
This is the secret that you do not understand: I give you the Windows Message Loop

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    MSG msg;
    BOOL bRet;
    while(TRUE)
    {
        bRet = GetMessage(&msg, NULL, 0, 0);
        if (bRet <= 0) break;
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return msg.wParam;
}

This is the actual "main" of your application; you just don't see it because it is hidden behind the scenes.

A simpler loop could not be imagined. It gets a message from the queue. If there are no more messages then the program must be done. If there was a message then it runs the standard message translations and dispatches the message, and then keeps on running.

How is it possible to resume on a thread that is already running other code?

It isn't. "Resuming on a thread that is running other code" is actually putting a message in the queue.  That "other code" is being synchronously called by DispatchMessage. When it is done, it returns to the loop, the queue is polled, and the message indicates what code needs to be dispatched next. That then runs synchronously until it returns back to the loop.

What forces the thread to switch between the two sections of code that want to run?

Nothing. That doesn't happen.

In general, what happens when you attempt to resume on a thread that is already running some other code?

The message that describes what continuation needs to be run is queued up.

I suppose this isn't any different to how my click event runs on the UI thread in the first place, in as much as I know it runs on the UI thread, and I know the UI thread is also doing other stuff, but I've not really thought about it like this before.

Start thinking about it.

Click events are exactly the same. Your program is doing something; you click the mouse; the click hander does not interrupt the UI thread and start running new work on it. Rather, the message is queued up, and when your UI thread control returns to the message loop, the click is eventually processed; DispatchMessage causes Button1_OnClick to be invoked via some mechanism in Windows Forms.  That's what WinForms is; a mechanism for translating Windows messages into calls to C# methods.

But you already knew that.  You know that when an event-driven program does a long-running synchronous operation, that the UI freezes, but that click events are processed eventually.  How did you think that happened?  You must have understood at some level that they were being queued up for processing later, right?

Exercise:  What does DoEvents do?

Exercise:  Given what you now know: what could possibly go wrong if you call DoEvents in a loop to unblock your UI?

Exercise: How is await different from DoEvents in a GUI application?


问:
Sort a numpy array of numpy arrays by lengths of the internal arrays
If I have a numpy array with each element being another numpy array of varying lengths (not an ndarray because of this), how can I sort the outer array by descending lengths of the inner array?

For example:

```<code>a = np.array([np.array([1]), np.array([1, 2, 3]), np.array([1, 2])])
</code>```

would be sorted as:

```<code>[[1, 2, 3], [1, 2], [1]]
</code>```

答:
An alternative could be to just sort by length the old Python way for lists and then reconstruct an array. </p>

```<code>np.array(sorted(b, key=len, reverse=True))
</code>```

<p>Remaining in NumPy-land probably isn't providing you any benefits here anyways.  </p>

Body:
If I have a numpy array with each element being another numpy array of varying lengths (not an ndarray because of this), how can I sort the outer array by descending lengths of the inner array?

For example:

a = np.array([np.array([1]), np.array([1, 2, 3]), np.array([1, 2])])

would be sorted as:

[[1, 2, 3], [1, 2], [1]]

Body:
An alternative could be to just sort by length the old Python way for lists and then reconstruct an array.

np.array(sorted(b, key=len, reverse=True))

Remaining in NumPy-land probably isn't providing you any benefits here anyways.


问:
How do I Input comma sign without Number format in java
I wrote this code with out number format class.
My Question Is: Is there any way to make this process shorter without Number Format Class.</p>

```<code>String num=JOptionPane.showInputDialog("enter number");
Int len=num.length();
String res="";

if (len==4){
res=num.charAt(0)+","+num.substring(1);

}

else if(len==5){
res=num.substring(0,2)+","+num.substring(2);
}

else if(len==6){
res=num.substring(0,3)+","+num.substring(3);
}

else if(len==7){
res=num.charAt(0)+","+num.substring(1,4)+","+num.substring(4);
}

else if(len==8){
res=num.substring(0,2)+","+num.substring(2,5)+","+num.substring(5);
}

else if(len==9){
res=num.substring(0,3)+","+num.substring(3,6)+","+num.substring(6);
}

else if(len==10){
res=num.charAt(0)+","+num.substring(1,4)+","+num.substring(4,7)+","+num.substring(7);
}

System.out.println(res);
</code>```

答:
Something like the following:</p>

```<code>public static void main(String[] args) {
        int myInt = 1234567890;
        StringBuilder str = new StringBuilder(String.valueOf(myInt));

        int length = str.length();
        int count = 0;

        for (int i = length; i > 0; i--) {
            count++;

            if (count % 3 == 0 && count != length) {
                str.insert(i - 1, ",");
            }
        }
        System.out.println("Formatted Number: " + str);

    }
</code>```

Body:
I wrote this code with out number format class.
My Question Is: Is there any way to make this process shorter without Number Format Class.

String num=JOptionPane.showInputDialog("enter number");
Int len=num.length();
String res="";

if (len==4){
res=num.charAt(0)+","+num.substring(1);

}

else if(len==5){
res=num.substring(0,2)+","+num.substring(2);
}

else if(len==6){
res=num.substring(0,3)+","+num.substring(3);
}

else if(len==7){
res=num.charAt(0)+","+num.substring(1,4)+","+num.substring(4);
}

else if(len==8){
res=num.substring(0,2)+","+num.substring(2,5)+","+num.substring(5);
}

else if(len==9){
res=num.substring(0,3)+","+num.substring(3,6)+","+num.substring(6);
}

else if(len==10){
res=num.charAt(0)+","+num.substring(1,4)+","+num.substring(4,7)+","+num.substring(7);
}

System.out.println(res);

Body:
Something like the following:

public static void main(String[] args) {
        int myInt = 1234567890;
        StringBuilder str = new StringBuilder(String.valueOf(myInt));

        int length = str.length();
        int count = 0;

        for (int i = length; i > 0; i--) {
            count++;

            if (count % 3 == 0 && count != length) {
                str.insert(i - 1, ",");
            }
        }
        System.out.println("Formatted Number: " + str);

    }


问:
R code: finding similar matches with a specified accuracy
I have two tables, and each contains a character variable, for instance in table g1 I have var1 with values such as 'girls leggings', 'leggings', 'leginggs', 'tops', and in g2 I have var2 with values 'girls tops', 'tops', 'leggings', 'long leggings'.
I am trying to compare these character  values  from two tables and based on accuracy match the rows which have  the  highest accuracy match

I thought I can use one to many merge and then just keep the records with the highest match, something like

g$comp<-levenshteinSim(g$var1, g$var2)

for each var1 to all var2 and then pick the row with the highest g$comp.
But since the table is  quite large, the one to many merge can result in really massive data set.
I wonder if there is a way to use the R loop process? Just can't imagine any more elegant and faster way of approaching this.

Any help will be highly appreciated.

Thank you

答:
```<code>library(dplyr)
library(purrr)
library(RecordLinkage)

tbl1 <- data_frame(var1 = c('girls leggings', 'leggings', 'leginggs', 'tops'),
                   var2 = c('girls tops', 'tops', 'leggings', 'long leggings'))

cross2(.x = tbl1$var1, .y = tbl1$var2, .filter = ~levenshteinSim(.x, .y) < 0.4) %>%
  map(set_names, c("var1", "var2")) %>% bind_rows()
</code>```

Output:

```<code># A tibble: 9 x 2
           var1          var2
          <chr>         <chr>
  1 girls leggings    girls tops
  2           tops    girls tops
  3           tops          tops
  4 girls leggings      leggings
  5       leggings      leggings
  6       leginggs      leggings
  7 girls leggings long leggings
  8       leggings long leggings
  9       leginggs long leggings
</code>```

Body:
library(dplyr)
library(purrr)
library(RecordLinkage)

tbl1 <- data_frame(var1 = c('girls leggings', 'leggings', 'leginggs', 'tops'),
                   var2 = c('girls tops', 'tops', 'leggings', 'long leggings'))

cross2(.x = tbl1$var1, .y = tbl1$var2, .filter = ~levenshteinSim(.x, .y) < 0.4) %>%
  map(set_names, c("var1", "var2")) %>% bind_rows()

Output:

# A tibble: 9 x 2
           var1          var2
          <chr>         <chr>
  1 girls leggings    girls tops
  2           tops    girls tops
  3           tops          tops
  4 girls leggings      leggings
  5       leggings      leggings
  6       leginggs      leggings
  7 girls leggings long leggings
  8       leggings long leggings
  9       leginggs long leggings


问:
How to pipe a string to process' STDIN?
I have a command that expects input from a pipe. For example, consider the famous cat command:

```<code>$ echo Hello | cat
Hello
</code>```

Suppose I have a string in a Perl 6 program that I want to pipe to the command:

```<code>use v6;

my $input = 'Hello'; # This is the string I want to pipe to the command.
my $proc  = run 'cat', :in($input);
</code>```

This does not work (I get no output). I can work around the problem by
invoking bash and echo:

```<code>my $proc  = run 'bash', '-c', "echo $input | cat";
</code>```

But is there a way I can do this without running bash and echo?

In Perl5, I could simply do my $pid = open my $fh, '|-', 'cat'; and then print $fh $str.

答:
Piping several commands is easy too. To achieve the equivalent of the pipe echo "Hello, world" | cat -n in Perl 6, and capture the output from the second command, you can do

```<code>my $p1 = run 'echo', 'Hello, world', :out;
my $p2 = run 'cat', '-n', :in($p1.out), :out;
say $p2.out.get;
</code>```

You can also feed the :in pipe directly from your program, by setting it to True, which will make the pipe available via .in method on the Proc:

```<code>my $p = run "cat", "-n", :in, :out;
$p.in.say: "Hello,\nworld!";
$p.in.close;
say $p.out.slurp: :close;
# OUTPUT: «1  Hello,␤
#          2  world!␤»
</code>```

Straight from the docs, btw

Title: How to pipe a string to process' STDIN?

Body:
I have a command that expects input from a pipe. For example, consider the famous cat command:

$ echo Hello | cat
Hello

Suppose I have a string in a Perl 6 program that I want to pipe to the command:

use v6;

my $input = 'Hello'; # This is the string I want to pipe to the command.
my $proc  = run 'cat', :in($input);

This does not work (I get no output). I can work around the problem by
invoking bash and echo:

my $proc  = run 'bash', '-c', "echo $input | cat";

But is there a way I can do this without running bash and echo?

In Perl5, I could simply do my $pid = open my $fh, '|-', 'cat'; and then print $fh $str.

Body:
Piping several commands is easy too. To achieve the equivalent of the pipe echo "Hello, world" | cat -n in Perl 6, and capture the output from the second command, you can do

my $p1 = run 'echo', 'Hello, world', :out;
my $p2 = run 'cat', '-n', :in($p1.out), :out;
say $p2.out.get;

You can also feed the :in pipe directly from your program, by setting it to True, which will make the pipe available via .in method on the Proc:

my $p = run "cat", "-n", :in, :out;
$p.in.say: "Hello,\nworld!";
$p.in.close;
say $p.out.slurp: :close;
# OUTPUT: «1  Hello,␤
#          2  world!␤»

Straight from the docs, btw