问:
Response getting back from the ibm mq is not match for the request sometimes
I copy the java client code for how to call IBM MQ, and pass the request to the queue, but sometimes I getting the wrong response back from the queue.

For example, if I submit the following request:
F                    LOYFI6331760101046481882

I expect from the response I should get
F                    LOYFA36331760101046481882

But actually I getting
F                    LOYFA36331760101051292448

As you can see the card number is wrong.

Here is the code

import javax.jms.BytesMessage;
import javax.jms.Destination;
import javax.jms.JMSConsumer;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.JMSProducer;
import javax.jms.TextMessage;

import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import com.ibm.msg.client.wmq.WMQConstants;

public class MQClient {
    // System exit status value (assume unset value to be 1)
    private static int status = 1;

    public static byte[] sendAndReceive(String HOST, Integer PORT, String QMGR, String CHANNEL, String requestQueue, String responseQueue, String payload) {
        // Variables
        JMSContext context = null;
        Destination destination = null;
        JMSProducer producer = null;
        JMSConsumer consumer = null;
        BytesMessage receivedMessage = null;
        byte[] result = null;
        try {
            // Create a connection factory
            JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
            JmsConnectionFactory cf = ff.createConnectionFactory();

            // Set the properties
            cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, HOST);
            cf.setIntProperty(WMQConstants.WMQ_PORT, PORT);
            cf.setStringProperty(WMQConstants.WMQ_CHANNEL, CHANNEL);
            cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
            cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, QMGR);
            cf.setStringProperty(WMQConstants.WMQ_APPLICATIONNAME, "JmsPutGet (JMS)");
            cf.setStringProperty(WMQConstants.WMQ_TARGET_CLIENT, "1");
            // Create JMS objects
            context = cf.createContext();
            destination = context.createQueue("queue:///" + requestQueue +"?targetClient=1");

            TextMessage message = context.createTextMessage(payload);

            producer = context.createProducer();
            producer.send(destination, message);
            System.out.println("Sent message:\n" + message);

            destination = context.createQueue("queue:///" + responseQueue + "?targetClient=1");
            consumer = context.createConsumer(destination); // autoclosable
            receivedMessage= (BytesMessage)consumer.receive();
            System.out.println("Receiving message:" + receivedMessage);
            int text_length = new Long(receivedMessage.getBodyLength()).intValue();
            result = new byte[text_length];
            receivedMessage.readBytes(result, text_length);

            System.out.println("\nReceived message:\n" + new String(result));

            recordSuccess();

        } catch (JMSException jmsex) {
            recordFailure(jmsex);
        }finally {
            context.close();
        }

        return result;

    }
}
```

I have another project to run concurrently to call MQClient.sendAndReceive() method, with same host, port, QMGR, channel, requestQueue and responseQueue, only payload is different.

So how do I fix the code above to make sure I always getting the correct response corresponding to the request?

EDIT:
1. For JoshMac questions, app means the IBM MQ one? Or the app that will call my sendAndReceive function?

Here is the flow I have, I using mule flow take the request from the POS, process the request, which need to call IBM MQ (which sit on AS400), to get the response back from MQ, and send back to POS. (In this example, I need to submit my request to INQ1 and get the response from INQR1). Based on the answer below, it seems like the sendAndReceive function is treat as Requester, I need another flow to call the Responder to handle the response, so receivedMessage= (BytesMessage)consumer.receive(); will not getting stuck? Correct me if I am wrong

答:
Can you use different topic to differentiate?

That's a bad idea when you are doing point-to-point messaging.

```<code>destination = context.createQueue("queue:///" + responseQueue + "?targetClient=1");
</code>```

It sounds like your responseQueue is shared between multiple consumers.  You have 2 options:

Create your own temporary dynamic queue and set it as the "Reply-To"
queue

i.e.

```<code>Queue replyQ = session.createTemporaryQueue();
</code>```

Use MsgId / CorrelId request-reply messaging pattern.

i.e. Follow the suggestions on this page: Not able to get response from IBM MQ using JMS application

Body:
I copy the java client code for how to call IBM MQ, and pass the request to the queue, but sometimes I getting the wrong response back from the queue.

For example, if I submit the following request:
F                    LOYFI6331760101046481882

I expect from the response I should get
F                    LOYFA36331760101046481882

But actually I getting
F                    LOYFA36331760101051292448

As you can see the card number is wrong.

Here is the code

import javax.jms.BytesMessage;
import javax.jms.Destination;
import javax.jms.JMSConsumer;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.JMSProducer;
import javax.jms.TextMessage;

import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import com.ibm.msg.client.wmq.WMQConstants;

public class MQClient {
    // System exit status value (assume unset value to be 1)
    private static int status = 1;

    public static byte[] sendAndReceive(String HOST, Integer PORT, String QMGR, String CHANNEL, String requestQueue, String responseQueue, String payload) {
        // Variables
        JMSContext context = null;
        Destination destination = null;
        JMSProducer producer = null;
        JMSConsumer consumer = null;
        BytesMessage receivedMessage = null;
        byte[] result = null;
        try {
            // Create a connection factory
            JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
            JmsConnectionFactory cf = ff.createConnectionFactory();

            // Set the properties
            cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, HOST);
            cf.setIntProperty(WMQConstants.WMQ_PORT, PORT);
            cf.setStringProperty(WMQConstants.WMQ_CHANNEL, CHANNEL);
            cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
            cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, QMGR);
            cf.setStringProperty(WMQConstants.WMQ_APPLICATIONNAME, "JmsPutGet (JMS)");
            cf.setStringProperty(WMQConstants.WMQ_TARGET_CLIENT, "1");
            // Create JMS objects
            context = cf.createContext();
            destination = context.createQueue("queue:///" + requestQueue +"?targetClient=1");

            TextMessage message = context.createTextMessage(payload);

            producer = context.createProducer();
            producer.send(destination, message);
            System.out.println("Sent message:\n" + message);

            destination = context.createQueue("queue:///" + responseQueue + "?targetClient=1");
            consumer = context.createConsumer(destination); // autoclosable
            receivedMessage= (BytesMessage)consumer.receive();
            System.out.println("Receiving message:" + receivedMessage);
            int text_length = new Long(receivedMessage.getBodyLength()).intValue();
            result = new byte[text_length];
            receivedMessage.readBytes(result, text_length);

            System.out.println("\nReceived message:\n" + new String(result));

            recordSuccess();

        } catch (JMSException jmsex) {
            recordFailure(jmsex);
        }finally {
            context.close();
        }

        return result;

    }
}

I have another project to run concurrently to call MQClient.sendAndReceive() method, with same host, port, QMGR, channel, requestQueue and responseQueue, only payload is different.

So how do I fix the code above to make sure I always getting the correct response corresponding to the request?

EDIT:
1. For JoshMac questions, app means the IBM MQ one? Or the app that will call my sendAndReceive function?

Here is the flow I have, I using mule flow take the request from the POS, process the request, which need to call IBM MQ (which sit on AS400), to get the response back from MQ, and send back to POS. (In this example, I need to submit my request to INQ1 and get the response from INQR1). Based on the answer below, it seems like the sendAndReceive function is treat as Requester, I need another flow to call the Responder to handle the response, so receivedMessage= (BytesMessage)consumer.receive(); will not getting stuck? Correct me if I am wrong

Body:
Can you use different topic to differentiate?

That's a bad idea when you are doing point-to-point messaging.

destination = context.createQueue("queue:///" + responseQueue + "?targetClient=1");

It sounds like your responseQueue is shared between multiple consumers.  You have 2 options:

Create your own temporary dynamic queue and set it as the "Reply-To"
queue

i.e.

Queue replyQ = session.createTemporaryQueue();

Use MsgId / CorrelId request-reply messaging pattern.

i.e. Follow the suggestions on this page: Not able to get response from IBM MQ using JMS application


来源: stackexchange

问:
How to split a long number into pairs of digits
I have a string of a long number 12345678 and want to convert it to an array like this :

```<code>["12", "34", "56", "78"].
</code>```

I have tried array.split(//).map { |e| e.to_i  }  but it does

```<code>["1", "2", "3", "4", "5", "6", "7", "8"]
</code>```

答:
You can use

p = 123456789.to_s
(0..p.length).each_cons(2).map {|i, j| "#{p[i]}#{p[j]}" if i%2 == 0}.compact

ContentLicense: CC BY-SA 4.0

Body:
I have a string of a long number 12345678 and want to convert it to an array like this :

["12", "34", "56", "78"].

I have tried array.split(//).map { |e| e.to_i  }  but it does

["1", "2", "3", "4", "5", "6", "7", "8"]


问:
Resize all images in all sub-directories of directory
I have a directory that is structured as such:

```<code>├── directory
|   ├── sub-directory_1
|   |   ├── img1.jpg
|   |   └── img2.jpg
|   |
|   ├── sub-directory_2
|   |   ├── img1.jpg
|   |   └── img2.jpg
.   .
.   .
.   .
    .
|   └── sub-directory_n
|   |   ├── img1.jpg
|   |   └── img2.jpg
</code>```

I have this code that resizes all images in a directory:

```<code>from PIL import Image
import os, sys

path = "/directory"
dirs = os.listdir( path )

def resize():
    for item in dirs:
        if os.path.isfile(path+item):
            im = Image.open(path+item)
            f, e = os.path.splitext(path+item)
            imResize = im.resize((64,64), Image.ANTIALIAS)
            imResize.save(f + 'r.jpg', 'JPEG', quality=90)

resize()
</code>```

Is there a way that I can modify it so that it iteratively resizes all the images in the sub directories?

答:
Does this fit the bill

```<code>from PIL import Image
import os, sys

dir_path = "/directory"

def resize_im(path):
    if os.path.isfile(path):
        im = Image.open(path).resize((64,64), Image.ANTIALIAS)
        parent_dir = os.path.dirname(path)
        img_name = os.path.basename(path).split('.')[0]
        im.save(os.path.join(parent_dir, img_name + 'r.jpg'), 'JPEG', quality=90)

def resize_all(mydir):
    for subdir , _ , fileList in os.walk(mydir):
        for f in fileList:
            try:
                full_path = os.path.join(subdir,f)
                resize_im(full_path)
            except Exception as e:
                print('Unable to resize %s. Skipping.' % full_path)

if __name__ == '__main__':
    resize_all(dir_path)
</code>```

Be careful when you save the resized image inside the same directory of the source image. If you run your code twice, it will create lots of extra resized images.

Body:
I have a directory that is structured as such:

├── directory
|   ├── sub-directory_1
|   |   ├── img1.jpg
|   |   └── img2.jpg
|   |
|   ├── sub-directory_2
|   |   ├── img1.jpg
|   |   └── img2.jpg
.   .
.   .
.   .
    .
|   └── sub-directory_n
|   |   ├── img1.jpg
|   |   └── img2.jpg

I have this code that resizes all images in a directory:

from PIL import Image
import os, sys

path = "/directory"
dirs = os.listdir( path )

def resize():
    for item in dirs:
        if os.path.isfile(path+item):
            im = Image.open(path+item)
            f, e = os.path.splitext(path+item)
            imResize = im.resize((64,64), Image.ANTIALIAS)
            imResize.save(f + 'r.jpg', 'JPEG', quality=90)

resize()

Is there a way that I can modify it so that it iteratively resizes all the images in the sub directories?

Body:
Does this fit the bill

from PIL import Image
import os, sys

dir_path = "/directory"

def resize_im(path):
    if os.path.isfile(path):
        im = Image.open(path).resize((64,64), Image.ANTIALIAS)
        parent_dir = os.path.dirname(path)
        img_name = os.path.basename(path).split('.')[0]
        im.save(os.path.join(parent_dir, img_name + 'r.jpg'), 'JPEG', quality=90)

def resize_all(mydir):
    for subdir , _ , fileList in os.walk(mydir):
        for f in fileList:
            try:
                full_path = os.path.join(subdir,f)
                resize_im(full_path)
            except Exception as e:
                print('Unable to resize %s. Skipping.' % full_path)

if __name__ == '__main__':
    resize_all(dir_path)

Be careful when you save the resized image inside the same directory of the source image. If you run your code twice, it will create lots of extra resized images.


问:
Is there a way to solve the error of make rstan
I use CentOS6.8 ,R version is 3.4.0,gcc version is 4.47,when i use offline install by R CMD INSTALL rstan_2.14.1.tar.gz or higher version ,The error is:make *** [chains.o]Error 1,what is the chains.o and how can i solve it.Help!

```<code>/opt/R-3.4.0/library/BH/include/boost/throw_exception.hpp:In function`void boost::throw_exception(const E&)`:
/opt/R-3.4.0/library/BH/include/boost/throw_exception.hpp:70:error`enable_ both:` is not a member of `boost::exception_detail`
In file included from /opt/R-3.4.0/library/BH/include/boost/random/detail/integer_log2.hpp:19,
from /opt/R-3.4.0/library/BH/include/boost/random/detail/large_arithmetic.hpp:19,
from /opt/R-3.4.0/library/BH/include/boost/random/detail/const_mod.hpp:23,
from /opt/R-3.4.0/library/BH/include/boost/random/linear_congruential.hpp:30,
from /opt/R-3.4.0/library/BH/include/boost/random/additive_combine.hpp:27,
from chains.cpp:29:
/opt/R-3.4.0/library/BH/include/boost/pending/integer_log2.hpp:At global scope:
/opt/R-3.4.0/library/BH/include/boost/pending/integer_log2.hpp:7:note:#pragma message :This header is deprecated .Use <boost/integer/integer_log2.hpp> instead.
make: *** [chains.o] Error 1
Error:compilation failed for package `rstan`
</code>```

答:
I got the same error on Azure with a virtual machine Standard_F2s_v2, Ubuntu 19.04, R 3.4.3, and g++ (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609 because I was using

devtools::install_deps(dependencies = TRUE)
```

<p>and my <code>DESCRIPTION</code> had:</p>

```Imports:
    rstan (>= 2.18.2),
```

<p>The solution was to install packages separately without versions:</p>

<pre class="lang-r prettyprint-override"><code>.libPaths(c("~/R/x86_64-pc-linux-gnu-library/3.4", .libPaths()))
options(repos=structure(c(CRAN = "https://cran.r-project.org")))
packages <- c("devtools", ..., "rstan")
for (p in packages) {
  install.packages(p)
}
</code>```

See this Github branch, commit 1b3d1f6, for the full details of the successful build.

Body:
I use CentOS6.8 ,R version is 3.4.0,gcc version is 4.47,when i use offline install by R CMD INSTALL rstan_2.14.1.tar.gz or higher version ,The error is:make *** [chains.o]Error 1,what is the chains.o and how can i solve it.Help!

/opt/R-3.4.0/library/BH/include/boost/throw_exception.hpp:In function`void boost::throw_exception(const E&)`:
/opt/R-3.4.0/library/BH/include/boost/throw_exception.hpp:70:error`enable_ both:` is not a member of `boost::exception_detail`
In file included from /opt/R-3.4.0/library/BH/include/boost/random/detail/integer_log2.hpp:19,
from /opt/R-3.4.0/library/BH/include/boost/random/detail/large_arithmetic.hpp:19,
from /opt/R-3.4.0/library/BH/include/boost/random/detail/const_mod.hpp:23,
from /opt/R-3.4.0/library/BH/include/boost/random/linear_congruential.hpp:30,
from /opt/R-3.4.0/library/BH/include/boost/random/additive_combine.hpp:27,
from chains.cpp:29:
/opt/R-3.4.0/library/BH/include/boost/pending/integer_log2.hpp:At global scope:
/opt/R-3.4.0/library/BH/include/boost/pending/integer_log2.hpp:7:note:#pragma message :This header is deprecated .Use <boost/integer/integer_log2.hpp> instead.
make: *** [chains.o] Error 1
Error:compilation failed for package `rstan`

Body:
I got the same error on Azure with a virtual machine Standard_F2s_v2, Ubuntu 19.04, R 3.4.3, and g++ (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609 because I was using

devtools::install_deps(dependencies = TRUE)

and my DESCRIPTION had:

Imports:
    rstan (>= 2.18.2),

The solution was to install packages separately without versions:

.libPaths(c("~/R/x86_64-pc-linux-gnu-library/3.4", .libPaths()))
options(repos=structure(c(CRAN = "https://cran.r-project.org")))
packages <- c("devtools", ..., "rstan")
for (p in packages) {
  install.packages(p)
}

See this Github branch, commit 1b3d1f6, for the full details of the successful build.


问:
Url to raw github csv keeps changing when I try to download to google colab
I am trying to download a large .csv file from where I have it stored in my github to a notebook I have in google colab. Here is the scheme of the code I am using:

#download fixed data sets
import pandas as pd
import numpy as np
url_train = 'https://raw.githubusercontent.com/username/data/master/train_fixed.csv?token=[long_string]'
x_train = pd.read_csv(url_train)

```

Usually this will work fun. Frequently, however, (but not always) if I close the notebook and re-open a day later, if I just re-run the code I get a 404 not found error for the URL, and have to go back to github and recopy the (now changed) raw URL for my file.

I am not sure why this is happening or what I was sure, and I wanted to ask if anyone else has experienced this problem and what solutions you would recommend. Perhaps the problem is because this repo is private?

答: If the repo is private, it's likely that the token argument expires so that accidental disclosure of the URL does not prevent access to the data without possibility of revocation. My recommendation is to arrange to construct the URL dynamically after fetching the token parameter in the context of your current session.

Body:
I am trying to download a large .csv file from where I have it stored in my github to a notebook I have in google colab. Here is the scheme of the code I am using:

#download fixed data sets
import pandas as pd
import numpy as np
url_train = 'https://raw.githubusercontent.com/username/data/master/train_fixed.csv?token=[long_string]'
x_train = pd.read_csv(url_train)

Usually this will work fun. Frequently, however, (but not always) if I close the notebook and re-open a day later, if I just re-run the code I get a 404 not found error for the URL, and have to go back to github and recopy the (now changed) raw URL for my file.

I am not sure why this is happening or what I was sure, and I wanted to ask if anyone else has experienced this problem and what solutions you would recommend. Perhaps the problem is because this repo is private?


问:
How to highlight an item from flatlist and show delete option to delete that item from the list on long press of that item?
I want to highlight an item from the flatlist on long press of that item and show delete option to delete that item from the list.

```<code>    renderFlatlist = () => {
    return (
      <View style={styles.flatListContainer}>
        <FlatList
          style={styles.flatListStyle}
          showsVerticalScrollIndicator={false}
          data={this.state.fetchProjectDetail}
          keyExtractor={(item, index) => index.toString()}
          renderItem={this._renderItem}
        />
      </View>
    );
  };

  _renderItem = ({ item }) => {
    console.log("_renderItem", item.id);
    return (
      <TouchableOpacity
        style={{ marginTop: 10 }}
        onLongPress={this._handleLongPress(item)}
        onPress={() => {
          this.props.navigation.navigate("CreateProject", {
            database: this.props.navigation.state.params.database,
            id: item.id,
            from: "edit"
          });
        }}
      >
        <Text>Project Name: {item.project_name}</Text>
      </TouchableOpacity>
    );
  };

  _handleLongPress = item => {
    Alert.alert("LongPress");
  };
</code>```

I have done this much, but when I render the list that alert keeps popping up without long press of that item from the list. And how do I highlight the item on long press and display a delete option to delete the item from list.

答:
You are invoking the handler right away, but it needs to be a callback, i.e. () => this._handleLongPress(item). From there you can set whatever state you need to highlight that row.

I suggest using an auxiliary data structure to track which items have been long pressed. Here's an example where I use a map to store the item id of selected items and apply a highlighting style. If you haven't the need for multiple selected you could just save the selected id by itself.

The trick here is to use react's FlatList extraData prop as a tigger to re-render the list as the data prop is unchanged (for good reason, you shouldn't mutate your data source inside components).

codesandbox

Body:
I want to highlight an item from the flatlist on long press of that item and show delete option to delete that item from the list.

    renderFlatlist = () => {
    return (
      <View style={styles.flatListContainer}>
        <FlatList
          style={styles.flatListStyle}
          showsVerticalScrollIndicator={false}
          data={this.state.fetchProjectDetail}
          keyExtractor={(item, index) => index.toString()}
          renderItem={this._renderItem}
        />
      </View>
    );
  };

  _renderItem = ({ item }) => {
    console.log("_renderItem", item.id);
    return (
      <TouchableOpacity
        style={{ marginTop: 10 }}
        onLongPress={this._handleLongPress(item)}
        onPress={() => {
          this.props.navigation.navigate("CreateProject", {
            database: this.props.navigation.state.params.database,
            id: item.id,
            from: "edit"
          });
        }}
      >
        <Text>Project Name: {item.project_name}</Text>
      </TouchableOpacity>
    );
  };

  _handleLongPress = item => {
    Alert.alert("LongPress");
  };

I have done this much, but when I render the list that alert keeps popping up without long press of that item from the list. And how do I highlight the item on long press and display a delete option to delete the item from list.


问:
How to process multidimensional array from jQuery Sortable (nested list)?
I'm working with jQuery Sortable to create some block of codes with nested list ( for loop and function block), then I got this json string use JSON.stringify on console.log(jsonString):

```<code>{
  "codes": [
    [
      {
        "id": "code_run",
        "code": "run",
        "name": "code_when_run"
      },
      {
        "id": "",
        "code": "loop",
        "name": "code_block_repeat",
        "children": [
          [
            {
              "id": "",
              "code": "up",
              "name": "code_arrow_up"
            },
            {
              "id": "",
              "code": "up",
              "name": "code_arrow_up"
            }
          ]
        ]
      }
    ]
  ]
}
</code>```

Here's my code from the jQuery sortable's example :

```<code>let oldContainer, codeBlockId, codeBlockItem;

$("ol.nest_workspace").sortable({
    group: 'nested',
    onDragStart: function ($item, container, _super) {
    // Duplicate items of the no drop area
    if(!container.options.drop)
      $item.clone().insertAfter($item);
    _super($item, container);
  },
    afterMove: function (placeholder, container) {

        if(oldContainer != container){
            if(oldContainer)
                oldContainer.el.removeClass("active");
            container.el.addClass("active");

            oldContainer = container;
        }
    },
    onDrop: function ($item, container, _super) {
        container.el.removeClass("active");

        $item.addClass("block_code_on_workspace");

        var data = group.sortable("serialize").get();

    var jsonString = JSON.stringify({"codes":data}, null, '\t');
        console.log(jsonString);
        _super($item, container);

    },

});
</code>```

How can I process the sub array (children[]) ?

I have plan to make it all block as a real codes, so it could execute with another function.

I may expect the text output printed some function like moveUp(), or if its loop with some function inside, then would be like :

```<code>for (var i = 0; i < 3; i++) {
  moveUp();
}
</code>```

Any help or suggest would be great, thanks!

答:
If your JSON string will always look like this. Then you can target there  “children" array like this.

I wrote this code base only on the format of the JSON that you have above.

```<code>const childrenArr = jsonString.codes[0][1].children;
</code>```

Based on the code we’re you are stringifying your data this code should work.

var jsonString = JSON.stringify({"codes":data}, null, '\t');
        console.log(jsonString),
    ChildrenArr = jsonString.codes[0][1].children;

Body:
I'm working with jQuery Sortable to create some block of codes with nested list ( for loop and function block), then I got this json string use JSON.stringify on console.log(jsonString):

{
  "codes": [
    [
      {
        "id": "code_run",
        "code": "run",
        "name": "code_when_run"
      },
      {
        "id": "",
        "code": "loop",
        "name": "code_block_repeat",
        "children": [
          [
            {
              "id": "",
              "code": "up",
              "name": "code_arrow_up"
            },
            {
              "id": "",
              "code": "up",
              "name": "code_arrow_up"
            }
          ]
        ]
      }
    ]
  ]
}

Here's my code from the jQuery sortable's example :

let oldContainer, codeBlockId, codeBlockItem;

$("ol.nest_workspace").sortable({
    group: 'nested',
    onDragStart: function ($item, container, _super) {
    // Duplicate items of the no drop area
    if(!container.options.drop)
      $item.clone().insertAfter($item);
    _super($item, container);
  },
    afterMove: function (placeholder, container) {

        if(oldContainer != container){
            if(oldContainer)
                oldContainer.el.removeClass("active");
            container.el.addClass("active");

            oldContainer = container;
        }
    },
    onDrop: function ($item, container, _super) {
        container.el.removeClass("active");

        $item.addClass("block_code_on_workspace");

        var data = group.sortable("serialize").get();

    var jsonString = JSON.stringify({"codes":data}, null, '\t');
        console.log(jsonString);
        _super($item, container);

    },

});

How can I process the sub array (children[]) ?

I have plan to make it all block as a real codes, so it could execute with another function.

I may expect the text output printed some function like moveUp(), or if its loop with some function inside, then would be like :

for (var i = 0; i < 3; i++) {
  moveUp();
}

Any help or suggest would be great, thanks!

Body:
If your JSON string will always look like this. Then you can target there  “children" array like this.

I wrote this code base only on the format of the JSON that you have above.

const childrenArr = jsonString.codes[0][1].children;

Based on the code we’re you are stringifying your data this code should work.

var jsonString = JSON.stringify({"codes":data}, null, '\t');
        console.log(jsonString),
    ChildrenArr = jsonString.codes[0][1].children;


问:
How to get domain name from URL
How can I fetch a domain name from a URL String?

Examples:

```<code>+----------------------+------------+
| input                | output     |
+----------------------+------------+
| www.google.com       | google     |
| www.mail.yahoo.com   | mail.yahoo |
| www.mail.yahoo.co.in | mail.yahoo |
| www.abc.au.uk        | abc        |
+----------------------+------------+
</code>```

Related:

Matching a web address through regex

答:
I know the question is seeking a regex solution but in every attempt it won't work to cover everything

I decided to write this method in Python which only works with urls that have a subdomain (i.e. www.mydomain.co.uk) and not multiple level subdomains like www.mail.yahoo.com

```<code>def urlextract(url):
  url_split=url.split(".")
  if len(url_split) <= 2:
      raise Exception("Full url required with subdomain:",url)
  return {'subdomain': url_split[0], 'domain': url_split[1], 'suffix': ".".join(url_split[2:])}
</code>```

OwnerDisplayName: Chinmay

Title: How to get domain name from URL

Body:
How can I fetch a domain name from a URL String?

Examples:

+----------------------+------------+
| input                | output     |
+----------------------+------------+
| www.google.com       | google     |
| www.mail.yahoo.com   | mail.yahoo |
| www.mail.yahoo.co.in | mail.yahoo |
| www.abc.au.uk        | abc        |
+----------------------+------------+

Related:

Matching a web address through regex

Body:
I know the question is seeking a regex solution but in every attempt it won't work to cover everything

I decided to write this method in Python which only works with urls that have a subdomain (i.e. www.mydomain.co.uk) and not multiple level subdomains like www.mail.yahoo.com

def urlextract(url):
  url_split=url.split(".")
  if len(url_split) <= 2:
      raise Exception("Full url required with subdomain:",url)
  return {'subdomain': url_split[0], 'domain': url_split[1], 'suffix': ".".join(url_split[2:])}


问:
FigureCanvas is never shown even when draw is called
I am trying to embed a matplotlib figure in my QT application, using which I want to show different plots upon different user actions.

I have created a custom figure canvas, in which I initialize a figure and a subplot. The code is as followed:

```<code>from matplotlib.backends.backend_qt5 import FigureCanvasQT, FigureManagerQT
from PyQt5 import QtWidgets
import matplotlib.pyplot as plt
import numpy as np

class CustomFigureCanvas(FigureCanvasQT):
    def __init__(self, parent=None, cmap_name="coolwarm"):
        fig = plt.Figure()
        self.color_map = plt.get_cmap(cmap_name)
        self.axes = fig.add_subplot(111)
        super().__init__(fig)
        self.setParent(parent)
        self.setBaseSize(300, 300)
        self.setMaximumSize(400, 400)
        self.setMinimumSize(250, 250)
        self.setSizePolicy(
            QtWidgets.QSizePolicy.MinimumExpanding,
            QtWidgets.QSizePolicy.MinimumExpanding,
        )

    def set_clf_2d(self, clf_2d):
        self.clf = clf_2d

    def plot_new_datapoints(self, x2D):
        self.add_datapoint(x2D)

    @staticmethod
    def _make_meshgrid(x, y, h=0.02):
        x_min, x_max = x.min() - 1, x.max() + 1
        y_min, y_max = y.min() - 1, y.max() + 1
        XX, YY = np.meshgrid(
            np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)
        )
        return XX, YY

    def _plot_contours(self, xx, yy, **params):
        """Plot the decision boundaries for a classifier.

        Parameters
        ----------
        ax: matplotlib axes object
        clf: a classifier
        xx: meshgrid ndarray
        yy: meshgrid ndarray
        params: dictionary of params to pass to contourf, optional
        """
        Z = self.clf.predict(np.c_[xx.ravel(), yy.ravel()])
        Z = Z.reshape(xx.shape)
        self.axes.contourf(xx, yy, Z, **params)

    def plot_data(self, x2D, y):
        """plots the given array and the decision function bounday.

        Arguments:
            x2D {np.array} -- [2d array]
            y {np.array} -- [1d array]
        """

        x0, x1 = x2D[:, 0], x2D[:, 1]
        xx, yy = CustomFigureCanvas._make_meshgrid(x0, x1)
        labels = ["Cognitive", "Not Cognitive"]
        colors = ["r", "b"]
        self.axes.clear()
        self._plot_contours(xx, yy, cmap=self.color_map, alpha=0.8)
        target_ids = [0, 1]
        for i, c, label in zip(target_ids, colors, labels):
            print(i, label)
            self.axes.scatter(
                x0[y == i, 0],
                x1[y == i, 1],
                color=c,
                label=label,
                marker="o",
                s=(15, 15),
            )

        self.axes.set_xlim(xx.min(), xx.max())
        self.axes.set_ylim(yy.min(), yy.max())
        self.axes.set_title("2D Representation using PCA")
        self.axes.legend(fontsize=8)
        self.axes.plot()

    def add_datapoint(self, x2d):
        """Adds a new datapoint to the plot

        Arguments:
            x2d {a 2d single point, [x,y]} -- [np.array with shape (1,2)]
            axes {plt.axes} -- [description]

        """
        print(x2d, type(x2d))
        self.axes.scatter(
            x2d[:, 0],
            x2d[:, 1],
            color="k",
            label="Current Text",
            marker="o",
            s=(15, 15),
        )
        self.axes.legend(fontsize=8)
</code>```

My problem is that whatever I do, my FigureCanvas will always be filled with black, and won't be changed on any circumstances.

By using the CustomFigureCanvas you can reproduce my problem.

答: So I was just trying to mimic what was written in this post, and I tried using FigureCanvasQTAgg instead of FigureCanvasQT and suddenly everything started to work. I don't know why this exists, and the pyqt documentation is very unclear about these kinds of differences.

Body:
I am trying to embed a matplotlib figure in my QT application, using which I want to show different plots upon different user actions.

I have created a custom figure canvas, in which I initialize a figure and a subplot. The code is as followed:

from matplotlib.backends.backend_qt5 import FigureCanvasQT, FigureManagerQT
from PyQt5 import QtWidgets
import matplotlib.pyplot as plt
import numpy as np

class CustomFigureCanvas(FigureCanvasQT):
    def __init__(self, parent=None, cmap_name="coolwarm"):
        fig = plt.Figure()
        self.color_map = plt.get_cmap(cmap_name)
        self.axes = fig.add_subplot(111)
        super().__init__(fig)
        self.setParent(parent)
        self.setBaseSize(300, 300)
        self.setMaximumSize(400, 400)
        self.setMinimumSize(250, 250)
        self.setSizePolicy(
            QtWidgets.QSizePolicy.MinimumExpanding,
            QtWidgets.QSizePolicy.MinimumExpanding,
        )

    def set_clf_2d(self, clf_2d):
        self.clf = clf_2d

    def plot_new_datapoints(self, x2D):
        self.add_datapoint(x2D)

    @staticmethod
    def _make_meshgrid(x, y, h=0.02):
        x_min, x_max = x.min() - 1, x.max() + 1
        y_min, y_max = y.min() - 1, y.max() + 1
        XX, YY = np.meshgrid(
            np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)
        )
        return XX, YY

    def _plot_contours(self, xx, yy, **params):
        """Plot the decision boundaries for a classifier.

        Parameters
        ----------
        ax: matplotlib axes object
        clf: a classifier
        xx: meshgrid ndarray
        yy: meshgrid ndarray
        params: dictionary of params to pass to contourf, optional
        """
        Z = self.clf.predict(np.c_[xx.ravel(), yy.ravel()])
        Z = Z.reshape(xx.shape)
        self.axes.contourf(xx, yy, Z, **params)

    def plot_data(self, x2D, y):
        """plots the given array and the decision function bounday.

        Arguments:
            x2D {np.array} -- [2d array]
            y {np.array} -- [1d array]
        """

        x0, x1 = x2D[:, 0], x2D[:, 1]
        xx, yy = CustomFigureCanvas._make_meshgrid(x0, x1)
        labels = ["Cognitive", "Not Cognitive"]
        colors = ["r", "b"]
        self.axes.clear()
        self._plot_contours(xx, yy, cmap=self.color_map, alpha=0.8)
        target_ids = [0, 1]
        for i, c, label in zip(target_ids, colors, labels):
            print(i, label)
            self.axes.scatter(
                x0[y == i, 0],
                x1[y == i, 1],
                color=c,
                label=label,
                marker="o",
                s=(15, 15),
            )

        self.axes.set_xlim(xx.min(), xx.max())
        self.axes.set_ylim(yy.min(), yy.max())
        self.axes.set_title("2D Representation using PCA")
        self.axes.legend(fontsize=8)
        self.axes.plot()

    def add_datapoint(self, x2d):
        """Adds a new datapoint to the plot

        Arguments:
            x2d {a 2d single point, [x,y]} -- [np.array with shape (1,2)]
            axes {plt.axes} -- [description]

        """
        print(x2d, type(x2d))
        self.axes.scatter(
            x2d[:, 0],
            x2d[:, 1],
            color="k",
            label="Current Text",
            marker="o",
            s=(15, 15),
        )
        self.axes.legend(fontsize=8)

My problem is that whatever I do, my FigureCanvas will always be filled with black, and won't be changed on any circumstances.

By using the CustomFigureCanvas you can reproduce my problem.


问:
How to automate disparate technology process in Azure
I have a weekly process that I wish to automate in Azure. The overall process consists of about 5 distinct sub-processes. Total execution time is approximately 8  hours. The sub-process technologies include:

A third party data loader program that runs on a Windows VM in Azure. This program is able to send an email upon completion. This process then needs to trigger...

T-SQL scripts running on a Windows VM in Azure which upon completion needs to trigger...

SSIS jobs running on a Windows VM in Azure which upon completion needs to trigger...

A c# application that runs on a Windows VM in Azure which upon completion needs to trigger...

Python code running on a linux VM in Azure.

My question is: what Azure technology or technologies (e.g. automation runbook, logic app) could be used to stitch this thing together to give me back my weekend? Thank you in advance.

答:
To answer your question, yes, sure, there's ways to automate the process using Azure.  I would choose Logic Apps because Business Process Automation is one of it's primary use cases.  But...that's the easy part!

The hard part for you is making these disparate apps accessible to outside services.  Running within Windows VM's, they don't have natural endpoints like native Azure Services.

There's lot's of ways to do this, depending on you ability to modify the VMs and programming skills.

Continued:  Since all the VM are in the same domain and network connected, the first thing would look at is a bit old school (new and shiny isn't always the best), Windows Tasks.  At least for 2-4.

Meaning, a Schedule Task on #2 can check for the email, then run its SQL, then start a Task on #3.

#3 can run it's jobs then start a task on #4 that runs the c# program.  Then #4 can trigger the Python script.  Your big gap then is how to trigger the Python script.  That could be as simple as FTP'ing a trigger file for task on #5 to see.

The Windows scripting can be done in PowerShell.  Not very elegant, but neither is your environment.

Finally, and almost the most important, you can use Azure Monitor and a custom log format to track the process.


问:
Why cant we change the color of badge class in bootstrap 4 using css?
The class for badge in Bootstrap v4.3.1 is

```<code>.badge {
   display: inline-block;
   padding: 0.25em 0.4em;
   font-size: 75%;
   font-weight: 700;
   line-height: 1;
   text-align: center;
   white-space: nowrap;
   vertical-align: baseline;
   border-radius: 0.25rem;
   transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out,
   border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}
</code>```

and to change its color we can add the following class

```<code>.badge-success {
   color: #fff;
   background-color: #28a745;
}
</code>```

Logic would say, if I wanted to make my own color I could make a new class in my css file like such

```<code>.badge-mine {
   color: #212529;
   background-color: #808080;
}
</code>```

and it should work when this works...

```<code><span class="badge badge-success">test</span>
</code>```

then this should work too, but it does not work, even though they appear the same.

```<code><span class="badge badge-mine">test</span>
</code>```

I have checked many answers, but no one seems to answer why we cannot do it like this. Although, I am no expert in CSS I understand that the last command overwrites the previous one i.e. this should overwrite

```<code>color: #212529;
background-color: #808080;
</code>```

this

```<code>color: #fff;
background-color: #28a745;
</code>```

but for some reason it is not happening here.

Can some bootstrap 4 expert shed some light on why the badge-mine does not work even though it looks almost exactly like badge-success?

Thanks

答:
Well it does seem to work as intended:

.badge-mine {
   color: #212529;
   background-color: #808080;
}

.badge-mine-2 {
   color: #ff3300;
   background-color: #0022ff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<span class="badge badge-mine">test</span>
<span class="badge badge-mine-2">test</span></code>```

Body:
The class for badge in Bootstrap v4.3.1 is

.badge {
   display: inline-block;
   padding: 0.25em 0.4em;
   font-size: 75%;
   font-weight: 700;
   line-height: 1;
   text-align: center;
   white-space: nowrap;
   vertical-align: baseline;
   border-radius: 0.25rem;
   transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out,
   border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

and to change its color we can add the following class

.badge-success {
   color: #fff;
   background-color: #28a745;
}

Logic would say, if I wanted to make my own color I could make a new class in my css file like such

.badge-mine {
   color: #212529;
   background-color: #808080;
}

and it should work when this works...

test

then this should work too, but it does not work, even though they appear the same.

test

I have checked many answers, but no one seems to answer why we cannot do it like this. Although, I am no expert in CSS I understand that the last command overwrites the previous one i.e. this should overwrite

color: #212529;
background-color: #808080;

this

color: #fff;
background-color: #28a745;

but for some reason it is not happening here.

Can some bootstrap 4 expert shed some light on why the badge-mine does not work even though it looks almost exactly like badge-success?

Thanks

Body:
Well it does seem to work as intended:

.badge-mine {
   color: #212529;
   background-color: #808080;
}

.badge-mine-2 {
   color: #ff3300;
   background-color: #0022ff;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<span class="badge badge-mine">test</span>
<span class="badge badge-mine-2">test</span>


问:
Overcome git svn caveats
I am reading the CAVEATS of git-svn. via this SO question.

What I understand is that:

If you are mirroring svn trunk, branches etc on git repo, don't merge or rebase anything locally on those branches. Specifically master points to the trunk.

My point is that, this would make git-svn crippled. What's the point of git, if I can't branch from master and then merge that changed branch back into the master? Perhaps I am missing some caveat in the caveat that says it is ok to merge certain branches that have the same parent without any rebases.

Can anyone point to me exactly what needs to be avoided and what is allowed. I'd want the local branches, if necessary, those need to be mirrored and merged and most importantly git should do the merges than the svn.

If I am using git branches to mirror svn branches and I cannot merge git branches, whats really the point of git-svn anyway?

答:
git-svn is crippled by definition. You can't do anything Subversion doesn't grok, like merges.

HOWEVER, you can bend around Subversion's rules temporarily with rebasing. I've shown an example of this in a blog-post/screencast:

http://blog.tfnico.com/2010/10/gitsvn-4-collaborate-with-other-git.html

(Lots of more tips on working with git-svn here.)

ContentLicense: CC BY-SA 3.0

Title: Overcome git svn caveats


问:
Combine import, declare keywords in typescript declaration files
Typescript compiler works not as expected when you combine import with declare statements.

For eg:
we have class.d.ts file with content

```<code>declare class ModuleClass {}
</code>```

and file main.ts

```<code>new ModuleClass()
</code>```

In this scenario typescript transpiles everything without errors.

But if i add import statement in class.d.ts like that:

```<code>import * as react from "react"

declare class ModuleClass {}
</code>```

In this case typescript will failed with next error:

```<code>src/class.ts:1:5 - error TS2304: Cannot find name 'ModuleClass'.

1 new ModuleClass()
      ~~~~~~~~~~~

Found 1 error.
</code>```

What am i doing wrong? May be i've setup tsconfig.json with wrong set of options?

```<code>{
    "compilerOptions": {
        "allowSyntheticDefaultImports": true,
        "jsx": "react",
        "module": "es6",
        "target": "es5",
        "moduleResolution": "node",
        "strict": true,
        "esModuleInterop": true,
        "noEmitHelpers": true,
        "outDir": "js",
        "rootDir": "src",
        "sourceMap": true,
    },
    "include": [
        "./typings/*",
        "./src/**/*"
    ]
}
</code>```

答:
You have to export the class from src/class.ts:

I would set ModuleClass as a const and then export it as such:

```<code>const ModuleClass = { };
export default ModuleClass;
</code>```

Body:
Typescript compiler works not as expected when you combine import with declare statements.

For eg:
we have class.d.ts file with content

declare class ModuleClass {}

and file main.ts

new ModuleClass()

In this scenario typescript transpiles everything without errors.

But if i add import statement in class.d.ts like that:

import * as react from "react"

declare class ModuleClass {}

In this case typescript will failed with next error:

src/class.ts:1:5 - error TS2304: Cannot find name 'ModuleClass'.

1 new ModuleClass()
      ~~~~~~~~~~~

Found 1 error.

What am i doing wrong? May be i've setup tsconfig.json with wrong set of options?

{
    "compilerOptions": {
        "allowSyntheticDefaultImports": true,
        "jsx": "react",
        "module": "es6",
        "target": "es5",
        "moduleResolution": "node",
        "strict": true,
        "esModuleInterop": true,
        "noEmitHelpers": true,
        "outDir": "js",
        "rootDir": "src",
        "sourceMap": true,
    },
    "include": [
        "./typings/*",
        "./src/**/*"
    ]
}

Body:
You have to export the class from src/class.ts:

I would set ModuleClass as a const and then export it as such:

const ModuleClass = { };
export default ModuleClass;


问:
Pricing when updating more than one field of the same document within a Firestore transaction
I have the following transaction using Firestore:

```<code>mDb.runTransaction(new Transaction.Function<Void>() {
    @Override
    public Void apply(final Transaction transaction) throws FirebaseFirestoreException {
        DocumentReference documentReference = mDb.collection("collectionOne").document("documentOne");
        /*
            some code
        */
        transaction.update(documentReference, App.getResourses().getString(R.string.field_one), FieldValue.increment(1));
        transaction.update(documentReference, App.getResourses().getString(R.string.field_two), FieldValue.increment(1));
        return null;
    }
}).addOnSuccessListener(new OnSuccessListener<Void>() {
    @Override
    public void onSuccess(Void aVoid) {
        Log.d("Debugging", "Transaction correctly executed.");
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        Log.w("Debugging", "Transaction failure.", e);
    }
});
</code>```

My question is: when updating, for example, two fields of the same document within the same transaction, will such a transaction yield to one or two documents reads?

答:
when updating, for example, two fields of the same document within the same transaction, will such a transaction yield to one or two documents reads?

Doesn't matter how many fields you change in a document in one operation, you'll always be charged with one write operation. If you make the writes, one after the other, you'll be charged with two write operations.

Body:
I have the following transaction using Firestore:

mDb.runTransaction(new Transaction.Function<Void>() {
    @Override
    public Void apply(final Transaction transaction) throws FirebaseFirestoreException {
        DocumentReference documentReference = mDb.collection("collectionOne").document("documentOne");
        /*
            some code
        */
        transaction.update(documentReference, App.getResourses().getString(R.string.field_one), FieldValue.increment(1));
        transaction.update(documentReference, App.getResourses().getString(R.string.field_two), FieldValue.increment(1));
        return null;
    }
}).addOnSuccessListener(new OnSuccessListener<Void>() {
    @Override
    public void onSuccess(Void aVoid) {
        Log.d("Debugging", "Transaction correctly executed.");
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        Log.w("Debugging", "Transaction failure.", e);
    }
});

My question is: when updating, for example, two fields of the same document within the same transaction, will such a transaction yield to one or two documents reads?


问:
Lambda function not executed in dictionary with "if-else" values
I'm trying to define different lambda functions in a Python dictionary. I know that probably the best thing to do is to have only one lambda function in the "value" part of the dictionary item and manage subcases inside the definded function, but however I don't understand why this code is not working like I want:

```<code>def a():
    print('a')

def b():
    print('b')

def c():
    print('c')

def d():
    print('d')

condition = True

dict = {
        'foo': lambda: a() if condition else lambda: b(),
        'bar': lambda: c() if condition else lambda: d()
    }.get('foo', lambda: print('not found'))()
</code>```

if we set condition = False, the code will not print b, it will not do anything (it seems)..why?
Instead if we try with a dictionary without lambda function definitions, it seems to work as I expect:

```<code>dict2 = {
        'foo': 4 if condition else 5,
        'bar': 6 if condition else 7
    }.get('foo', -1)
</code>```

dict2 will be 5.

Someone can explain to me why the definition returned in the first case is not working?

Thank you in advance!

答:
There is a problem here due to operator precedence. You need to parenthesise the lambdas:

```<code>(lambda: a()) if condition else (lambda: b())
</code>```

What your code does is this:

```<code>lambda: (a() if condition else lambda: b())
</code>```

Which creates a function that either returns a() or returns another function that returns b().

By parenthesising each lambda, you get proper execution: either a function returning a() or one returning b()

If condition is False, your function call actually returns this:

```<code><function <lambda>.<locals>.<lambda> at 0x...>
</code>```

Body:
I'm trying to define different lambda functions in a Python dictionary. I know that probably the best thing to do is to have only one lambda function in the "value" part of the dictionary item and manage subcases inside the definded function, but however I don't understand why this code is not working like I want:

def a():
    print('a')

def b():
    print('b')

def c():
    print('c')

def d():
    print('d')

condition = True

dict = {
        'foo': lambda: a() if condition else lambda: b(),
        'bar': lambda: c() if condition else lambda: d()
    }.get('foo', lambda: print('not found'))()

if we set condition = False, the code will not print b, it will not do anything (it seems)..why?
Instead if we try with a dictionary without lambda function definitions, it seems to work as I expect:

dict2 = {
        'foo': 4 if condition else 5,
        'bar': 6 if condition else 7
    }.get('foo', -1)

dict2 will be 5.

Someone can explain to me why the definition returned in the first case is not working?

Thank you in advance!

Body:
There is a problem here due to operator precedence. You need to parenthesise the lambdas:

(lambda: a()) if condition else (lambda: b())

What your code does is this:

lambda: (a() if condition else lambda: b())

Which creates a function that either returns a() or returns another function that returns b().

By parenthesising each lambda, you get proper execution: either a function returning a() or one returning b()

If condition is False, your function call actually returns this:

<function <lambda>.<locals>.<lambda> at 0x...>


答:
Your lambdas:

lambda: a() if condition else lambda: b()

Are actually:

(lambda: a() if condition else (lambda: b()))

So if condition == False, you return lambda, if True - you use a()

Anyway, lambdas here are unnecessary. You can replace it with:

```<code>dict_ = {
        'foo': a if condition else b,
        'bar': c if condition else d
    }.get('foo', lambda: print('not found'))()
</code>```

Title: Lambda function not executed in dictionary with "if-else" values

Body:
Your lambdas:

lambda: a() if condition else lambda: b()

Are actually:

(lambda: a() if condition else (lambda: b()))

So if condition == False, you return lambda, if True - you use a()

Anyway, lambdas here are unnecessary. You can replace it with:

dict_ = {
        'foo': a if condition else b,
        'bar': c if condition else d
    }.get('foo', lambda: print('not found'))()


问:
Getting "EOFError" in python 3
I am getting EOFError not in my terminal but in Coursera's terminal.
in my system it shows expected output but the coursera is not accepting it

python3

```<code>#Uses python3

import sys

def largest_number(a):
     #write your code here
     l = len(a)
     for i in range(0,l):
          m = max(a)
          print(m,sep="",end ="")
          a.remove(m)

     return 0

if __name__ == '__main__':
    n = int(input())
    for i in range(0,n):
        data = list(map(int,input().split()))
        largest_number(data)
</code>```

Traceback (most recent call last):
  File "largest_number.py", line 20, in <module>
    data = list(map(int,input().split()))
EOFError: EOF when reading a line
```

答:
I will guess: as I know portals with challenges they put all numbers in one line so you can get all values using only one input

```<code>if __name__ == '__main__':
    # get `n` but I will not use it later
    input()

    # get all numbers at once
    data = list(map(int, input().split()))
    largest_number(data)
</code>```

Other languages may need n because they may read numbers one by one and they have to know how many numbers are in line.

Title: Getting "EOFError" in python 3

Body:
I am getting EOFError not in my terminal but in Coursera's terminal.
in my system it shows expected output but the coursera is not accepting it

python3

#Uses python3

import sys

def largest_number(a):
     #write your code here
     l = len(a)
     for i in range(0,l):
          m = max(a)
          print(m,sep="",end ="")
          a.remove(m)

     return 0

if __name__ == '__main__':
    n = int(input())
    for i in range(0,n):
        data = list(map(int,input().split()))
        largest_number(data)

Traceback (most recent call last):
  File "largest_number.py", line 20, in <module>
    data = list(map(int,input().split()))
EOFError: EOF when reading a line

Body:
I will guess: as I know portals with challenges they put all numbers in one line so you can get all values using only one input

if __name__ == '__main__':
    # get `n` but I will not use it later
    input()

    # get all numbers at once
    data = list(map(int, input().split()))
    largest_number(data)

Other languages may need n because they may read numbers one by one and they have to know how many numbers are in line.


问:
If A extends B extends C, why can I cast to A but get a ClassCastException casting to C?
I am trying to read an ASN1 object using Bouncycastle on Android. I expect it to be a DERSequence, which in Bouncycastle is a subclass of ASN1Sequence, which is a subclass of ASN1Object.

```<code>import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;
...

ASN1InputStream ais = ...;
Object o = ais.readObject();
// Eclipse's debugger now says o is a DERSequence, as expected.

DERSequence o2 = (DERSequence)o;
ASN1Sequence o3 = o2;
ASN1Object o4 = o3;
// And o4 is now exactly what I want.

ASN1Object o5 = (ASN1Object)o;
// But this throws:
///    java.lang.ClassCastException: org.bouncycastle.asn1.DERSequence
</code>```

Based on feedback from the answers, I have constructed another, shorter example:

```<code>Object o = new DERSequence();
ASN1Object o1 = new DERSequence(); // This behaves fine.
ASN1Object o2 = (ASN1Object)o; // Throws ClassCastException.
</code>```

What causes this cast to fail?

答:
Android has a modified class hierarchy here, see comment in http://www.netmite.com/android/mydroid/1.5/dalvik/libcore/security/src/main/java/org/bouncycastle/asn1/ASN1Sequence.java  Are you absolutely sure the version you are using that a DERSequence is a subtype of ASN1Object?

e.g it is here http://www.eecs.berkeley.edu/~jonah/bc/org/bouncycastle/asn1/DERSequence.html

but not here http://www.androidjavadoc.com/m3-rc37a/org/bouncycastle/asn1/DERSequence.html

Body:
I am trying to read an ASN1 object using Bouncycastle on Android. I expect it to be a DERSequence, which in Bouncycastle is a subclass of ASN1Sequence, which is a subclass of ASN1Object.

import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;
...

ASN1InputStream ais = ...;
Object o = ais.readObject();
// Eclipse's debugger now says o is a DERSequence, as expected.

DERSequence o2 = (DERSequence)o;
ASN1Sequence o3 = o2;
ASN1Object o4 = o3;
// And o4 is now exactly what I want.

ASN1Object o5 = (ASN1Object)o;
// But this throws:
///    java.lang.ClassCastException: org.bouncycastle.asn1.DERSequence

Based on feedback from the answers, I have constructed another, shorter example:

Object o = new DERSequence();
ASN1Object o1 = new DERSequence(); // This behaves fine.
ASN1Object o2 = (ASN1Object)o; // Throws ClassCastException.

What causes this cast to fail?


问:
Error while sending Image for face matching to AWS Rekognition on Android
I'm getting an error while sending Image for recognition to AWS Rekognition.
This is the code which I use:

```<code>        val byteBuffer = ByteBuffer.allocate(facePicture.byteCount)
        facePicture.copyPixelsToBuffer(byteBuffer)
        val image = Image().withBytes(byteBuffer)

        val searchFacesByImageResult = rekognitionClient.searchFacesByImage(
            SearchFacesByImageRequest()
                .withCollectionId(collectionId)
                .withImage(image)
                .withMaxFaces(1)
                .withFaceMatchThreshold(88F)
        )
</code>```

And this is an error:

```<code>com.amazonaws.AmazonServiceException: 1 validation error detected: Value 'java.nio.HeapByteBuffer[pos=0 lim=0 cap=0]' at 'image.bytes' failed to satisfy constraint: Member must have length greater than or equal to 1 (Service: AmazonRekognition; Status Code: 400; Error Code: ValidationException; Request ID: 70a3f05c-8166-11e9-a1cb-fbae8cf4359b)
        at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:730)
        at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:405)
        at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:212)
        at com.amazonaws.services.rekognition.AmazonRekognitionClient.invoke(AmazonRekognitionClient.java:3006)
        at com.amazonaws.services.rekognition.AmazonRekognitionClient.searchFacesByImage(AmazonRekognitionClient.java:238
</code>```

Exception looks like ByteBuffer is empty, I have debugged and checked that ByteBuffer is valid and is not empty

答:
It appeared the problem was in Image format, I was using RAW BMP format, the format in which Bitmap is represented in memory. But Amazon doesn't support this format, it is stated in the documentation here

Amazon Rekognition supports the PNG and JPEG image formats. That is, the images you provide as input to various API operations, such as DetectLabels and IndexFaces must be in one of the supported formats.

To fix this I have changed my code to this:

```<code>     val stream = ByteArrayOutputStream()
     facePicture.compress(Bitmap.CompressFormat.PNG, 100, stream)
     val byteBuffer = ByteBuffer.wrap(stream.toByteArray())
     val image = Image().withBytes(byteBuffer)

</code>```

Body:
I'm getting an error while sending Image for recognition to AWS Rekognition.
This is the code which I use:

        val byteBuffer = ByteBuffer.allocate(facePicture.byteCount)
        facePicture.copyPixelsToBuffer(byteBuffer)
        val image = Image().withBytes(byteBuffer)

        val searchFacesByImageResult = rekognitionClient.searchFacesByImage(
            SearchFacesByImageRequest()
                .withCollectionId(collectionId)
                .withImage(image)
                .withMaxFaces(1)
                .withFaceMatchThreshold(88F)
        )

And this is an error:

com.amazonaws.AmazonServiceException: 1 validation error detected: Value 'java.nio.HeapByteBuffer[pos=0 lim=0 cap=0]' at 'image.bytes' failed to satisfy constraint: Member must have length greater than or equal to 1 (Service: AmazonRekognition; Status Code: 400; Error Code: ValidationException; Request ID: 70a3f05c-8166-11e9-a1cb-fbae8cf4359b)
        at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:730)
        at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:405)
        at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:212)
        at com.amazonaws.services.rekognition.AmazonRekognitionClient.invoke(AmazonRekognitionClient.java:3006)
        at com.amazonaws.services.rekognition.AmazonRekognitionClient.searchFacesByImage(AmazonRekognitionClient.java:238

Exception looks like ByteBuffer is empty, I have debugged and checked that ByteBuffer is valid and is not empty

Body:
It appeared the problem was in Image format, I was using RAW BMP format, the format in which Bitmap is represented in memory. But Amazon doesn't support this format, it is stated in the documentation here

Amazon Rekognition supports the PNG and JPEG image formats. That is, the images you provide as input to various API operations, such as DetectLabels and IndexFaces must be in one of the supported formats.

To fix this I have changed my code to this:

     val stream = ByteArrayOutputStream()
     facePicture.compress(Bitmap.CompressFormat.PNG, 100, stream)
     val byteBuffer = ByteBuffer.wrap(stream.toByteArray())
     val image = Image().withBytes(byteBuffer)


问:
Input type="submit" fails to pass its value to the server if the value starts with the capital letter
I have two buttons in my HTML: Save & Save and Exit.  On the server I check the value of the button and act accordingly.  However if the value of the button starts with a capital letter on the server it is Null.  The lower case letter goes through fine.

Below is my code

//HTML:

```<code>        <input type="submit" class="btn btn-primary btn-block"  name="submissionbutton" value="Save" />
        <input type="submit" class="btn btn-primary btn-block" name="submissionbutton" value="Save & Exit" />
</code>```

//SERVER:

```<code>        var button = Request.Form["submissionbutton"];
        model.Save(id, db);
        if (button == "Save & Exit")
        {
            return RedirectToAction("Index");
        }
        else
        {
            model = new EditEquipmentViewModel(id, db);
            return View(model);
        }
</code>```

If I change the value in the input from "Save" to "save", all works fine but then it displays lower case "save" on the button itself, which is undesirable.
I don't understand how changing the value from Lower Case to Upper Case in the input type="button" nullifies it on the server.

答:
I am thinking it has something to do with how Json serializes form values:

Try this link below:
JSON properties now lower case on swap from ASP .Net Core 1.0.0-rc2-final to 1.0.0

Replace this line:

```<code>jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
</code>```

With:

```<code>jsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver();
</code>```

Body:
I have two buttons in my HTML: Save & Save and Exit.  On the server I check the value of the button and act accordingly.  However if the value of the button starts with a capital letter on the server it is Null.  The lower case letter goes through fine.

Below is my code

//HTML:

        <input type="submit" class="btn btn-primary btn-block"  name="submissionbutton" value="Save" />
        <input type="submit" class="btn btn-primary btn-block" name="submissionbutton" value="Save & Exit" />

//SERVER:

        var button = Request.Form["submissionbutton"];
        model.Save(id, db);
        if (button == "Save & Exit")
        {
            return RedirectToAction("Index");
        }
        else
        {
            model = new EditEquipmentViewModel(id, db);
            return View(model);
        }

If I change the value in the input from "Save" to "save", all works fine but then it displays lower case "save" on the button itself, which is undesirable.
I don't understand how changing the value from Lower Case to Upper Case in the input type="button" nullifies it on the server.

Body:
I am thinking it has something to do with how Json serializes form values:

Try this link below:
JSON properties now lower case on swap from ASP .Net Core 1.0.0-rc2-final to 1.0.0

Replace this line:

jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

With:

jsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver();


问:
Look for specific number in list and echo that lines containing that number
I have to get a output of a list that only contain ports like :8080, not any other ports so the php has to check if the website contains any lines with :8080 port, and if so you will have to print the whole line. </p>

```<code>$url = "https://proxymagic.cc/Home/FreeProxies?accesskey=key";
$str = file_get_contents($url);
$lines = explode('
', $str);
foreach($lines as $line) {
  if (stripos($line, '8080') !== false) {
    $line = $output;
  }

echo $output;

}
</code>```

答:
I'm not sure why you are storing the line if you just want to echo it back out. This will echo each matching line on a separate line.</p>

```<code>$url = "https://proxymagic.cc/Home/FreeProxies?accesskey=key";
$str = file_get_contents($url);
$lines = explode('
', $str);

foreach($lines as $line) {
  if (stripos($line, '8080') !== false) {
    echo $line . "\n<br/>";
  }
}
</code>```

Body:
I have to get a output of a list that only contain ports like :8080, not any other ports so the php has to check if the website contains any lines with :8080 port, and if so you will have to print the whole line.

$url = "https://proxymagic.cc/Home/FreeProxies?accesskey=key";
$str = file_get_contents($url);
$lines = explode('
', $str);
foreach($lines as $line) {
  if (stripos($line, '8080') !== false) {
    $line = $output;
  }

echo $output;

}

Body:
I'm not sure why you are storing the line if you just want to echo it back out. This will echo each matching line on a separate line.

$url = "https://proxymagic.cc/Home/FreeProxies?accesskey=key";
$str = file_get_contents($url);
$lines = explode('
', $str);

foreach($lines as $line) {
  if (stripos($line, '8080') !== false) {
    echo $line . "\n<br/>";
  }
}


问:
D3.js Can't update existing element in group
I'm trying to build chart using d3.js and es6 classes.
I have array of data data = [{someProp: '', hasWarning: true}, ...].
Some of data elements can have hasWarning property.

If this property exists I draw <path class="notification"></path> element inside parent group.

<g id="g-parent" transform="translate(500, 300)" class="group">
    <circle r="50" cx="10" cy="10" fill="red"></circle>
    <path d="..." transform="translate(30,-40) scale(0.05)"></path>
</g>
```

And when data updates I redraw my notifications. But if some of .notification already exist, my code adds a new item instead of update exisitng.

Here is example

How to avoid adding new element and update existing?

Body:
I'm trying to build chart using d3.js and es6 classes.
I have array of data data = [{someProp: '', hasWarning: true}, ...].
Some of data elements can have hasWarning property.

If this property exists I draw <path class="notification"></path> element inside parent group.

<g id="g-parent" transform="translate(500, 300)" class="group">
    <circle r="50" cx="10" cy="10" fill="red"></circle>
    <path d="..." transform="translate(30,-40) scale(0.05)"></path>
</g>

And when data updates I redraw my notifications. But if some of .notification already exist, my code adds a new item instead of update exisitng.

Here is example

How to avoid adding new element and update existing?

Body:
In your renderNotifications you can remove any existing notifications before appending them.

class ChartRenderer {
  constructor(data) {
    this.data = data;
    this.lineFn = d3.line().curve(d3.curveLinear);
  }

  renderSvg() {
    this.svg = d3.select('body')
      .append('svg')
      .attr('width', 1000)
      .attr('height', 1000)
      .attr('id', 1000);
  }

  renderContainer() {
    this.container = this.svg.append('g')
      .attr('id', 'testUpdate');
  }

  renderGroups() {
    this.groupSelection = this.container.selectAll('.group')
      .data(this.data);

    this.groupEnter = this.groupSelection.enter()
      .append('g')
      .attr('id', (d, i) => `g-${d._id}`)
      .attr('transform', (d, i) => `translate(${d.position.x}, ${d.position.y})`)
      .attr('class', 'group');

    this.groupSelection
      .exit()
      .classed('remove', true)
      .transition()
      .delay(200)
      .remove();
  }

  renderCircles() {
    this.circles = this.groupEnter
      .append('circle')
      .attr('r', 50)
      .attr('cx', 10)
      .attr('cy', 10)
      .attr('fill', 'red');
  }

  renderNotifications() {
    this.groupEnter.select('.notification').remove();
    this.notifications = this.groupEnter.filter(d => d.hasWarnings)
      .append('path')
      .attr('class', 'notification')
      .attr('d', 'M248.747 204.705l6.588 112c.373 6.343 5.626 11.295 11.979 11.295h41.37a12 12 0 0 0 11.979-11.295l6.588-112c.405-6.893-5.075-12.705-11.979-12.705h-54.547c-6.903 0-12.383 5.812-11.978 12.705zM330 384c0 23.196-18.804 42-42 42s-42-18.804-42-42 18.804-42 42-42 42 18.804 42 42zm-.423-360.015c-18.433-31.951-64.687-32.009-83.154 0L6.477 440.013C-11.945 471.946 11.118 512 48.054 512H527.94c36.865 0 60.035-39.993 41.577-71.987L329.577 23.985zM53.191 455.002L282.803 57.008c2.309-4.002 8.085-4.002 10.394 0l229.612 397.993c2.308 4-.579 8.998-5.197 8.998H58.388c-4.617.001-7.504-4.997-5.197-8.997z')
      .attr('transform', 'translate(30,-40) scale(0.05)');

  }
}

class Chart {
  constructor(data = []) {
    // console.log(data);
    this.data = data;
    this.data.forEach(this.multiplyElementCoordinates);

    this.renderer = new ChartRenderer(this.data);
    this.draw();
  }

  draw() {
    this.renderer.renderSvg();
    this.renderer.renderContainer();
    this.renderer.renderGroups();
    this.renderer.renderCircles();
    this.renderer.renderNotifications();
  }

  multiplyElementCoordinates(el) {
    el.position.x *= 100;
    el.position.y *= 100;
  }

  toggleNotifications() {
    this.data.forEach(d => {
      d.hasWarnings = true;
    });

    this.renderer.renderNotifications();
  }
}

const data = [{
    _id: 'first',
    position: {
      x: 5,
      y: 1
    },
    hasWarnings: true
  },
  {
    _id: 'second',
    position: {
      x: 5,
      y: 3
    }
  },
  {
    _id: 'third',
    position: {
      x: 3,
      y: 5
    }
  },
  {
    _id: 'fourth',
    type: 'Condition',
    position: {
      x: 7,
      y: 5
    }
  }
];
const lineChart = new Chart(data);

setTimeout(() => {
  lineChart.toggleNotifications();
}, 5000)

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

Your Forked Fiddle


问:
Cast reflection "Type" to a List<class> in Kotlin
In my Kotlin code, I have a variable that is the Type interface from
java.lang.reflect

```<code>var type: Type
</code>```

But I need to cast this to:

```<code>List<UserInfo>
</code>```

If I was not casting to a List, I would just do this:

```<code>var type = UserInfo::class.java
</code>```

and this works. But I don't know how to cast it using a List. The closest I found is this:

```<code>var type = Array<UserInfo>::class.java
</code>```

This would compile if my UserInfo was an Array but it's a List.

答:
The issue (as @Miha_x64 says) is type erasure.

The Java Virtual Machine knows nothing about type parameters.  So although the source specified a List<UserInfo>, it compiles down to a plain List.

So this works:

```<code>var type = List::class.java
</code>```

(Your Array example works because arrays are a special case: they're directly supported in the JVM, and keep their types at runtime.)

Java's use of type erasure is at least partly for historical reasons; when generics were added to Java 5, they wanted to preserve compatibility with existing source and bytecode.  For all the gory details (much of which is inherited by Kotlin), see here.

Body:
In my Kotlin code, I have a variable that is the Type interface from
java.lang.reflect

var type: Type

But I need to cast this to:

List<UserInfo>

If I was not casting to a List, I would just do this:

var type = UserInfo::class.java

and this works. But I don't know how to cast it using a List. The closest I found is this:

var type = Array<UserInfo>::class.java

This would compile if my UserInfo was an Array but it's a List.

Body:
The issue (as @Miha_x64 says) is type erasure.

The Java Virtual Machine knows nothing about type parameters.  So although the source specified a List<UserInfo>, it compiles down to a plain List.

So this works:

var type = List::class.java

(Your Array example works because arrays are a special case: they're directly supported in the JVM, and keep their types at runtime.)

Java's use of type erasure is at least partly for historical reasons; when generics were added to Java 5, they wanted to preserve compatibility with existing source and bytecode.  For all the gory details (much of which is inherited by Kotlin), see here.


问:
C++ Shell multiple pipelines are not working?
I have worked on pipelines in C++ and I managed to get a single pipeline working. I am struggling a bit to get multiple pipelines working. I have no idea where it is actually going wrong.

An example that I have used to test single pipelines:

```<code>ls -l | grep test
</code>```

An example that I have used to test multiple pipelines:

```<code>ls -l | grep test | grep test2
</code>```

The first command works fine for me.
However, the second command does literally nothing for me.

EDIT 1-6-2019: I am going to try to work with this pseudocode

```<code>left_pipe = NULL
right_pipe = NULL

for each command:

    if not last:
        right_pipe = pipe()

    fork():
        child:
            if left_pipe is not NULL:
                STDIN = left_pipe.read
            if right_pipe is not NULL:
                STDOUT = right_pipe.write
            left_pipe.close_W()
            right_pipe.close_R()
            execute()
            left_pipe.close_RW()
            //Move right pipe to the left side for the next command
            left_pipe = right_pipe
end
</code>```

I would appreciate any insight/help.

Thanks in forward.

答:
As @AndyG said, please refactor the code, it's messy, redundant and error-prone. Here are those errors:

You are not closing the pipes. READPIPE,
WRITEPIPE file descriptors are still open, which keeps the reader
running. EOF is read only if all write ends are closed.

Opening pipes in the child does not make sense, there's no way to pass them onto the next one.

During execution of a middle command, there are two actives pipes - reading end of the left pipe as input. Writing end of the right pipe as output.

In pseudo-code you want to be doing something like this:

```<code>left_pipe = NULL
right_pipe = NULL

for each command:

    if not last:
        right_pipe = pipe()

    fork():
        child:
            if left_pipe is not NULL:
                STDIN = left_pipe.read
            if right_pipe is not NULL:
                STDOUT = right_pipe.write
            left_pipe.close_W()
            right_pipe.close_R()
            execute()
            left_pipe.close_RW()
            //Move right pipe to the left side for the next command
            left_pipe = right_pipe
end
</code>```

Plus some error checking, close_ should ignore already closed/non-existing pipes. Closing in the child is important otherwise the child would keep itself alive because it would block on left_pipe.read which would be waiting the left_pipe.write ( held by the same child) end to write something.

I hope that you agree this is also more readable.

Body:
I have worked on pipelines in C++ and I managed to get a single pipeline working. I am struggling a bit to get multiple pipelines working. I have no idea where it is actually going wrong.

An example that I have used to test single pipelines:

ls -l | grep test

An example that I have used to test multiple pipelines:

ls -l | grep test | grep test2

The first command works fine for me.
However, the second command does literally nothing for me.

EDIT 1-6-2019: I am going to try to work with this pseudocode

left_pipe = NULL
right_pipe = NULL

for each command:

    if not last:
        right_pipe = pipe()

    fork():
        child:
            if left_pipe is not NULL:
                STDIN = left_pipe.read
            if right_pipe is not NULL:
                STDOUT = right_pipe.write
            left_pipe.close_W()
            right_pipe.close_R()
            execute()
            left_pipe.close_RW()
            //Move right pipe to the left side for the next command
            left_pipe = right_pipe
end

I would appreciate any insight/help.

Thanks in forward.

Body:
As @AndyG said, please refactor the code, it's messy, redundant and error-prone. Here are those errors:

You are not closing the pipes. READPIPE,
WRITEPIPE file descriptors are still open, which keeps the reader
running. EOF is read only if all write ends are closed.

Opening pipes in the child does not make sense, there's no way to pass them onto the next one.

During execution of a middle command, there are two actives pipes - reading end of the left pipe as input. Writing end of the right pipe as output.

In pseudo-code you want to be doing something like this:

left_pipe = NULL
right_pipe = NULL

for each command:

    if not last:
        right_pipe = pipe()

    fork():
        child:
            if left_pipe is not NULL:
                STDIN = left_pipe.read
            if right_pipe is not NULL:
                STDOUT = right_pipe.write
            left_pipe.close_W()
            right_pipe.close_R()
            execute()
            left_pipe.close_RW()
            //Move right pipe to the left side for the next command
            left_pipe = right_pipe
end

Plus some error checking, close_ should ignore already closed/non-existing pipes. Closing in the child is important otherwise the child would keep itself alive because it would block on left_pipe.read which would be waiting the left_pipe.write ( held by the same child) end to write something.

I hope that you agree this is also more readable.


问:
center on resize too
This works:

```<code>$.fn.center = function () {
    this.css("position", "absolute");
    this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
    this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
    return this
};
$('#container').center();
</code>```

.. but the element stays in the same position if the window is resized, how do I center it with the resize too?

Thanks

答:
EDIT::

giving percentage to top and left can put at center. but this bad ... really really bad.

```<code>    $.fn.center = function () {
        $(this).css({'position': 'absolute',
                     'top': '40%',
                     'left': '40%'
                    });
    };

    $(function (){
        $('#container').center();
    })
</code>```

On jsfiddle.

Title: center on resize too

Body:
This works:

$.fn.center = function () {
    this.css("position", "absolute");
    this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
    this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
    return this
};
$('#container').center();

.. but the element stays in the same position if the window is resized, how do I center it with the resize too?

Thanks

Body:
EDIT::

giving percentage to top and left can put at center. but this bad ... really really bad.

    $.fn.center = function () {
        $(this).css({'position': 'absolute',
                     'top': '40%',
                     'left': '40%'
                    });
    };

    $(function (){
        $('#container').center();
    })

On jsfiddle.