问:
How to get time difference Duration totals grouped by Name and when Value changes in certain way?
I'm looking for the Sum of time value differences between rows where Value was initially 1 and is now 0, grouped by Name.

Example data for a single Name, but there are many different Names in the real data.

```<code>+--------+---------------+---------------------+--------+
| RowNum |     Name      |      Timestamp      | Value  |
+--------+---------------+---------------------+--------+
|      1 | D1_HS_308_ALM | 2020-02-10 11:55:00 | 0      |
|      2 | D1_HS_308_ALM | 2020-02-10 11:51:00 | 0      |
|      3 | D1_HS_308_ALM | 2020-02-10 11:49:00 | NULL   |
|      4 | D1_HS_308_ALM | 2020-02-10 11:46:00 | 1      |
|      5 | D1_HS_308_ALM | 2020-02-10 08:02:00 | 0      |
|      6 | D1_HS_308_ALM | 2020-02-10 08:02:00 | NULL   |
|      7 | D1_HS_308_ALM | 2020-02-10 08:02:00 | 0      |
|      8 | D1_HS_308_ALM | 2020-02-10 07:56:00 | 1      |
|      9 | D1_HS_308_ALM | 2020-02-10 07:51:00 | 1      |
|     10 | D1_HS_308_ALM | 2020-02-10 07:50:00 | 0      |
+--------+---------------+---------------------+--------+
</code>```

This data should return 11 minutes for Row 9-->7 transition and 5 minutes for Row 4-->2 transition; totaling 16 minutes for this Name.

I'm not sure how to accomplish this when it's not guaranteed that the next row has the correct Value change - sometimes it will be several or many rows later.

答:
```<code>DECLARE @myTable TABLE
(
    RowNum INT,
    Name VARCHAR(20),
    [Timestamp] DATETIME,
    Value INT
);

INSERT INTO @myTable
(
    RowNum,
    Name,
    [Timestamp],
    Value
)
VALUES
(1, 'D1_HS_308_ALM', '2020-02-10 11:55:00', 0),
(2, 'D1_HS_308_ALM', '2020-02-10 11:51:00', 0),
(3, 'D1_HS_308_ALM', '2020-02-10 11:49:00', NULL),
(4, 'D1_HS_308_ALM', '2020-02-10 11:46:00', 1),
(5, 'D1_HS_308_ALM', '2020-02-10 08:02:00', 0),
(6, 'D1_HS_308_ALM', '2020-02-10 08:02:00', NULL),
(7, 'D1_HS_308_ALM', '2020-02-10 08:02:00', 0),
(8, 'D1_HS_308_ALM', '2020-02-10 07:56:00', 1),
(9, 'D1_HS_308_ALM', '2020-02-10 07:51:00', 1),
(10, 'D1_HS_308_ALM', '2020-02-10 07:50:00', 0);

SELECT *,
       DATEDIFF(MINUTE, tStart, tEnd) AS duration
FROM
(
    SELECT t1.Name,
           MIN(t1.RowNum) AS rStart,
           MIN(t1.Timestamp) AS tStart,
           t.rNo AS rEnd,
           t.tEnd
    FROM @myTable t1
        OUTER APPLY
    (
        SELECT TOP (1)
               t2.RowNum,
               t2.Timestamp
        FROM @myTable t2
        WHERE t1.Name = t2.Name
              AND t2.Timestamp > t1.Timestamp
              AND t2.Value = 0
        ORDER BY t2.Timestamp
    ) t(rNo, tEnd)
    WHERE t1.Value = 1
    GROUP BY t1.Name,
             t.rNo,
             t.tEnd
) tmp;
</code>```

<p>Update: </p>

```<code>SELECT Name,
       Sum(DATEDIFF(MINUTE, tStart, tEnd)) AS duration
FROM
(
    SELECT t1.Name,
           MIN(t1.Timestamp) AS tStart,
           t.tEnd
    FROM @myTable t1
        OUTER APPLY
    (
        SELECT TOP (1)
               t2.Timestamp
        FROM @myTable t2
        WHERE t1.Name = t2.Name
              AND t2.Timestamp > t1.Timestamp
              AND t2.Value = 0
        ORDER BY t2.Timestamp
    ) t(tEnd)
    WHERE t1.Value = 1
    GROUP BY t1.Name,
             t.tEnd
) tmp
group by name;
</code>```

Body:
I'm looking for the Sum of time value differences between rows where Value was initially 1 and is now 0, grouped by Name.

Example data for a single Name, but there are many different Names in the real data.

+--------+---------------+---------------------+--------+
| RowNum |     Name      |      Timestamp      | Value  |
+--------+---------------+---------------------+--------+
|      1 | D1_HS_308_ALM | 2020-02-10 11:55:00 | 0      |
|      2 | D1_HS_308_ALM | 2020-02-10 11:51:00 | 0      |
|      3 | D1_HS_308_ALM | 2020-02-10 11:49:00 | NULL   |
|      4 | D1_HS_308_ALM | 2020-02-10 11:46:00 | 1      |
|      5 | D1_HS_308_ALM | 2020-02-10 08:02:00 | 0      |
|      6 | D1_HS_308_ALM | 2020-02-10 08:02:00 | NULL   |
|      7 | D1_HS_308_ALM | 2020-02-10 08:02:00 | 0      |
|      8 | D1_HS_308_ALM | 2020-02-10 07:56:00 | 1      |
|      9 | D1_HS_308_ALM | 2020-02-10 07:51:00 | 1      |
|     10 | D1_HS_308_ALM | 2020-02-10 07:50:00 | 0      |
+--------+---------------+---------------------+--------+

This data should return 11 minutes for Row 9-->7 transition and 5 minutes for Row 4-->2 transition; totaling 16 minutes for this Name.

I'm not sure how to accomplish this when it's not guaranteed that the next row has the correct Value change - sometimes it will be several or many rows later.

Body:
DECLARE @myTable TABLE
(
    RowNum INT,
    Name VARCHAR(20),
    [Timestamp] DATETIME,
    Value INT
);

INSERT INTO @myTable
(
    RowNum,
    Name,
    [Timestamp],
    Value
)
VALUES
(1, 'D1_HS_308_ALM', '2020-02-10 11:55:00', 0),
(2, 'D1_HS_308_ALM', '2020-02-10 11:51:00', 0),
(3, 'D1_HS_308_ALM', '2020-02-10 11:49:00', NULL),
(4, 'D1_HS_308_ALM', '2020-02-10 11:46:00', 1),
(5, 'D1_HS_308_ALM', '2020-02-10 08:02:00', 0),
(6, 'D1_HS_308_ALM', '2020-02-10 08:02:00', NULL),
(7, 'D1_HS_308_ALM', '2020-02-10 08:02:00', 0),
(8, 'D1_HS_308_ALM', '2020-02-10 07:56:00', 1),
(9, 'D1_HS_308_ALM', '2020-02-10 07:51:00', 1),
(10, 'D1_HS_308_ALM', '2020-02-10 07:50:00', 0);

SELECT *,
       DATEDIFF(MINUTE, tStart, tEnd) AS duration
FROM
(
    SELECT t1.Name,
           MIN(t1.RowNum) AS rStart,
           MIN(t1.Timestamp) AS tStart,
           t.rNo AS rEnd,
           t.tEnd
    FROM @myTable t1
        OUTER APPLY
    (
        SELECT TOP (1)
               t2.RowNum,
               t2.Timestamp
        FROM @myTable t2
        WHERE t1.Name = t2.Name
              AND t2.Timestamp > t1.Timestamp
              AND t2.Value = 0
        ORDER BY t2.Timestamp
    ) t(rNo, tEnd)
    WHERE t1.Value = 1
    GROUP BY t1.Name,
             t.rNo,
             t.tEnd
) tmp;

Update:

SELECT Name,
       Sum(DATEDIFF(MINUTE, tStart, tEnd)) AS duration
FROM
(
    SELECT t1.Name,
           MIN(t1.Timestamp) AS tStart,
           t.tEnd
    FROM @myTable t1
        OUTER APPLY
    (
        SELECT TOP (1)
               t2.Timestamp
        FROM @myTable t2
        WHERE t1.Name = t2.Name
              AND t2.Timestamp > t1.Timestamp
              AND t2.Value = 0
        ORDER BY t2.Timestamp
    ) t(tEnd)
    WHERE t1.Value = 1
    GROUP BY t1.Name,
             t.tEnd
) tmp
group by name;


来源: stackexchange

问:
Problem access to GPIO rasbery pi 3 with android things
I want to turn on A LED with android things and raspberry Pi 3. I did it as instructed in https://developer.android.com/things/sdk/pio/gpio. And I am using last android things version (1.0.15).
any comments why I get a such error?

2009-01-01 03:30:07.762 667-667/com.inflashpay.inflash
  E/Request Permission: List of available ports: [BCM2] 2009-01-01
  03:30:07.774 667-667/com.inflashpay.inflash E/Request Permission:
  Unable to access GPIO
      com.google.android.things.pio.PioException: android.os.ServiceSpecificException: BCM2 failed to apply the required
  pin mux: No such file or directory (code 2)

added:

```<code>private static final String LED = "BCM2";
private Handler mHandler = new Handler();
private Gpio mLedGpio;
    PeripheralManager service = PeripheralManager.getInstance();
    Log.i(TAG, "Available GPIO: " + service.getGpioList());
    try {

        mLedGpio = service.openGpio(LED);
        mLedGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
        Log.i(TAG, "Start blinking LED GPIO pin");
        // Post a Runnable that continuously switch the state of the GPIO, blinking the
        // corresponding LED
        mHandler.post(mBlinkRunnable);
    } catch (IOException e) {
        Log.e(TAG, "Error on PeripheralIO API", e);
    }
</code>```

答:
The code sounds good, but the problem is probably the GPIO name.

Check out the pinout diagram of the Raspberry Pi

You can see that BCM2 is not available (although BCM21 is)

You can see another example that uses the pins on the Rainbow HAT on this sample. That one I have run and verified that works. Feel free to compare the project with yours or clone the repo and try that code.

ContentLicense: CC BY-SA 4.0

Body:
I want to turn on A LED with android things and raspberry Pi 3. I did it as instructed in https://developer.android.com/things/sdk/pio/gpio. And I am using last android things version (1.0.15).
any comments why I get a such error?

2009-01-01 03:30:07.762 667-667/com.inflashpay.inflash
  E/Request Permission: List of available ports: [BCM2] 2009-01-01
  03:30:07.774 667-667/com.inflashpay.inflash E/Request Permission:
  Unable to access GPIO
      com.google.android.things.pio.PioException: android.os.ServiceSpecificException: BCM2 failed to apply the required
  pin mux: No such file or directory (code 2)

added:

private static final String LED = "BCM2";
private Handler mHandler = new Handler();
private Gpio mLedGpio;
    PeripheralManager service = PeripheralManager.getInstance();
    Log.i(TAG, "Available GPIO: " + service.getGpioList());
    try {

        mLedGpio = service.openGpio(LED);
        mLedGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
        Log.i(TAG, "Start blinking LED GPIO pin");
        // Post a Runnable that continuously switch the state of the GPIO, blinking the
        // corresponding LED
        mHandler.post(mBlinkRunnable);
    } catch (IOException e) {
        Log.e(TAG, "Error on PeripheralIO API", e);
    }


问:
is it possible to reduce delete code size with templates in C++
I have a lot of items, I am deleting. For each item, I am calling the following lines of related codes:

```<code>if (item) {
   delete item;
   item=nullptr;
}
</code>```

so, instead, I am considering of using templates by defining a single function:

```<code>template <typename T>
void delete_it(T &item) {
    if (item) {
       delete item;
       item=nullptr;
    }
}
</code>```

from this on, the following lines work fine:

```<code>delete_it(an_item);
delete_it(another_item);
</code>```

I have checked it by allocating a character array dynamically and it seemed to work fine.
However, I haven't seen it used in anywhere. Is it an appropriate way of deleting?Is there a library(std for example) function doing just that? Thank you,

答:
Replace

```<code>Type *item;
...
if (item) {
   delete item;
   item=nullptr;
}
</code>```

With:

```<code>std::unique_ptr<Type> item;
...
item.reset();
</code>```

For arrays:

```<code>std::vector<Type> items;
...
items.clear();
</code>```

Body:
I have a lot of items, I am deleting. For each item, I am calling the following lines of related codes:

if (item) {
   delete item;
   item=nullptr;
}

so, instead, I am considering of using templates by defining a single function:

template <typename T>
void delete_it(T &item) {
    if (item) {
       delete item;
       item=nullptr;
    }
}

from this on, the following lines work fine:

delete_it(an_item);
delete_it(another_item);

I have checked it by allocating a character array dynamically and it seemed to work fine.
However, I haven't seen it used in anywhere. Is it an appropriate way of deleting?Is there a library(std for example) function doing just that? Thank you,

Body:
Replace

Type *item;
...
if (item) {
   delete item;
   item=nullptr;
}

With:

std::unique_ptr<Type> item;
...
item.reset();

For arrays:

std::vector<Type> items;
...
items.clear();


问:
Find all lines where a value exists in one line
Here is my query

```<code>        select order_no, pkg_no, zone_no
        from T_DETAIL_ITEM a
        where order_no = 495
        order by order_no, pkg_no
</code>```

For a given package I have zone number = 0

What I need to do is return all the lines with the pkg_no = 1597. Because one where exists with a zero zone.

I tried a few different 'where exists' lines and it isn't working.

答:
If I correctly understood the question, you need something like this
BEGIN</p>

```<code>declare @str varchar(max);

set @str='';

SELECT  @str=@str+ [YOURCOLUMB]

  FROM [YOURTABLE]

SELECT @str

END
</code>```

Body:
Here is my query

        select order_no, pkg_no, zone_no
        from T_DETAIL_ITEM a
        where order_no = 495
        order by order_no, pkg_no

For a given package I have zone number = 0

What I need to do is return all the lines with the pkg_no = 1597. Because one where exists with a zero zone.

I tried a few different 'where exists' lines and it isn't working.

Body:
If I correctly understood the question, you need something like this
BEGIN

declare @str varchar(max);

set @str='';

SELECT  @str=@str+ [YOURCOLUMB]

  FROM [YOURTABLE]

SELECT @str

END


问:
Java: NullPointerException from class.getResource( ... )
I was writing a small application and when I tried to create an ImageIcon I always got an exception. The exception was caused by this line of code:

```<code>prayerLevel.setIcon(new ImageIcon(getClass().getResource("/icons/icon_prayer.png")));
</code>```

Now within my program, the folder /icons/ does exist. I don't know if it makes the difference but the class file is within a package, where as the icons folder is within the project folder (when you would see the bin and src folder).

I have looked around for a bit and I couldn't find a solution that could help me solve the problem. Perhaps any of you guys could help?

Edit: someone asked for my folder hierarchy:

I know the class file is not in the same folder as the icons are, but I've made applications where I had to load files from a different folder and doing /folder/ always used to work.

Edit 2:

```<code>System.out.println(getClass().getResource("/icons/icon_prayer.png") == null);
</code>```

Prints true.

答: The only thing that can throw a NullPointerException in this line of code is the first ., which means that prayerLevel is null.

ContentLicense: CC BY-SA 3.0

Body:
I was writing a small application and when I tried to create an ImageIcon I always got an exception. The exception was caused by this line of code:

prayerLevel.setIcon(new ImageIcon(getClass().getResource("/icons/icon_prayer.png")));

Now within my program, the folder /icons/ does exist. I don't know if it makes the difference but the class file is within a package, where as the icons folder is within the project folder (when you would see the bin and src folder).

I have looked around for a bit and I couldn't find a solution that could help me solve the problem. Perhaps any of you guys could help?

Edit: someone asked for my folder hierarchy:

I know the class file is not in the same folder as the icons are, but I've made applications where I had to load files from a different folder and doing /folder/ always used to work.

Edit 2:

System.out.println(getClass().getResource("/icons/icon_prayer.png") == null);

Prints true.


问:
An argument that can be supplied in both positional and keyword ways?
In Python, a positional argument can always be supplied as a keyword argument (we're not digging into Python-C extensions where this may be false):

def foo(bar=None):
    print(bar)

foo("aaa")
foo(bar="aaa")
```

I want to achieve the same effect as bar in Ruby. However neither bar = nil nor bar: nil work:

def foo bar = nil is positional-only, and arguments passed as foo(key: value) will be collected into a Hash and provided as the next positional argument, while foo(bar = value) instead assigns to a local variable bar and passes it positionally (instead of matching the argument name).

def foo bar: nil is keyword-only. There's no way to supply bar except in the form f(bar: value)

I'm afraid it's not possible in Ruby to have an argument that can be passed both positionally and keyword-ly. Is it?

I only need to work with Ruby 2.5 and later.

答:
The closest you are going to get in Ruby is:

```<code>def foo(bar=nil, **kwargs)
  bar = bar || kwargs[:bar]
end
</code>```

Which is not great since the method now takes any keyword argument.

Ruby does not allow you to duplicate a argument name:

```<code>irb(main):022:0> def foo(bar = nil, bar: nil)
irb(main):023:1> end
Traceback (most recent call last):
SyntaxError ((irb):22: duplicated argument name)
def foo(bar = nil, bar: nil)
</code>```

And while this might be a nice feature in Python - its not Ruby-eske. In Ruby passing a hash to a method follows the same syntax as defining a hash - because that's exactly what you are doing.

Body:
In Python, a positional argument can always be supplied as a keyword argument (we're not digging into Python-C extensions where this may be false):

def foo(bar=None):
    print(bar)

foo("aaa")
foo(bar="aaa")

I want to achieve the same effect as bar in Ruby. However neither bar = nil nor bar: nil work:

def foo bar = nil is positional-only, and arguments passed as foo(key: value) will be collected into a Hash and provided as the next positional argument, while foo(bar = value) instead assigns to a local variable bar and passes it positionally (instead of matching the argument name).

def foo bar: nil is keyword-only. There's no way to supply bar except in the form f(bar: value)

I'm afraid it's not possible in Ruby to have an argument that can be passed both positionally and keyword-ly. Is it?

I only need to work with Ruby 2.5 and later.

Body:
The closest you are going to get in Ruby is:

def foo(bar=nil, **kwargs)
  bar = bar || kwargs[:bar]
end

Which is not great since the method now takes any keyword argument.

Ruby does not allow you to duplicate a argument name:

irb(main):022:0> def foo(bar = nil, bar: nil)
irb(main):023:1> end
Traceback (most recent call last):
SyntaxError ((irb):22: duplicated argument name)
def foo(bar = nil, bar: nil)

And while this might be a nice feature in Python - its not Ruby-eske. In Ruby passing a hash to a method follows the same syntax as defining a hash - because that's exactly what you are doing.


问:
Is it possible to have an objectType within the same object
I've been trying to get it so I can put multiple "trainings" within the training type if since they would merge into each other once the user has both. However I can't seem to get it working and I'm stumped as to how to go about it.

Here is my trainingmodel:

const mongoose = require('mongoose')
const Schema = mongoose.Schema

let trainingSchema = new Schema({
  name: {
    type: String,
    required: true,
    unique: true
  },
  shortHand: {
    type: String,
    required: true,
    unqiue: true
  },
  desc: { type: String },
  office: {
    type: Schema.Types.ObjectId,
    ref: "Office"
  },
  isMerge: { type: Boolean, default: false},
  mergeInto: [{
    type: Schema.Types.ObjectId,
    ref: "Training"
  }]
})

module.exports = mongoose.model('Training', trainingSchema)
```

<p>and here is my training object</p>

<pre class="lang-js prettyprint-override"><code>/**
 * Defines Training Type
 */
const TrainingType = new GraphQLObjectType({
  name: "Training",
  fields: {
    id: { type: GraphQLID },
    name: { type: GraphQLString },
    shortHand: { type: GraphQLString },
    desc: { type: GraphQLString },
    office: {
      type: require('./office').OfficeType,
      resolve: async (office) => {
        return await Office.findById(office.office)
      }
    },
    isMerge: { type: GraphQLBoolean },
    mergeInto: {
      type: new GraphQLList(TrainingType), // This is the error line
      resolve: async (training) => {
        return await Training.find({id: training.id})
      }
    }
  }
})
module.exports.TrainingType = TrainingType
</code>```

Now obviously the error I get back is TrainingType is not defined, since I'm trying use something that hasn't fully been defined yet. But I've tried other ways like making a different objectType called MergesInto and then use it in the other. But that doesn't work either as one requires the other and one has to be defined before the other which will give me the error Is Not Defined. I can't seem to figure out how to get it working. Is this even possible?

答:
fields can be either an object or a function that returns one. Making it a function will delay the execution of the code inside the function, so you can reference the TrainingType variable without an error.

```<code>const TrainingType = new GraphQLObjectType({
  name: "Training",
  fields: () => ({
    ...
    mergeInto: {
      type: new GraphQLList(TrainingType),
      ...
    },
  })
})
</code>```

Body:
I've been trying to get it so I can put multiple "trainings" within the training type if since they would merge into each other once the user has both. However I can't seem to get it working and I'm stumped as to how to go about it.

Here is my trainingmodel:

const mongoose = require('mongoose')
const Schema = mongoose.Schema

let trainingSchema = new Schema({
  name: {
    type: String,
    required: true,
    unique: true
  },
  shortHand: {
    type: String,
    required: true,
    unqiue: true
  },
  desc: { type: String },
  office: {
    type: Schema.Types.ObjectId,
    ref: "Office"
  },
  isMerge: { type: Boolean, default: false},
  mergeInto: [{
    type: Schema.Types.ObjectId,
    ref: "Training"
  }]
})

module.exports = mongoose.model('Training', trainingSchema)

and here is my training object

/**
 * Defines Training Type
 */
const TrainingType = new GraphQLObjectType({
  name: "Training",
  fields: {
    id: { type: GraphQLID },
    name: { type: GraphQLString },
    shortHand: { type: GraphQLString },
    desc: { type: GraphQLString },
    office: {
      type: require('./office').OfficeType,
      resolve: async (office) => {
        return await Office.findById(office.office)
      }
    },
    isMerge: { type: GraphQLBoolean },
    mergeInto: {
      type: new GraphQLList(TrainingType), // This is the error line
      resolve: async (training) => {
        return await Training.find({id: training.id})
      }
    }
  }
})
module.exports.TrainingType = TrainingType

Now obviously the error I get back is TrainingType is not defined, since I'm trying use something that hasn't fully been defined yet. But I've tried other ways like making a different objectType called MergesInto and then use it in the other. But that doesn't work either as one requires the other and one has to be defined before the other which will give me the error Is Not Defined. I can't seem to figure out how to get it working. Is this even possible?

Body:
fields can be either an object or a function that returns one. Making it a function will delay the execution of the code inside the function, so you can reference the TrainingType variable without an error.

const TrainingType = new GraphQLObjectType({
  name: "Training",
  fields: () => ({
    ...
    mergeInto: {
      type: new GraphQLList(TrainingType),
      ...
    },
  })
})


问:
How to compute a value from two MySQL database columns for use in WHERE clause
I have a query that starts like...

```<code>SELECT session_id, time, quantity, teacher, sum(time+(quantity*60*60*60)) AS end FROM my_table WHERE end > 1582214400
</code>```

I am getting a PDO exception...

```<code>column not found: 1054 Unknown column 'end' in 'where clause'
</code>```

Why is PDO/MySQL giving me this error?  What is the correct syntax to compute end so I can use it in the WHERE clause?

答:
You can't use an alias from select in where clause. Use having instead as follows:

```<code>SELECT session_id, time, quantity, teacher, sum(time+(quantity*60*60*60)) AS end FROM my_table having end > 1582214400
</code>```

Body:
I have a query that starts like...

SELECT session_id, time, quantity, teacher, sum(time+(quantity*60*60*60)) AS end FROM my_table WHERE end > 1582214400

I am getting a PDO exception...

column not found: 1054 Unknown column 'end' in 'where clause'

Why is PDO/MySQL giving me this error?  What is the correct syntax to compute end so I can use it in the WHERE clause?

Body:
You can't use an alias from select in where clause. Use having instead as follows:

SELECT session_id, time, quantity, teacher, sum(time+(quantity*60*60*60)) AS end FROM my_table having end > 1582214400


问:
Python function that takes lists and elements and makes one list
Hopefully an example could illustrate this better. I am creating a function that will take either a list of names, various lists of names, just a name or multiple names (not in a list) and make one list of them all (without importing... non-native libraries? I am ignorant here but I mean I want to use only what's already available in python).

```<code>def make_one_list(entry1, entry2, entry3 ...):
   #regardless of what is entered (well.. it has to be list or element)
   #extract elements from list and combine with single elements and...
   return one_big_list_of_all_elements

>>>make_one_list(['John','Mark'],'Mike',['Kate','Ally'],'Shawn','Marina'...)
['John','Mark','Mike','Kate','Ally','Shawn','Marina',...]
</code>```

My pseudo-code is not set in stone, obviously. I think, eventually, some input checking might be in order but not very pythonic in nature to do that. I am simply doing this as a personal communication function for my office.

THANKS!!

答:
Like the chain answer but a bit more straightforward at a glance

```<code>def make_one_list(*args):
    one_list = []
    for arg in args:
        if isinstance(arg, str):
            one_list.append(arg)
        else:
            one_list.extend(arg)
    return one_list

ret = make_one_list(['John','Mark'],'Mike',['Kate','Ally'],'Shawn','Marina')
print(ret)
</code>```

Body:
Hopefully an example could illustrate this better. I am creating a function that will take either a list of names, various lists of names, just a name or multiple names (not in a list) and make one list of them all (without importing... non-native libraries? I am ignorant here but I mean I want to use only what's already available in python).

def make_one_list(entry1, entry2, entry3 ...):
   #regardless of what is entered (well.. it has to be list or element)
   #extract elements from list and combine with single elements and...
   return one_big_list_of_all_elements

>>>make_one_list(['John','Mark'],'Mike',['Kate','Ally'],'Shawn','Marina'...)
['John','Mark','Mike','Kate','Ally','Shawn','Marina',...]

My pseudo-code is not set in stone, obviously. I think, eventually, some input checking might be in order but not very pythonic in nature to do that. I am simply doing this as a personal communication function for my office.

THANKS!!

Body:
Like the chain answer but a bit more straightforward at a glance

def make_one_list(*args):
    one_list = []
    for arg in args:
        if isinstance(arg, str):
            one_list.append(arg)
        else:
            one_list.extend(arg)
    return one_list

ret = make_one_list(['John','Mark'],'Mike',['Kate','Ally'],'Shawn','Marina')
print(ret)


问:
How to loop a question until getting the answer from scanner?
I am trying to loop asking coordinates and getting input from the scanner. I want to ask for input until the coordinates are valid. However I am really new with java and the loops confused me for this task.
First I should print a console output asking the player to input a pair of board coordinates.

If the inputs are valid coordinates I will return the coordinates as a string array.

If the inputs are not valid coordinates I should print an error message and then ask again until I get valid coordinates.

public static String[] positionQuery(int dim, Scanner test_in) {
    Scanner stdin = new Scanner(System.in);
    System.out.println("Provide origin and destination coordinates.");
    System.out.println("Enter two positions between A1-H8:");
    String s1 = stdin.nextLine();
    String[] coordinates = s1.split(" ");
    String origin = coordinates[0];
    String dest = coordinates[1];

    while (!validCoordinate(origin, dim) && !validCoordinate(dest,dim)) {
        System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
        String s2 = stdin.nextLine();
        String[] coordinates2 = s2.split(" ");
        String origin2 = coordinates[0];
        String dest2 = coordinates[1];
    }
    return new String[0];
}
```

I created a helper function validCoordinate(String, int) that checks the validity.
How can I fix my code?

答:
This is how it can be. With while(true), you get an input. If the coordinates are valid, it will return them. Just implement the validation method the way you want and you're good to go.

```<code>public static String[] positionQuery(int dim) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Provide origin and destination coordinates.");
    System.out.println("Enter two positions between A1-H8:");
    while(true) {
        String line = scanner.nextLine();
        String[] coordinates = line.split(" ");
        if(coordinates.length == 2) { // valid input with just one space
            String src = coordinates[0];
            String dst = coordinates[1];
            if(validCoordinate(src, dst, dim)) {
                return coordinates;
            }
        }
        System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
    }
}

/**
 * checks the validity of source and destination
 * @param src source
 * @param dst destination
 * @param dim
 * @return true if the coordinates are valid, otherwise false
 */
private static boolean validCoordinate(String src, String dst, int dim) {
    // TODO
}
</code>```

Body:
I am trying to loop asking coordinates and getting input from the scanner. I want to ask for input until the coordinates are valid. However I am really new with java and the loops confused me for this task.
First I should print a console output asking the player to input a pair of board coordinates.

If the inputs are valid coordinates I will return the coordinates as a string array.

If the inputs are not valid coordinates I should print an error message and then ask again until I get valid coordinates.

public static String[] positionQuery(int dim, Scanner test_in) {
    Scanner stdin = new Scanner(System.in);
    System.out.println("Provide origin and destination coordinates.");
    System.out.println("Enter two positions between A1-H8:");
    String s1 = stdin.nextLine();
    String[] coordinates = s1.split(" ");
    String origin = coordinates[0];
    String dest = coordinates[1];

    while (!validCoordinate(origin, dim) && !validCoordinate(dest,dim)) {
        System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
        String s2 = stdin.nextLine();
        String[] coordinates2 = s2.split(" ");
        String origin2 = coordinates[0];
        String dest2 = coordinates[1];
    }
    return new String[0];
}

I created a helper function validCoordinate(String, int) that checks the validity.
How can I fix my code?

Body:
This is how it can be. With while(true), you get an input. If the coordinates are valid, it will return them. Just implement the validation method the way you want and you're good to go.

public static String[] positionQuery(int dim) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Provide origin and destination coordinates.");
    System.out.println("Enter two positions between A1-H8:");
    while(true) {
        String line = scanner.nextLine();
        String[] coordinates = line.split(" ");
        if(coordinates.length == 2) { // valid input with just one space
            String src = coordinates[0];
            String dst = coordinates[1];
            if(validCoordinate(src, dst, dim)) {
                return coordinates;
            }
        }
        System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
    }
}

/**
 * checks the validity of source and destination
 * @param src source
 * @param dst destination
 * @param dim
 * @return true if the coordinates are valid, otherwise false
 */
private static boolean validCoordinate(String src, String dst, int dim) {
    // TODO
}


问:
Unable to use aggregate in mongoose from nodejs
I have two collections in mongodb named 'users' and 'posts'

users look like this:-

```<code>[
    {
      "_id": "5e3ffba65bad3a38dc0509cd",
      "name": "Ekansh Jain",
      "email": "ejekanshjain@gmail.com",
      "password": "$2a$10$lF1evuJgfC0N7fIC4I7KrOG.lq56aiHzndIYwc/YRb3auLTgHfmGK",
      "createdAt": "2020-02-09T12:31:34.117Z",
      "updatedAt": "2020-02-09T12:31:34.117Z",
      "__v": 0
    },
    {
      "_id": "5e403dcd1000793694bd2276",
      "name": "Ekansh Jain",
      "email": "ejekanshjain2@gmail.com",
      "password": "$2a$10$qGmng4KrXVXKt0RLnSMgMueo.BenKM43QIpURrzxW4M.HGDHe//TC",
      "createdAt": "2020-02-09T17:13:49.508Z",
      "updatedAt": "2020-02-09T17:13:49.508Z",
      "__v": 0
    }
]
</code>```

posts look like this

```<code>[
    {
      "_id": "5e403aa22a28e430b0d2641a",
      "title": "My Post 1",
      "body": "this is my first post's body",
      "createdBy": "5e3ffba65bad3a38dc0509cd",
      "createdAt": "2020-02-09T17:00:18.991Z",
      "updatedAt": "2020-02-09T17:00:18.991Z",
      "__v": 0,
      "userInfo": []
    },
    {
      "_id": "5e403e8b1000793694bd2278",
      "title": "LOL",
      "body": "LOL",
      "createdBy": "5e403dcd1000793694bd2276",
      "createdAt": "2020-02-09T17:16:59.513Z",
      "updatedAt": "2020-02-09T17:16:59.513Z",
      "__v": 0,
      "userInfo": []
    },
    {
      "_id": "5e46c8cfe56d4325b4e8d334",
      "title": "test Post",
      "body": "this is my first post's body",
      "createdBy": "5e3ffba65bad3a38dc0509cd",
      "createdAt": "2020-02-14T16:20:31.771Z",
      "updatedAt": "2020-02-14T16:20:31.771Z",
      "__v": 0,
      "userInfo": []
    }
]
</code>```

I have two mongoose models in my nodejs express application named User and Post.

I am not able to aggregate (unable apply inner join on the posts and user)

Here's the code I am currently using right now :-

```<code>const posts = await Post.aggregate([
            {
                "$lookup": {
                    "from": "users",
                    "localField": "createdBy",
                    "foreignField": "_id",
                    "as": "userInfo"
                }
            }
        ]).exec()
</code>```

In the result, it returns array of objects of posts with empty userInfo object.
Can someone help me out with this...

答:
As createdBy is a string & _id is of type ObjectId(), then You need to bring both fields to same type, try this :

```<code>Post.aggregate([
    {
        $lookup:
        {
            from: "users",
            let: { createdBy: "$createdBy" },
            pipeline: [
                {
                    $match:
                    {
                        $expr:
                            { $eq: [{ $toObjectId: "$$createdBy" }, "$_id"] }
                    }
                }
            ],
            as: "userInfo"
        }
    }
])
</code>```

Test : MongoDB-Playground

Note : Alternatively if you don't want to convert these every time you need to store createdBy as ObjectId().

So in your Post model createdBy type should be Schema.Types.ObjectId.

while saving Post document createdBy : mongoose.Types.ObjectId('someString');

Body:
I have two collections in mongodb named 'users' and 'posts'

users look like this:-

[
    {
      "_id": "5e3ffba65bad3a38dc0509cd",
      "name": "Ekansh Jain",
      "email": "ejekanshjain@gmail.com",
      "password": "$2a$10$lF1evuJgfC0N7fIC4I7KrOG.lq56aiHzndIYwc/YRb3auLTgHfmGK",
      "createdAt": "2020-02-09T12:31:34.117Z",
      "updatedAt": "2020-02-09T12:31:34.117Z",
      "__v": 0
    },
    {
      "_id": "5e403dcd1000793694bd2276",
      "name": "Ekansh Jain",
      "email": "ejekanshjain2@gmail.com",
      "password": "$2a$10$qGmng4KrXVXKt0RLnSMgMueo.BenKM43QIpURrzxW4M.HGDHe//TC",
      "createdAt": "2020-02-09T17:13:49.508Z",
      "updatedAt": "2020-02-09T17:13:49.508Z",
      "__v": 0
    }
]

posts look like this

[
    {
      "_id": "5e403aa22a28e430b0d2641a",
      "title": "My Post 1",
      "body": "this is my first post's body",
      "createdBy": "5e3ffba65bad3a38dc0509cd",
      "createdAt": "2020-02-09T17:00:18.991Z",
      "updatedAt": "2020-02-09T17:00:18.991Z",
      "__v": 0,
      "userInfo": []
    },
    {
      "_id": "5e403e8b1000793694bd2278",
      "title": "LOL",
      "body": "LOL",
      "createdBy": "5e403dcd1000793694bd2276",
      "createdAt": "2020-02-09T17:16:59.513Z",
      "updatedAt": "2020-02-09T17:16:59.513Z",
      "__v": 0,
      "userInfo": []
    },
    {
      "_id": "5e46c8cfe56d4325b4e8d334",
      "title": "test Post",
      "body": "this is my first post's body",
      "createdBy": "5e3ffba65bad3a38dc0509cd",
      "createdAt": "2020-02-14T16:20:31.771Z",
      "updatedAt": "2020-02-14T16:20:31.771Z",
      "__v": 0,
      "userInfo": []
    }
]

I have two mongoose models in my nodejs express application named User and Post.

I am not able to aggregate (unable apply inner join on the posts and user)

Here's the code I am currently using right now :-

const posts = await Post.aggregate([
            {
                "$lookup": {
                    "from": "users",
                    "localField": "createdBy",
                    "foreignField": "_id",
                    "as": "userInfo"
                }
            }
        ]).exec()

In the result, it returns array of objects of posts with empty userInfo object.
Can someone help me out with this...

Body:
As createdBy is a string & _id is of type ObjectId(), then You need to bring both fields to same type, try this :

Post.aggregate([
    {
        $lookup:
        {
            from: "users",
            let: { createdBy: "$createdBy" },
            pipeline: [
                {
                    $match:
                    {
                        $expr:
                            { $eq: [{ $toObjectId: "$$createdBy" }, "$_id"] }
                    }
                }
            ],
            as: "userInfo"
        }
    }
])

Test : MongoDB-Playground

Note : Alternatively if you don't want to convert these every time you need to store createdBy as ObjectId().

So in your Post model createdBy type should be Schema.Types.ObjectId.

while saving Post document createdBy : mongoose.Types.ObjectId('someString');


问:
Docker Hub on AirGap Widows 2019 Server With No Internet Connection
I am bit stuck on how to do following, excuse me if this is not actually fit StackOverFlow rules.

We have

VM Workstation With Windows 2019 Server (Host)

No Internet Connection on server as a company policy

What I am Planning To Achieve

Run Multiple Docker Containers on Windows Server 2019 Host

Docker Container 1(Private Docker Hub) : Function similar to Docker Hub where users can pull images and push new images.

Docker Container 2 : Python Container. This container is build by pulling image from Container 1(Private Docker Hub). i.e., When user execute command docker pull python on Windows Server 2019 Host, instead of pulling image from Docker Hub(Remember no internet), it should pull the image from Container 1.

I have searched google there are lot of air-gap articles but not very clear on how to approach problem like this with complete air-gap.

Any pointers or directions will really help me.

Thanks once again.

答:
You can point Docker client to you private registry: https://www.docker.com/blog/how-to-use-your-own-registry/

To seed your registry you need computer with acces to internet to pull image and then push to your private registry.

Consider security implications when running public images in restricted environment.


问:
Transpose and create new variables in R
I have a data frame with the following structure:

```<code>study_id date
1        01/01/2011
2        01/01/2012
2        01/01/2013
3        01/01/2014
3        01/01/2015
3        01/01/2016
</code>```

I would like to change the data frame to:

```<code>study_id date_1      date_2    date_3
1        01/01/2011  NA         NA
2        01/01/2012  01/01/2013 NA
3        01/01/2014  01/01/2014 01/01/2016

</code>```

Please note these dates are just examples, the date does not follow this order (01/01/2011 + 1 years and so goes on)

PS: Thanks webprogrammer for editing my question. I deleted before I noticed you fixed it.

答:
We can use dcast from data.table

```<code>library(data.table)
dcast(setDT(df1), study_id ~ paste0("date_", rowid(study_id)), value.var = "date")
#study_id     date_1     date_2     date_3
#1:        1 01/01/2011       <NA>       <NA>
#2:        2 01/01/2012 01/01/2013       <NA>
#3:        3 01/01/2014 01/01/2015 01/01/2016
</code>```

Title: Transpose and create new variables in R

Body:
I have a data frame with the following structure:

study_id date
1        01/01/2011
2        01/01/2012
2        01/01/2013
3        01/01/2014
3        01/01/2015
3        01/01/2016

I would like to change the data frame to:

study_id date_1      date_2    date_3
1        01/01/2011  NA         NA
2        01/01/2012  01/01/2013 NA
3        01/01/2014  01/01/2014 01/01/2016

Please note these dates are just examples, the date does not follow this order (01/01/2011 + 1 years and so goes on)

PS: Thanks webprogrammer for editing my question. I deleted before I noticed you fixed it.

Body:
We can use dcast from data.table

library(data.table)
dcast(setDT(df1), study_id ~ paste0("date_", rowid(study_id)), value.var = "date")
#study_id     date_1     date_2     date_3
#1:        1 01/01/2011       <NA>       <NA>
#2:        2 01/01/2012 01/01/2013       <NA>
#3:        3 01/01/2014 01/01/2015 01/01/2016


问:
Dynamically Change WCF Service URL in ASP.NET MVC
I have one solution in which I have 2 projects with:

ASP.NET MVC Application to consume wcf services.

5 WCF services.

I have added one web service reference in the project 1. Now, I need to use different services based on the user e.g.

User Type 1: Only allow to consume Service 1.

User Type 2: Only allow to consume Service 2.
etc.

I have Service URL's like localhost:6227/Service1.svc, localhost:6227/Service2.svc etc.

I have stored all service URL's in the db and I need to change URL for each user type to consume his allowed service only without adding more end points and only change URL from the backend based on user type. I need relevant link or code to solve this problem.

Edit

In Web Config
I have added just this endpoint in the mvc application and I don't want to use web config to change address in here but I want to change address in the code for each user type while application is running.

```<code><client>
      <endpoint address="http://localhost:6227/Service1.svc"
        binding="customBinding" bindingConfiguration="CustomBinding_IService1"
        contract="Service1.IService1" name="CustomBinding_IService1" />
    </client>
</code>```

答:
You can modify directly your EndPoint Address doing this:</p>

```<code>ClientService1 ws = new ClientService1();
ws.Endpoint.Address = new EndpointAddress("Your new URL svc service");
</code>```

Body:
I have one solution in which I have 2 projects with:

ASP.NET MVC Application to consume wcf services.

5 WCF services.

I have added one web service reference in the project 1. Now, I need to use different services based on the user e.g.

User Type 1: Only allow to consume Service 1.

User Type 2: Only allow to consume Service 2.
etc.

I have Service URL's like localhost:6227/Service1.svc, localhost:6227/Service2.svc etc.

I have stored all service URL's in the db and I need to change URL for each user type to consume his allowed service only without adding more end points and only change URL from the backend based on user type. I need relevant link or code to solve this problem.

Edit

In Web Config
I have added just this endpoint in the mvc application and I don't want to use web config to change address in here but I want to change address in the code for each user type while application is running.

<client>
      <endpoint address="http://localhost:6227/Service1.svc"
        binding="customBinding" bindingConfiguration="CustomBinding_IService1"
        contract="Service1.IService1" name="CustomBinding_IService1" />
    </client>

Body:
You can modify directly your EndPoint Address doing this:

ClientService1 ws = new ClientService1();
ws.Endpoint.Address = new EndpointAddress("Your new URL svc service");


问:
How to switch two words around in file document in python
I was wondering how to switch two words around in a file document in python. Example: I want to switch the words motorcycle to car, and car to motorcycle.
The way I'm doing it is making it have all the words motorcycle change to car, and because car is being switched to motorcycle, it get's switched back to car. Hopefully that makes sense.</p>

答:
First, replace all the motocycle to carholder

Second, replace all car to motocycle

Third, replace all carholder to car

That's it


答:
```<code>final_list = []
def make_one_list(arg_list):
  for arg in arg_list:
    if isinstance(arg, list):
        for item in arg:
            final_list.append(item)
    else:
        final_list.append(arg)
  return final_list
</code>```

Title: Python function that takes lists and elements and makes one list


问:
syntax for ancestor:: in Xpath expression
xpath -e '//attribute::vo/../text()' books.xml

returns the content of each element having an attribute named vo.

For example, with this book.xml :

```<code><bookstore>
<book category="cooking">
  <title lang="en" vo="it">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>
<book category="children">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>
<book category="web">
  <title lang="en" vo="fr">XQuery Kick Start</title>
  <author>James McGovern</author>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
</book>
<book category="web">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
</book>
</bookstore>
</code>```

then the request :

xpath -e '//attribute::vo/../text()' books.xml

gives :

```<code>Found 2 nodes in /tmp/books.xml:
-- NODE --
Everyday Italian
-- NODE --
XQuery Kick Start
</code>```

What should be the syntax of the request having the same result, but with ancestor:: in place of .. ?

答:
If you still want to know how ancestor works, it takes parent of current node, grand parent of current node and so on up to the root. So your query with ancestor would look like

```<code>//attribute::vo/ancestor::*[1]/title/text()
</code>```

Where ancestor means that you're going to collect all the (grand)parents, * means that you do not care of what nodes those (grand)parents would be, and [1] means that you need the "closest" one to the current node.

The same result would be produced by the following query:

```<code>//attribute::vo/ancestor::book/title/text()
</code>```

Since it doesn't take root element because it is not book node. So that we have "flat" hierarchy here.

The following query would take only the books with "Web" category (this is not what you asked actually but probably will give more clear vision on how to work with axes):

//attribute::vo/ancestor::book[@category='web']/title/text()

Body:
xpath -e '//attribute::vo/../text()' books.xml

returns the content of each element having an attribute named vo.

For example, with this book.xml :

<bookstore>
<book category="cooking">
  <title lang="en" vo="it">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>
<book category="children">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>
<book category="web">
  <title lang="en" vo="fr">XQuery Kick Start</title>
  <author>James McGovern</author>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
</book>
<book category="web">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
</book>
</bookstore>

then the request :

xpath -e '//attribute::vo/../text()' books.xml

gives :

Found 2 nodes in /tmp/books.xml:
-- NODE --
Everyday Italian
-- NODE --
XQuery Kick Start

What should be the syntax of the request having the same result, but with ancestor:: in place of .. ?

Body:
If you still want to know how ancestor works, it takes parent of current node, grand parent of current node and so on up to the root. So your query with ancestor would look like

//attribute::vo/ancestor::*[1]/title/text()

Where ancestor means that you're going to collect all the (grand)parents, * means that you do not care of what nodes those (grand)parents would be, and [1] means that you need the "closest" one to the current node.

The same result would be produced by the following query:

//attribute::vo/ancestor::book/title/text()

Since it doesn't take root element because it is not book node. So that we have "flat" hierarchy here.

The following query would take only the books with "Web" category (this is not what you asked actually but probably will give more clear vision on how to work with axes):

//attribute::vo/ancestor::book[@category='web']/title/text()


问:
Converting a member function to a static function in C++
I am writing a memory testing framework, in which I replace dynamic memory allocation functions with my own (eg. malloc, realloc, free, etc.). However, the system expects static functions (I can not change this).

I have a MemoryTester class, which logs the memory calls, and I want to bind its member function implementations of the memory allocation functions. Is this possible with C++?

EDIT:

Here is some code highlighting what I'm trying to do:

```<code>typedef void*(allocateFuncPtr) (uint8_t);
typedef void (freeFuncPtr) (void*);

void setAllocateFunction(allocateFuncPtr) {...}
void setFreeFunction(freeFuncPtr) {...}

class MemoryTester
{
    void *malloc(uint8_t size);
    void free(void *ptr);
}

int main()
{
    MemoryTester *tester = new MemoryTester();

    //want to set allocate and free functions to those in tester
    setAllocateFunction( tester->getAllocateFunction() );
    setFreeFunction( tester->getFreeFunction() );

    return 0;
}
</code>```

答: Have one singleton MemoryTester object, and have bridge static functions that call member functions of that object.</p>

Body:
I am writing a memory testing framework, in which I replace dynamic memory allocation functions with my own (eg. malloc, realloc, free, etc.). However, the system expects static functions (I can not change this).

I have a MemoryTester class, which logs the memory calls, and I want to bind its member function implementations of the memory allocation functions. Is this possible with C++?

EDIT:

Here is some code highlighting what I'm trying to do:

typedef void*(allocateFuncPtr) (uint8_t);
typedef void (freeFuncPtr) (void*);

void setAllocateFunction(allocateFuncPtr) {...}
void setFreeFunction(freeFuncPtr) {...}

class MemoryTester
{
    void *malloc(uint8_t size);
    void free(void *ptr);
}

int main()
{
    MemoryTester *tester = new MemoryTester();

    //want to set allocate and free functions to those in tester
    setAllocateFunction( tester->getAllocateFunction() );
    setFreeFunction( tester->getFreeFunction() );

    return 0;
}


问:
Replace image in word doc using OpenXML
Following on from my last question here

OpenXML looks like it probably does exactly what I want, but the documentation is terrible. An hour of googling hasn't got me any closer to figuring out what I need to do.

I have a word document. I want to add an image to that word document (using word) in such a way that I can then open the document in OpenXML and replace that image. Should be simple enough, yes?

I'm assuming I should be able to give my image 'placeholder' an id of some sort and then use GetPartById to locate the image and replace it. Would this be the correct method? What is this Id? How do you add it using Word?

Every example I can find which does anything remotely similar starts by building the whole word document from scratch in ML, which really isn't a lot of use.

EDIT: it occured to me that it would be easier to just replace the image in the media folder with the new image, but again can't find any indication of how to do this.

答:
Okay, thank you to everyone who helped me out on this. My goal was simpler than replacing an image, mainly to pull out all images in a Word document. I found this code did the work for me on that, INCLUDING the needed extension.

Feel free to use:

```<code>var inlineImages = from paragraph in wordprocessingDocument.MainDocumentPart.Document.Body
  from graphic in paragraph.Descendants<DocumentFormat.OpenXml.Drawing.Graphic>()
  let graphicData = graphic.Descendants<DocumentFormat.OpenXml.Drawing.GraphicData>().FirstOrDefault()
  let pic = graphicData.ElementAt(0).Descendants<DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault()
  let imgPID = pic.GetAttribute("embed", "http://schemas.openxmlformats.org/officeDocument/2006/relationships").Value
  select new { Id = imgPID,
               Extension = ((ImagePart)wordprocessingDocument.MainDocumentPart.GetPartById(imgPID)).ContentType.Split('/')[1]
};
</code>```

ContentLicense: CC BY-SA 2.5

Title: Replace image in word doc using OpenXML

Body:
Okay, thank you to everyone who helped me out on this. My goal was simpler than replacing an image, mainly to pull out all images in a Word document. I found this code did the work for me on that, INCLUDING the needed extension.

Feel free to use:

var inlineImages = from paragraph in wordprocessingDocument.MainDocumentPart.Document.Body
  from graphic in paragraph.Descendants<DocumentFormat.OpenXml.Drawing.Graphic>()
  let graphicData = graphic.Descendants<DocumentFormat.OpenXml.Drawing.GraphicData>().FirstOrDefault()
  let pic = graphicData.ElementAt(0).Descendants<DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault()
  let imgPID = pic.GetAttribute("embed", "http://schemas.openxmlformats.org/officeDocument/2006/relationships").Value
  select new { Id = imgPID,
               Extension = ((ImagePart)wordprocessingDocument.MainDocumentPart.GetPartById(imgPID)).ContentType.Split('/')[1]
};


问:
WF4 Services and WIF Integration
Are there proven patterns that anyone could share regarding Workflow 4.0 services integrated with Windows Identity Foundation? We are looking for the best way to inspect the STS token and claims in order to derive who the user is outside the workflow service instance context and make the application's user object available to the workflow context.

We want to maintain separation of concerns between the service implementation of WIF and workflow business logic so our workflow services are highly testable. We have seen a few examples provided which point to wrapping the Receive activity with a code activity that instantiates an implementation of IReceiveMessageCallback in order to get a reference to the OperationContext. Link to Maurice's Blog Post. However, this means activities internal to the service are dependent on the existence of the operation context and possibly even the IClaimsIdentity.

The best solution we can come up with so far is to create an implementation of IDispatchMessageInspector for the service that interrogates the token and creates the application user objects needed by the workflow making them available to the workflow runtime via InstanceContext.Extensions. This seems to work but doesn't feel exactly solid. Any help or feedback is greatly appreciated!

Service Behavior

```<code>public class SecurityTokenServiceBehavior : IServiceBehavior, IDispatchMessageInspector
{
...
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
    {
        var claimsPrincipal = (IClaimsPrincipal)(Thread.CurrentPrincipal is GenericPrincipal ? null : Thread.CurrentPrincipal);

        ...

        instanceContext.Extensions.Add(new SecurityContextExtension(appUser, audit));
        return null;
    }
...
}
</code>```

IReceiveMessageCallback

```<code>public class SecurityContextCallback : IReceiveMessageCallback
{
    [DataMember]
    public SecurityContextExtension SecurityContext { get; private set; }

    public void OnReceiveMessage(OperationContext operationContext, ExecutionProperties activityExecutionProperties)
    {
        SecurityContext = operationContext.InstanceContext.Extensions.Find<SecurityContextExtension>();
    }
}
</code>```

答:
Did you see this blog post about using the ClaimsAuthorizationManager as well? Using the ClaimsAuthorizationManager is the usual way to check for authorization when using WIF.

See Dominick post here for some example on how to embed checks in your code using either the ClaimsAuthorize attribute or the static ClaimsAuthorize.CheckAccess() method. You might also want to take a look at the WF Security Pack CTP 1 here.

Title: WF4 Services and WIF Integration

Body:
Are there proven patterns that anyone could share regarding Workflow 4.0 services integrated with Windows Identity Foundation? We are looking for the best way to inspect the STS token and claims in order to derive who the user is outside the workflow service instance context and make the application's user object available to the workflow context.

We want to maintain separation of concerns between the service implementation of WIF and workflow business logic so our workflow services are highly testable. We have seen a few examples provided which point to wrapping the Receive activity with a code activity that instantiates an implementation of IReceiveMessageCallback in order to get a reference to the OperationContext. Link to Maurice's Blog Post. However, this means activities internal to the service are dependent on the existence of the operation context and possibly even the IClaimsIdentity.

The best solution we can come up with so far is to create an implementation of IDispatchMessageInspector for the service that interrogates the token and creates the application user objects needed by the workflow making them available to the workflow runtime via InstanceContext.Extensions. This seems to work but doesn't feel exactly solid. Any help or feedback is greatly appreciated!

Service Behavior

public class SecurityTokenServiceBehavior : IServiceBehavior, IDispatchMessageInspector
{
...
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
    {
        var claimsPrincipal = (IClaimsPrincipal)(Thread.CurrentPrincipal is GenericPrincipal ? null : Thread.CurrentPrincipal);

        ...

        instanceContext.Extensions.Add(new SecurityContextExtension(appUser, audit));
        return null;
    }
...
}

IReceiveMessageCallback

public class SecurityContextCallback : IReceiveMessageCallback
{
    [DataMember]
    public SecurityContextExtension SecurityContext { get; private set; }

    public void OnReceiveMessage(OperationContext operationContext, ExecutionProperties activityExecutionProperties)
    {
        SecurityContext = operationContext.InstanceContext.Extensions.Find<SecurityContextExtension>();
    }
}


问:
How can I print multidimensional arrays in C?
```<code>#include <stdio.h>

int main(){

  int number[3][4] = {
    {10,20,30,40},
    {15,25,35,45},
    {47,48,49,50},
  };
      printf("%s",number[]);
  return 0;
}
</code>```

Ok, here's my code and what I wonder is how can I print out those arrays that I created. Do I have to use for loop or is there another way?

P.S: Im a newbie.

答:
Use nested for loops. For example

```<code>for ( size_t i = 0; i < 3; i++ )
{
    for ( size_t j = 0; j < 4; j++ )
    {
        printf( "%2d ", number[i][j] );
    }
    putchar( '\n' );
}
</code>```

Pay attention to that it is a bad idea to use magic numbers like 3 and 4. Instead use named constants.

As for the conversion specifier %s then it is used to output one-dimensional character arrays that contain strings

Here is a demonstrative program

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

int main(void)
{
    enum { M = 3, N = 4 };
    int number[M][N] =
    {
        { 10, 20, 30, 40 },
        { 15, 25, 35, 45 },
        { 47, 48, 49, 50 },
    };

    for ( size_t i = 0; i < M; i++ )
    {
        for ( size_t j = 0; j < N; j++ )
        {
            printf( "%2d ", number[i][j] );
        }
        putchar( '\n' );
    }

    return 0;
}
</code>```

Its output is

```<code>10 20 30 40
15 25 35 45
47 48 49 50
</code>```

To output a two-dimensional integer array as a one-dimensional integer array apply casting to the array designator to the type int * or const int *.

For example

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

int main(void)
{
    enum { M = 3, N = 4 };
    int number[M][N] =
    {
        { 10, 20, 30, 40 },
        { 15, 25, 35, 45 },
        { 47, 48, 49, 50 },
    };

    const int *p = ( const int * )number;

    for ( size_t i = 0; i < M * N; i++ )
    {
        printf( "%2d ", p[i] );
    }
    putchar( '\n' );

    return 0;
}
</code>```

The program output is

```<code>10 20 30 40 15 25 35 45 47 48 49 50
</code>```

And vice versa to print a one dimensional array as a two-dimensional array use the following approach.

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

int main(void)
{
    enum { N = 12 };
    int number[N] = { 10, 20, 30, 40, 15, 25, 35, 45, 47, 48, 49, 50 };

    size_t rows = 3, cols = 4;

    for ( size_t i = 0; i < rows; i++ )
    {
        for ( size_t j = 0; j < cols; j++ )
        {
            printf( "%2d ", number[i * cols + j] );
        }
        putchar( '\n' );
    }

    return 0;
}
</code>```

The program output is

```<code>10 20 30 40
15 25 35 45
47 48 49 50
</code>```

Body:
#include <stdio.h>

int main(){

  int number[3][4] = {
    {10,20,30,40},
    {15,25,35,45},
    {47,48,49,50},
  };
      printf("%s",number[]);
  return 0;
}

Ok, here's my code and what I wonder is how can I print out those arrays that I created. Do I have to use for loop or is there another way?

P.S: Im a newbie.

Body:
Use nested for loops. For example

for ( size_t i = 0; i < 3; i++ )
{
    for ( size_t j = 0; j < 4; j++ )
    {
        printf( "%2d ", number[i][j] );
    }
    putchar( '\n' );
}

Pay attention to that it is a bad idea to use magic numbers like 3 and 4. Instead use named constants.

As for the conversion specifier %s then it is used to output one-dimensional character arrays that contain strings

Here is a demonstrative program

#include <stdio.h>

int main(void)
{
    enum { M = 3, N = 4 };
    int number[M][N] =
    {
        { 10, 20, 30, 40 },
        { 15, 25, 35, 45 },
        { 47, 48, 49, 50 },
    };

    for ( size_t i = 0; i < M; i++ )
    {
        for ( size_t j = 0; j < N; j++ )
        {
            printf( "%2d ", number[i][j] );
        }
        putchar( '\n' );
    }

    return 0;
}

Its output is

10 20 30 40
15 25 35 45
47 48 49 50

To output a two-dimensional integer array as a one-dimensional integer array apply casting to the array designator to the type int * or const int *.

For example

#include <stdio.h>

int main(void)
{
    enum { M = 3, N = 4 };
    int number[M][N] =
    {
        { 10, 20, 30, 40 },
        { 15, 25, 35, 45 },
        { 47, 48, 49, 50 },
    };

    const int *p = ( const int * )number;

    for ( size_t i = 0; i < M * N; i++ )
    {
        printf( "%2d ", p[i] );
    }
    putchar( '\n' );

    return 0;
}

The program output is

10 20 30 40 15 25 35 45 47 48 49 50

And vice versa to print a one dimensional array as a two-dimensional array use the following approach.

#include <stdio.h>

int main(void)
{
    enum { N = 12 };
    int number[N] = { 10, 20, 30, 40, 15, 25, 35, 45, 47, 48, 49, 50 };

    size_t rows = 3, cols = 4;

    for ( size_t i = 0; i < rows; i++ )
    {
        for ( size_t j = 0; j < cols; j++ )
        {
            printf( "%2d ", number[i * cols + j] );
        }
        putchar( '\n' );
    }

    return 0;
}

The program output is

10 20 30 40
15 25 35 45
47 48 49 50


问:
How to enable a bool by holding left click and disable that bool
I am quite new to Unity.</p>

```<code>private bool scoreIncreasing;

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        scoreIncreasing = true;
    }
    else
    {
        scoreIncreasing = false;
    }
}
</code>```

答:
There are 3 events for key or button:

GetMouseButtonDown invokes only once when it was pressed

GetMouseButtonUp invokes only once when it was released

GetMouseButton every frame while button is holded

For your case change GetMouseButtonDown to GetMouseButton

Body:
I am quite new to Unity.

private bool scoreIncreasing;

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        scoreIncreasing = true;
    }
    else
    {
        scoreIncreasing = false;
    }
}


问:
Error with Subnet ID while creating EC2 instaces with module
I am trying to create 3 ec2 instances in private subnet. Using ec2-module.tf from below git repo

https://github.com/quickbooks2018/Terraform-Classic-Modules

Below is the line I enabled in tf file

ec2-subnets-ids = ["${module.vpc.private-subnet-ids}"]

Error looks below,

Error: Invalid value for module argument

on ec2-module.tf line 17, in module "ec2-app-v1":
  17:   ec2-subnets-ids = ["${module.vpc.private-subnet-ids}"]

The given value is not suitable for child module variable "ec2-subnets-ids"
defined at modules/ec2/ec2-variables.tf:46,1-27: element 0: string required.

Please help to understand the error and how to fix it.

答:
Looking at those modules you're referencing it looks like the issue is that you're passing a list of list of strings but should just be passing a list of strings.

So, instead of

```<code>ec2-subnets-ids = ["${module.vpc.private-subnet-ids}"]
</code>```

which passes a list of a single element (that element being a list of strings), try

```<code>ec2-subnets-ids = "${module.vpc.private-subnet-ids}"
</code>```

which just passes the list forward.

Body:
Looking at those modules you're referencing it looks like the issue is that you're passing a list of list of strings but should just be passing a list of strings.

So, instead of

ec2-subnets-ids = ["${module.vpc.private-subnet-ids}"]

which passes a list of a single element (that element being a list of strings), try

ec2-subnets-ids = "${module.vpc.private-subnet-ids}"

which just passes the list forward.


问:
Autopsy on netbeans giving java version error
I am trying to run autopsy on windows, netbeans.
I am getting unsupported java version 13
Make sure that the java version is 1.8.0_66 or higher

https://github.com/sleuthkit/autopsy

I set up enviroment variables, and its not working.

When I echo %JAVA_HOME%

I am getting C:\Programfiles/java/jre1.8.0_241

java -version prints 1.8.0_241

I also went to check netbeans.conf

found the property named “netbeans_jdkhome”. it is set correctly to
Windows Systems, this might be C:\Program Files\Java\jdk-13.0.2).

Build.xml

```<code><condition property="supported-java-versions">
        <or>
            <matches string="${java.version}" pattern="1\.8\.0_6[6-9]"/>
            <matches string="${java.version}" pattern="1\.8\.0_[7-9][0-9]"/>
            <matches string="${java.version}" pattern="1\.8\.0_[1-9][0-9][0-9]"/>
            <matches string="${java.version}" pattern="1\.8\.[1-9]_[0-9][0-9]"/>
            <equals arg1="${ant.java.version}" arg2="1.9"/>
        </or>
    </condition>
</code>```

答:
[This is not necessarily a solution to your problem, but is too long to post as a comment.]

You haven't specified your NetBeans version, but for all versions note that:

NetBeans doesn't care at all about the settings of environment variables such as JAVA_HOME. They are completely irrelevant. Checking the value of java -version from the command line is also irrelevant; it proves/disproves nothing.

NetBeans does care about the value of netbeans_jdkhome in netbeans.conf, and it will use it (if set).

In your case it seems that netbeans_jdkhome has a value that specifies the path to your JDK 13 installation. If you are running NetBeans 8.2 that is an invalid path since 8.2 does not support Java versions > 1.8. The fix is to edit netbeans.conf and set netbeans_jdkhome to specify the path to your Java 8 installation.

If you are not running NetBeans 8.x please update your question with details of your NetBeans installation. You can get that by copying and pasting the output from the Help > About window.

Body:
I am trying to run autopsy on windows, netbeans.
I am getting unsupported java version 13
Make sure that the java version is 1.8.0_66 or higher

https://github.com/sleuthkit/autopsy

I set up enviroment variables, and its not working.

When I echo %JAVA_HOME%

I am getting C:\Programfiles/java/jre1.8.0_241

java -version prints 1.8.0_241

I also went to check netbeans.conf

found the property named “netbeans_jdkhome”. it is set correctly to
Windows Systems, this might be C:\Program Files\Java\jdk-13.0.2).

Build.xml

<condition property="supported-java-versions">
        <or>
            <matches string="${java.version}" pattern="1\.8\.0_6[6-9]"/>
            <matches string="${java.version}" pattern="1\.8\.0_[7-9][0-9]"/>
            <matches string="${java.version}" pattern="1\.8\.0_[1-9][0-9][0-9]"/>
            <matches string="${java.version}" pattern="1\.8\.[1-9]_[0-9][0-9]"/>
            <equals arg1="${ant.java.version}" arg2="1.9"/>
        </or>
    </condition>


问:
Await isn't waiting?
Hi I've got two functions. They're called inside another function. And I need the second function execute after the first is done.

I'm sorry this is probably a very simple question, but I'm still trying to wrap my head around promises and async/await in js. Can anyone help me figure out why this isn't working.

```<code>async function addDetails(){
    const sub = await getSession();
    // now wait for firstFunction to finish...
    addProfileDetails(sub);
  };
</code>```

I have debug/logging statements in both. So I know that addProfileDetails is being executed before the variable sub is defined.

I'm using react native and node.js

EDIT:

```<code>export function getSession() {
  console.log("checking user ...............................................")
  Auth.currentSession().then(res=>{
      console.log("retrieving token");
      let accessToken = res.getAccessToken()
      let payload = accessToken.payload;
      console.log(`sub: ${payload.sub}`)
      return payload.sub
  })
};
</code>```

This is my getSession() function. It also needs to be async?

答:
Try this in your getSession

```<code>export function getSession() {
  return new Promise((resolve, reject) => {
      console.log("checking user ...............................................")
      Auth.currentSession().then(res=>{
      console.log("retrieving token");
      let accessToken = res.getAccessToken()
      let payload = accessToken.payload;
      console.log(`sub: ${payload.sub}`)
      resolve(payload.sub)
  })

};
</code>```

Title: Await isn't waiting?

Body:
Hi I've got two functions. They're called inside another function. And I need the second function execute after the first is done.

I'm sorry this is probably a very simple question, but I'm still trying to wrap my head around promises and async/await in js. Can anyone help me figure out why this isn't working.

async function addDetails(){
    const sub = await getSession();
    // now wait for firstFunction to finish...
    addProfileDetails(sub);
  };

I have debug/logging statements in both. So I know that addProfileDetails is being executed before the variable sub is defined.

I'm using react native and node.js

EDIT:

export function getSession() {
  console.log("checking user ...............................................")
  Auth.currentSession().then(res=>{
      console.log("retrieving token");
      let accessToken = res.getAccessToken()
      let payload = accessToken.payload;
      console.log(`sub: ${payload.sub}`)
      return payload.sub
  })
};

This is my getSession() function. It also needs to be async?

Body:
Try this in your getSession

export function getSession() {
  return new Promise((resolve, reject) => {
      console.log("checking user ...............................................")
      Auth.currentSession().then(res=>{
      console.log("retrieving token");
      let accessToken = res.getAccessToken()
      let payload = accessToken.payload;
      console.log(`sub: ${payload.sub}`)
      resolve(payload.sub)
  })

};


问:
is there a simple way to add the dplyr summarize function result to every row?
The following is a simple version of my data:

I want to create a flag for each group if they at least have one item in Column1.
I know I can do this in dplyr and then merge it with my original data but I was wondering if there is an easier way.

For example, I can do this:

```<code>df_column <- df %>% filter(!is.na(Column1)) %>% group_by(Group)%>%
  summarize(n=n_distinct(Column1))
</code>```

and then I can merge this with the original data and create a flag.

答:
Without filtering, we can do this with mutate by creating a logical column based on the number of unique elements (n_distinct) in 'Column1' after groupingby 'Group'

```<code>library(dplyr)
df %>%
     group_by(Group) %>%
     mutate(flag = n_distinct(Column1[!is.na(Column1)]) > 1)
</code>```

Body:
The following is a simple version of my data:

I want to create a flag for each group if they at least have one item in Column1.
I know I can do this in dplyr and then merge it with my original data but I was wondering if there is an easier way.

For example, I can do this:

df_column <- df %>% filter(!is.na(Column1)) %>% group_by(Group)%>%
  summarize(n=n_distinct(Column1))

and then I can merge this with the original data and create a flag.

Body:
Without filtering, we can do this with mutate by creating a logical column based on the number of unique elements (n_distinct) in 'Column1' after groupingby 'Group'

library(dplyr)
df %>%
     group_by(Group) %>%
     mutate(flag = n_distinct(Column1[!is.na(Column1)]) > 1)


答:
I figured out a way myself. Thanks to the ones who gave their own solution. It gave me new perspective.

Below is my code:

```<code>persons_library={}
persons=['david','anna','charlie']
for i,person in enumerate(persons,start=0):
    persons_library[person]=[]

with open('data.txt','r') as f:
    for line in f:
        line=line.replace('*',"")
        line=line.split()
        for i,val in enumerate(line,start=0):
            if val in persons_library:
                key=val
            else:
                persons_library[key].append(val)
    print(persons_library)
</code>```

Title: Adding words between lines to an array

Body:
This is the content of my file:

david    C001 C002 C004 C005 C006 C007

*    C008 C009 C010 C011 C016 C017 C018

*    C019 C020 C021 C022 C023 C024 C025

anna C500 C521 C523 C547 C555 C556

*    C557 C559 C562 C563 C566 C567 C568

*    C569 C571 C572 C573 C574 C575 C576

*    C578

charlie    C701 C702 C704 C706 C707 C708

*    C709 C712 C715 C716 C717 C718

I want my output to be:

david=[C001,C002,C004,C005,C006,C007,C008,C009,C010,C011,C016,C017,C018,C019,C020,C021,C022,C023,C024,C025]

anna=[C500,C521,C523,C547,C555,C556,C557,C559,C562,C563,C566,C567,C568,C569,C571,C572,C573,C574,C575,C576,C578]

charlie=[C701,C702,C704,C706,C707,C708,C709,C712,C715,C716,C717,C718]

I am able to create:

david=[C001,C002,C004,C005,C006,C007]
anna=[C500,C521,C523,C547,C555,C556]
charlie=[C701,C702,C704,C706,C707,C708]

counting the number of words in a line and using line[0] as the array name and adding the remaining words to the array.
However, I don't know how to take the continuation of words in the next lines starting with "*" to the array.

Can anyone help?

Body:
I figured out a way myself. Thanks to the ones who gave their own solution. It gave me new perspective.

Below is my code:

persons_library={}
persons=['david','anna','charlie']
for i,person in enumerate(persons,start=0):
    persons_library[person]=[]

with open('data.txt','r') as f:
    for line in f:
        line=line.replace('*',"")
        line=line.split()
        for i,val in enumerate(line,start=0):
            if val in persons_library:
                key=val
            else:
                persons_library[key].append(val)
    print(persons_library)


问:
Drop observations with certain conditions iterating in the whole dataframe
I am sure this question have been already made several times, but for some reason I am not able to find the answer. Basically, I have a dataframe with 500 variables (columns) and 15000 observarions (rows). The values of the variables ranges from -140 to 100, in all the obsertations.

Basically, I need to remove the observations (rows) that have some values that are between -20 and 0.

I tried with (X_train are the 500 variables):

```<code>for i in X_train.columns:
    a=X_train[(X_train[i] >= -20) & (X_train[i] <= 0) ]
</code>```

And also with this:

```<code>a = X_train[(X_train.iloc[:,:].values > -20) & (X_train.iloc[:,:].values < -0)]
</code>```

The first code gives me a dataframe full of NA's, and the second one a dataframe with 0 rows.

Someone could help me with the correct syntaxis for this?

Thank you!!!

答:
I think this should work:</p>

```<code>for col in X_train.columns:
    mask = list(X_train[col] <= 0) & (X_train[col] >= -20)
    X_train = X_train.loc[mask]
</code>```

Body:
I am sure this question have been already made several times, but for some reason I am not able to find the answer. Basically, I have a dataframe with 500 variables (columns) and 15000 observarions (rows). The values of the variables ranges from -140 to 100, in all the obsertations.

Basically, I need to remove the observations (rows) that have some values that are between -20 and 0.

I tried with (X_train are the 500 variables):

for i in X_train.columns:
    a=X_train[(X_train[i] >= -20) & (X_train[i] <= 0) ]

And also with this:

a = X_train[(X_train.iloc[:,:].values > -20) & (X_train.iloc[:,:].values < -0)]

The first code gives me a dataframe full of NA's, and the second one a dataframe with 0 rows.

Someone could help me with the correct syntaxis for this?

Thank you!!!

Body:
I think this should work:

for col in X_train.columns:
    mask = list(X_train[col] <= 0) & (X_train[col] >= -20)
    X_train = X_train.loc[mask]


问:
Find all lines where a value exists in one line
Here is my query

```<code>        select order_no, pkg_no, zone_no
        from T_DETAIL_ITEM a
        where order_no = 495
        order by order_no, pkg_no
</code>```

For a given package I have zone number = 0

What I need to do is return all the lines with the pkg_no = 1597. Because one where exists with a zero zone.

I tried a few different 'where exists' lines and it isn't working.

答:
One way is to self reference the table in a left join and only include those with a zone_no=0, within the join clause. The filter out non-matching records by excluding records that do not match from the left join, T2.pkg_no = NULL.</p>

```<code>SELECT
    T1.pkg_no, T1.zone_no
FROM
    T_DETAIL_ITEM  T1
    LEFT OUTER JOIN T_DETAIL_ITEM T2 ON T2.pkg_no = T1.pkg_no AND T2.zone_no = 0
WHERE
    NOT T2.pkg_no IS NULL
</code>```

Body:
Here is my query

        select order_no, pkg_no, zone_no
        from T_DETAIL_ITEM a
        where order_no = 495
        order by order_no, pkg_no

For a given package I have zone number = 0

What I need to do is return all the lines with the pkg_no = 1597. Because one where exists with a zero zone.

I tried a few different 'where exists' lines and it isn't working.

Body:
One way is to self reference the table in a left join and only include those with a zone_no=0, within the join clause. The filter out non-matching records by excluding records that do not match from the left join, T2.pkg_no = NULL.

SELECT
    T1.pkg_no, T1.zone_no
FROM
    T_DETAIL_ITEM  T1
    LEFT OUTER JOIN T_DETAIL_ITEM T2 ON T2.pkg_no = T1.pkg_no AND T2.zone_no = 0
WHERE
    NOT T2.pkg_no IS NULL


问:
How can I avoid duplicated functions using MVC?
I'm building an application using ASP.NET Core, and I would like to avoid duplicated code, in the following situation. I'm using usermanager to get all users with a specific role, but I'm using the exact same function for three diferent controllers because I don't know how to reuse the function.

I've read about action filters, but I don't know how to adapt my code in this situation.

Example first controller:

```<code>public class FirstController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public async Task<IActionResult> Index()
    {
        Dictionary<string, string> emails = await GetAdminEmails();
        ViewBag.Emails = emails;
    }

    private async Task<Dictionary<string, string>> GetAdminEmails()
    {
        Dictionary<string, string> emails = new Dictionary<string, string>();

        foreach (var email in _userManager.Users.ToList())
        {
            var user = await _userManager.FindByEmailAsync(email.Email);
            var roles = await _userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                if (role == "Admin")
                {
                    emails.Add(email.Email, email.Id);
                }
            }
        }

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

Second controller

```<code>public class SecondController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public async Task<IActionResult> Index()
    {
        Dictionary<string, string> emails = await GetAdminEmails();
        ViewBag.Emails = emails;
    }

    private async Task<Dictionary<string, string>> GetAdminEmails()
    {
        Dictionary<string, string> emails = new Dictionary<string, string>();

        foreach (var email in _userManager.Users.ToList())
        {
            var user = await _userManager.FindByEmailAsync(email.Email);
            var roles = await _userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                if (role == "Admin")
                {
                    emails.Add(email.Email, email.Id);
                }
            }
        }

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

Third controller

```<code>public class ThirdController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public async Task<IActionResult> Index()
    {
        Dictionary<string, string> emails = await GetAdminEmails();
        ViewBag.Emails = emails;
    }

    private async Task<Dictionary<string, string>> GetAdminEmails()
    {
        Dictionary<string, string> emails = new Dictionary<string, string>();

        foreach (var email in _userManager.Users.ToList())
        {
            var user = await _userManager.FindByEmailAsync(email.Email);
            var roles = await _userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                if (role == "Admin")
                {
                    emails.Add(email.Email, email.Id);
                }
            }
        }

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

答:
You can create a custom base controller that has the common functionality (your GetAdminEmails method):

```<code>public class BaseController : Controller
</code>```

and move the common method there.

Then, on each of the three controllers above change

```<code>public class xxxController : Controller
</code>```

to

```<code>public class xxxController : BaseController
</code>```

Body:
I'm building an application using ASP.NET Core, and I would like to avoid duplicated code, in the following situation. I'm using usermanager to get all users with a specific role, but I'm using the exact same function for three diferent controllers because I don't know how to reuse the function.

I've read about action filters, but I don't know how to adapt my code in this situation.

Example first controller:

public class FirstController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public async Task<IActionResult> Index()
    {
        Dictionary<string, string> emails = await GetAdminEmails();
        ViewBag.Emails = emails;
    }

    private async Task<Dictionary<string, string>> GetAdminEmails()
    {
        Dictionary<string, string> emails = new Dictionary<string, string>();

        foreach (var email in _userManager.Users.ToList())
        {
            var user = await _userManager.FindByEmailAsync(email.Email);
            var roles = await _userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                if (role == "Admin")
                {
                    emails.Add(email.Email, email.Id);
                }
            }
        }

        return emails;
    }
}

Second controller

public class SecondController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public async Task<IActionResult> Index()
    {
        Dictionary<string, string> emails = await GetAdminEmails();
        ViewBag.Emails = emails;
    }

    private async Task<Dictionary<string, string>> GetAdminEmails()
    {
        Dictionary<string, string> emails = new Dictionary<string, string>();

        foreach (var email in _userManager.Users.ToList())
        {
            var user = await _userManager.FindByEmailAsync(email.Email);
            var roles = await _userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                if (role == "Admin")
                {
                    emails.Add(email.Email, email.Id);
                }
            }
        }

        return emails;
    }
}

Third controller

public class ThirdController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public async Task<IActionResult> Index()
    {
        Dictionary<string, string> emails = await GetAdminEmails();
        ViewBag.Emails = emails;
    }

    private async Task<Dictionary<string, string>> GetAdminEmails()
    {
        Dictionary<string, string> emails = new Dictionary<string, string>();

        foreach (var email in _userManager.Users.ToList())
        {
            var user = await _userManager.FindByEmailAsync(email.Email);
            var roles = await _userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                if (role == "Admin")
                {
                    emails.Add(email.Email, email.Id);
                }
            }
        }

        return emails;
    }
}

Body:
You can create a custom base controller that has the common functionality (your GetAdminEmails method):

public class BaseController : Controller

and move the common method there.

Then, on each of the three controllers above change

public class xxxController : Controller

to

public class xxxController : BaseController


问:
Does RabbitMQ support hash partition like Kafka?
I have a RabbitMQ with multiple consumers subscribed on a single queue. And I want the messages with same hash key can be consumed by the same consumer for each time. I know the default behavior for RabbitMQ is loop through all consumers and dispatch the message 1 by 1.

Does it have the same ability like Kafka partition?

Thanks

答:
Well not exactly but a very close one .

You need to use RabbitMQ Consistent Hash Exchange Type which is available by adding the rabbitmq-consistent-hash-exchange plugin. It adds a consistent-hash exchange type to RabbitMQ. This exchange type uses consistent hashing  to distribute messages between the bound queues. It is recommended to get a basic understanding of the concept before evaluating this plugin and its alternatives.


问:
Batch Testing in LUIS incorrect prediction for List enities
I am trying to run batch tests for my LUIS app. The entities labelled as List Entity are displayed as False Positive inside the chart.

I have already gone through the below question and I believe this issue has already been resolved. But I still have issues with the list entity type. I have not included list entities inside the batch file.

LUIS Batch Testing for Entity is Not Working

In the documentation, it is stated that:
"Only the machine-learned entities are used: simple, hierarchical (parent-only), and composite entities. Do not add non-machine-learned entities because they are always found either through regular expressions, or explicit text matches"

I have used the following syntax inside batch test file (no labelled entites):

```<code>         [
          {
            "text": "example utterance goes here",
            "intent": "intent name goes here",
            "entities": []
          }
         ]
</code>```

Do I have to exclude all the utterances containing the list entity while creating the batch file ? If so how can I test the Intent prediction for those utterances using batch tests?

答:
Do I have to exclude all the utterances containing the list entity while creating the batch file ?

Correct.

If so how can I test the Intent prediction for those utterances using batch tests?

You'll need to test them manually.

Per the docs,

Entity types allowed: only machined-learned entities of simple and composite. Batch testing is only useful for machined-learned intents and entities.

The reason for this is that batch testing is meant to test scenarios where you've made changes to your app and you want to ensure it still works. Detection of non-machine-learned entities is never going to change, so they don't really need to be batch-tested (other than maybe the first time).

That being said, I understand you'll likely still want the ability to do this. I recommend opening a feature request on the LUIS UserVoice

Body:
I am trying to run batch tests for my LUIS app. The entities labelled as List Entity are displayed as False Positive inside the chart.

I have already gone through the below question and I believe this issue has already been resolved. But I still have issues with the list entity type. I have not included list entities inside the batch file.

LUIS Batch Testing for Entity is Not Working

In the documentation, it is stated that:
"Only the machine-learned entities are used: simple, hierarchical (parent-only), and composite entities. Do not add non-machine-learned entities because they are always found either through regular expressions, or explicit text matches"

I have used the following syntax inside batch test file (no labelled entites):

         [
          {
            "text": "example utterance goes here",
            "intent": "intent name goes here",
            "entities": []
          }
         ]

Do I have to exclude all the utterances containing the list entity while creating the batch file ? If so how can I test the Intent prediction for those utterances using batch tests?


答:
%s expects a null terminated string of chars. You print arrays by iterating through them:

```<code>for (i = 0; i < 3; i++)
{
    for (i2 = 0; i2 < 4; i2++)
    {
        printf("%d ", number[i][i2]);
    }

    putchar('\n');
}
</code>```

It helps to do this in row-major order if performance matters.

Title: How can I print multidimensional arrays in C?

Body:
#include <stdio.h>

int main(){

  int number[3][4] = {
    {10,20,30,40},
    {15,25,35,45},
    {47,48,49,50},
  };
      printf("%s",number[]);
  return 0;
}

Ok, here's my code and what I wonder is how can I print out those arrays that I created. Do I have to use for loop or is there another way?

P.S: Im a newbie.

Body:
%s expects a null terminated string of chars. You print arrays by iterating through them:

for (i = 0; i < 3; i++)
{
    for (i2 = 0; i2 < 4; i2++)
    {
        printf("%d ", number[i][i2]);
    }

    putchar('\n');
}

It helps to do this in row-major order if performance matters.


问:
Don't know why I am getting Null Pointer exception
Here I am retrieving data from an API everything works fine but
1. Suces is showing on Toast then App crashes

```<code>public class MainActivity extends AppCompatActivity {

    public TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textview);
        MyWebService myWebService = MyWebService.retrofit.create(MyWebService.class);
        Call<Train>  call = myWebService.getTrain();
        call.enqueue(new Callback<Train>() {
            @Override
            public void onResponse(Call<Train> call, Response<Train> response) {
                if(response.isSuccessful() && response.body()!=null)
                {

                    Train train = response.body();
                    Toast.makeText(getApplicationContext(),"Sucess",Toast.LENGTH_LONG).show();
                    textView.setText(train.getTrain2().getName());
                }
            }

            @Override
            public void onFailure(Call<Train> call, Throwable t) {
                Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();

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

I am getting error at this line

textView.setText(train.getTrain2().getName());

But I initialize the textview and also checking response!=null

Error is

```<code>02-14 22:41:40.003 1557-1557/? E/Zygote: v2
02-14 22:41:40.003 1557-1557/? E/Zygote: accessInfo : 0
02-14 22:41:41.963 1557-1557/com.piyushjaiswal121.rail E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.piyushjaiswal121.rail, PID: 1557
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.piyushjaiswal121.rail.Train2.getName()' on a null object reference
        at com.piyushjaiswal121.rail.MainActivity$1.onResponse(MainActivity.java:36)
        at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:7325)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
</code>```

答:
The reason why you're getting a Null Pointer Exception is because apparently
train2 is null.

An approach to avoid that exception could be just check if train2 is null or not

```<code>if(train.getTrain2()!=null)
   textView.setText(train.getTrain2().getName());
</code>```

Body:
Here I am retrieving data from an API everything works fine but
1. Suces is showing on Toast then App crashes

public class MainActivity extends AppCompatActivity {

    public TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textview);
        MyWebService myWebService = MyWebService.retrofit.create(MyWebService.class);
        Call<Train>  call = myWebService.getTrain();
        call.enqueue(new Callback<Train>() {
            @Override
            public void onResponse(Call<Train> call, Response<Train> response) {
                if(response.isSuccessful() && response.body()!=null)
                {

                    Train train = response.body();
                    Toast.makeText(getApplicationContext(),"Sucess",Toast.LENGTH_LONG).show();
                    textView.setText(train.getTrain2().getName());
                }
            }

            @Override
            public void onFailure(Call<Train> call, Throwable t) {
                Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();

            }
        });
    }
}

I am getting error at this line

textView.setText(train.getTrain2().getName());

But I initialize the textview and also checking response!=null

Error is

02-14 22:41:40.003 1557-1557/? E/Zygote: v2
02-14 22:41:40.003 1557-1557/? E/Zygote: accessInfo : 0
02-14 22:41:41.963 1557-1557/com.piyushjaiswal121.rail E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.piyushjaiswal121.rail, PID: 1557
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.piyushjaiswal121.rail.Train2.getName()' on a null object reference
        at com.piyushjaiswal121.rail.MainActivity$1.onResponse(MainActivity.java:36)
        at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:7325)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Body:
The reason why you're getting a Null Pointer Exception is because apparently
train2 is null.

An approach to avoid that exception could be just check if train2 is null or not

if(train.getTrain2()!=null)
   textView.setText(train.getTrain2().getName());


问:
Can't use setTimeout to undo boolean
In my Javascript code I am trying to set up this code

```<code>    if(this.boolean == true) {
        setTimeout(function(){ this.boolean = false; }, 2000);

    }
</code>```

But for some reason it won't work, the boolean just remains true. How can I fix this/what can I do instead?
The setTimeout works with other lines of code but weirdly not this one.

答:
The scope of "this" is changed in your function inside the setTimeout.

You could use the arrow function like other commenters have said.

Or, you can set a var as this, and then use that var in the functions inside the SetTimeout.

```<code>var coolThis = this;
if(coolThis.boolean == true) {
    setTimeout(function(){ coolThis.boolean = false; }, 2000);
}
</code>```

Title: Can't use setTimeout to undo boolean

Body:
In my Javascript code I am trying to set up this code

    if(this.boolean == true) {
        setTimeout(function(){ this.boolean = false; }, 2000);

    }

But for some reason it won't work, the boolean just remains true. How can I fix this/what can I do instead?
The setTimeout works with other lines of code but weirdly not this one.

Body:
The scope of "this" is changed in your function inside the setTimeout.

You could use the arrow function like other commenters have said.

Or, you can set a var as this, and then use that var in the functions inside the SetTimeout.

var coolThis = this;
if(coolThis.boolean == true) {
    setTimeout(function(){ coolThis.boolean = false; }, 2000);
}