问:
How to display activity indicator in center of UIAlertController?
I currently have a UIAlertController being displayed on the screen. The view of the alert should only display 2 elements, a title and a UIActivityIndicatorView in the center of the alert. Below is the function that displays the alert and its elements.

```<code>func displaySignUpPendingAlert() -> UIAlertController {
        //Create the UIAlertController
        let pending = UIAlertController(title: "Creating New User", message: nil, preferredStyle: .Alert)
        //Create the activity indicator to display in it.
        let indicator = UIActivityIndicatorView(frame: CGRectMake(pending.view.frame.width / 2.0, pending.view.frame.height / 2.0, 20.0, 20.0))
        indicator.center = CGPointMake(pending.view.frame.width / 2.0, pending.view.frame.height / 2.0)
        //Add the activity indicator to the alert's view
        pending.view.addSubview(indicator)
        //Start animating
        indicator.startAnimating()

        self.presentViewController(pending, animated: true, completion: nil)
        return pending
    }
</code>```

However, the activity indicator doesn't display in the center of the view, in fact it displays in the bottom right of the screen, far off of the view. What is the reason for this?

EDIT: I understand that I can hardcode numbers for the indicator's position, but I want the alert to work on multiple devices with multiple screen sizes and orientations.

答:
Swift 5.0 solution

```<code>let alert = UIAlertController(title: "Sender ...", message: nil, preferredStyle: .alert)
let activityIndicator = UIActivityIndicatorView(style: .gray)
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
activityIndicator.isUserInteractionEnabled = false
activityIndicator.startAnimating()

alert.view.addSubview(activityIndicator)
alert.view.heightAnchor.constraint(equalToConstant: 95).isActive = true

activityIndicator.centerXAnchor.constraint(equalTo: alert.view.centerXAnchor, constant: 0).isActive = true
activityIndicator.bottomAnchor.constraint(equalTo: alert.view.bottomAnchor, constant: -20).isActive = true

present(alert, animated: true)
</code>```

Body:
I currently have a UIAlertController being displayed on the screen. The view of the alert should only display 2 elements, a title and a UIActivityIndicatorView in the center of the alert. Below is the function that displays the alert and its elements.

func displaySignUpPendingAlert() -> UIAlertController {
        //Create the UIAlertController
        let pending = UIAlertController(title: "Creating New User", message: nil, preferredStyle: .Alert)
        //Create the activity indicator to display in it.
        let indicator = UIActivityIndicatorView(frame: CGRectMake(pending.view.frame.width / 2.0, pending.view.frame.height / 2.0, 20.0, 20.0))
        indicator.center = CGPointMake(pending.view.frame.width / 2.0, pending.view.frame.height / 2.0)
        //Add the activity indicator to the alert's view
        pending.view.addSubview(indicator)
        //Start animating
        indicator.startAnimating()

        self.presentViewController(pending, animated: true, completion: nil)
        return pending
    }

However, the activity indicator doesn't display in the center of the view, in fact it displays in the bottom right of the screen, far off of the view. What is the reason for this?

EDIT: I understand that I can hardcode numbers for the indicator's position, but I want the alert to work on multiple devices with multiple screen sizes and orientations.

Body:
Swift 5.0 solution

let alert = UIAlertController(title: "Sender ...", message: nil, preferredStyle: .alert)
let activityIndicator = UIActivityIndicatorView(style: .gray)
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
activityIndicator.isUserInteractionEnabled = false
activityIndicator.startAnimating()

alert.view.addSubview(activityIndicator)
alert.view.heightAnchor.constraint(equalToConstant: 95).isActive = true

activityIndicator.centerXAnchor.constraint(equalTo: alert.view.centerXAnchor, constant: 0).isActive = true
activityIndicator.bottomAnchor.constraint(equalTo: alert.view.bottomAnchor, constant: -20).isActive = true

present(alert, animated: true)


来源: stackexchange

问:
IBM Informix NodeJS Setup Issues - The INFORMIXSERVER value is not listed in the sqlhosts file or the Registry
I am attempting to connect Informix with NodeJS on MacOS but coming up against issues configuring the environment correctly.

In my ~/.bash_profile I have the following:

```<code>export INFORMIXDIR=/Applications/IBM/informix
export PATH=$INFORMIXDIR/bin:$PATH
export CSDK_HOME=/Applications/IBM/informix
export INFORMIXSQLHOSTS=/Users/username/Documents/sqlhosts

export LD_LIBRARY_PATH=$INFORMIXDIR/lib:$INFORMIXDIR/lib/esql:$INFORMIXDIR/lib/cli
</code>```

As you can see, I have specified the INFORMIXSQLHOSTS variable to a local file rather than the default $INFORMIXDIR/etc/sqlhosts as I could not make sense of the multiple example files in that directory.

My local file for sqlhosts is as such:

```<code>#INFORMIXSERVER
informix_server     onsoctcp    localhost   my_alias
</code>```

I am then running my node file index.js:

```<code>const opts = {
    database: 'db_name@informix_server',
    username: 'user',
    password: 'password'
};
const informix = require('informix')(opts)

informix.query('select name from table')
    .then(cursor => {
        return cursor.fetchAll({close: true});
    })
    .then(results => {
        console.log('results:', results);
    })
    .catch(err => {
        console.log(err);
    });
</code>```

When I run this with node index.js I get the error:

Error: [-25596] The INFORMIXSERVER value is not listed in the sqlhosts file or the Registry.

Can anybody help me troubleshoot this?

答:
It turns out that you are required to have a "default" value for the INFORMIXSERVER in the environmental configs. It can be anything you like. It only comes into play if you are not specifying the server name when attempting to connect in the code. Usually we would write db_name@server_name, however if we omit the @server_name it will connect to the default defined within the environmental variables.

For example:
In the environmental variables I define:

```<code>export INFORMIXSERVER=server_name
</code>```

Then in the code I would connect to another server called my_server as such:

```<code>const opts = {
  database: 'my_db@my_server', // I specify the db name and the server name
  username: 'user',
  password: 'pass'
}

const infx = require('Informix')(opts);
</code>```

Whereas, if I were to omit the server name:

```<code>const opts = {
  database: 'my_db',
  ...
}
</code>```

The code would interpret this as really being:

```<code>const opts = {
  database: 'my_db@server_name', // server name defined in INFORMIXSERVER
  ...
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am attempting to connect Informix with NodeJS on MacOS but coming up against issues configuring the environment correctly.

In my ~/.bash_profile I have the following:

export INFORMIXDIR=/Applications/IBM/informix
export PATH=$INFORMIXDIR/bin:$PATH
export CSDK_HOME=/Applications/IBM/informix
export INFORMIXSQLHOSTS=/Users/username/Documents/sqlhosts

export LD_LIBRARY_PATH=$INFORMIXDIR/lib:$INFORMIXDIR/lib/esql:$INFORMIXDIR/lib/cli

As you can see, I have specified the INFORMIXSQLHOSTS variable to a local file rather than the default $INFORMIXDIR/etc/sqlhosts as I could not make sense of the multiple example files in that directory.

My local file for sqlhosts is as such:

#INFORMIXSERVER
informix_server     onsoctcp    localhost   my_alias

I am then running my node file index.js:

const opts = {
    database: 'db_name@informix_server',
    username: 'user',
    password: 'password'
};
const informix = require('informix')(opts)

informix.query('select name from table')
    .then(cursor => {
        return cursor.fetchAll({close: true});
    })
    .then(results => {
        console.log('results:', results);
    })
    .catch(err => {
        console.log(err);
    });

When I run this with node index.js I get the error:

Error: [-25596] The INFORMIXSERVER value is not listed in the sqlhosts file or the Registry.

Can anybody help me troubleshoot this?

Body:
It turns out that you are required to have a "default" value for the INFORMIXSERVER in the environmental configs. It can be anything you like. It only comes into play if you are not specifying the server name when attempting to connect in the code. Usually we would write db_name@server_name, however if we omit the @server_name it will connect to the default defined within the environmental variables.

For example:
In the environmental variables I define:

export INFORMIXSERVER=server_name

Then in the code I would connect to another server called my_server as such:

const opts = {
  database: 'my_db@my_server', // I specify the db name and the server name
  username: 'user',
  password: 'pass'
}

const infx = require('Informix')(opts);

Whereas, if I were to omit the server name:

const opts = {
  database: 'my_db',
  ...
}

The code would interpret this as really being:

const opts = {
  database: 'my_db@server_name', // server name defined in INFORMIXSERVER
  ...
}


问:
What is "IIS 7 Recommended Configuration" in Web Platform Installer 3.0?
Just installed the new IIS Express today and saw that the Web Platform Installer also has the option to install "IIS 7 Recommended Configuration".
But I couldn't actually figure out anywhere what it does?

Anyone using it?

答:
This seems to be from the Chris Sfanos post here: http://forums.iis.net/t/1174703.aspx

But it doesn't really say what it improves over what IIS 7 already has.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
how to repeat characters in a string
I'm trying to link two tables, one has an 'EntityRef' that's made of four alpha characters and a sequential number...

```<code>EntityRef
=========
SWIT1
LIVE32
KIRB48
MEHM38
BRAD192
</code>```

The table that I'm trying to link to stores the reference in a 15 character field where the 4 alphas are at the start and the numbers are at the end but with zeros in between to make up the 15 characters...

```<code>EntityRef
=========
SWIT00000000001
LIVE00000000032
</code>```

So, to get theses to link, my options are to either remove the zeros on one field or add the zeros on the other.

I've gone for the later as it seems to be a simpler approach and eliminates the risk of getting into problems if the numeric element contains a zero.

So, the alpha is always 4 characters at the beginning and the number is the remainder and 15 minus the LEN() of the EntityRef is the number of zeros that I need to insert...

```<code>left(entityref,4) as 'Alpha',
right(entityref,len(EntityRef)-4) as 'Numeric',
15-len(EntityRef) as 'No.of Zeros'

Alpha   Numeric No.of Zeros
=====   ======= ===========
SWIT    1       10
LIVE    32      9
KIRB    48      9
MEHM    38      9
MALL    36      9
</code>```

So, I need to concatenate the three elements but I don't know how to create the string of zeros to the specified length...how do I do that??

```<code>Concat(Alpha, '0'*[No. of Zeros], Numeric)
</code>```

What is the correct way to repeat a character a specified number of times?

答:
You can use string manipulation.  In this case:

LEFT() to get the alpha portion.

REPLICATE() to get the zeros.

STUFF() to get the number.

The query:

```<code>select left(val, 4) + replicate('0', 15 - len(val)) + stuff(val, 1, 4, '')
from (values ('SWIT1'), ('ABC12345')) v(val)
</code>```

Title: how to repeat characters in a string

Body:
I'm trying to link two tables, one has an 'EntityRef' that's made of four alpha characters and a sequential number...

EntityRef
=========
SWIT1
LIVE32
KIRB48
MEHM38
BRAD192

The table that I'm trying to link to stores the reference in a 15 character field where the 4 alphas are at the start and the numbers are at the end but with zeros in between to make up the 15 characters...

EntityRef
=========
SWIT00000000001
LIVE00000000032

So, to get theses to link, my options are to either remove the zeros on one field or add the zeros on the other.

I've gone for the later as it seems to be a simpler approach and eliminates the risk of getting into problems if the numeric element contains a zero.

So, the alpha is always 4 characters at the beginning and the number is the remainder and 15 minus the LEN() of the EntityRef is the number of zeros that I need to insert...

left(entityref,4) as 'Alpha',
right(entityref,len(EntityRef)-4) as 'Numeric',
15-len(EntityRef) as 'No.of Zeros'

Alpha   Numeric No.of Zeros
=====   ======= ===========
SWIT    1       10
LIVE    32      9
KIRB    48      9
MEHM    38      9
MALL    36      9

So, I need to concatenate the three elements but I don't know how to create the string of zeros to the specified length...how do I do that??

Concat(Alpha, '0'*[No. of Zeros], Numeric)

What is the correct way to repeat a character a specified number of times?

Body:
You can use string manipulation.  In this case:

LEFT() to get the alpha portion.

REPLICATE() to get the zeros.

STUFF() to get the number.

The query:

select left(val, 4) + replicate('0', 15 - len(val)) + stuff(val, 1, 4, '')
from (values ('SWIT1'), ('ABC12345')) v(val)


问:
How to populate dynamically added input fields with Json object
I have a this table of input fields which I can add rows dynamically with help of KnockoutJS

```<code>     <table id="sTypeTable" class="table table-bordered" hidden="hidden">
         <tr>
             <th> Name </th>
             <th> Value </th>
             <th> <a class="btn btn-primary btn-sm"  onclick="addReqField(0);"><i class="fa fa-plus"></i></a></th>
         </tr>
<!-- ko foreach: {data: requestFields, as: 'reqField'} -->
        <tr id="sRow">
           <td>
              <input id="sName" data-bind="value: reqField[0]" onblur="createJSON()"/>
           </td>
           <td>
              <input id="sValue" data-bind="value: reqField[0]" onblur="createJSON()"/>
           </td>
           <td>
              <a class="btn btn-warning  btn-sm" data-bind="click: removeResField2" ><i class="glyphicon glyphicon-remove"></i></a>
          </td>
       </tr>
<!-- /ko -->
 </table>
  <div class="col-md-11 ">
    <textarea style="font-size: larger; min-height: 200px" class="form-control" id="requestData" oninput="storeValueOfTextArea()"></textarea>
  </div>
</code>```

From this inputs I'm generating
following Json object on textarea (id="requestData")

```<code>[
  {
    "users": [
      {
        "name": "John",
        "value": "12"
      },
      {
        "name": "Sarah",
        "value": "13"
      },
      {
        "name": "Tom",
        "value": "14"
      }
    ]
  }
]
</code>```

It works well, but now I need populate these input fields from Json object,
When object entered to textarea.
I have tried following way

```<code><script th:inline="javascript">

 function storeValueOfTextArea() {
      var lines = $('#requestData').val();
      var texts = JSON.parse(lines);

  for (var i=0; i!== texts[0].users.length;i++){
      addReqField();  // method for adding new row of input fields

      let  v = texts[0].users[i];
      $("tr[id=sRow]").each(function() {
          $("#sName").val(v.name);
          $("#sValue").val(v.value);
      });
  }
 </script>
</code>```

but in result  only first input field gets the last object

```<code>{
   "name": "Tom",
   "value": "14"
 }
</code>```

others stays empty

答:
I think the problem is that you're giving each created new row the same ID of sRow.

So inside your loop

```<code>  $("tr[id=sRow]").each(function() {
      $("#sName").val(v.name);
      $("#sValue").val(v.value);
  });
</code>```

in the last iteration this will fill all sRow elements with the objects last values of Tom and 14.
Try giving your rows an unique id like sRow + a counter from 0 onwards sRow0 sRow1...

Body:
I have a this table of input fields which I can add rows dynamically with help of KnockoutJS

              Name
              Value

              <input id="sName" data-bind="value: reqField[0]" onblur="createJSON()"/>

              <input id="sValue" data-bind="value: reqField[0]" onblur="createJSON()"/>

    <textarea style="font-size: larger; min-height: 200px" class="form-control" id="requestData" oninput="storeValueOfTextArea()"></textarea>

From this inputs I'm generating
following Json object on textarea (id="requestData")

[
  {
    "users": [
      {
        "name": "John",
        "value": "12"
      },
      {
        "name": "Sarah",
        "value": "13"
      },
      {
        "name": "Tom",
        "value": "14"
      }
    ]
  }
]

It works well, but now I need populate these input fields from Json object,
When object entered to textarea.
I have tried following way

but in result  only first input field gets the last object

{
   "name": "Tom",
   "value": "14"
 }

others stays empty

Body:
I think the problem is that you're giving each created new row the same ID of sRow.

So inside your loop

  $("tr[id=sRow]").each(function() {
      $("#sName").val(v.name);
      $("#sValue").val(v.value);
  });

in the last iteration this will fill all sRow elements with the objects last values of Tom and 14.
Try giving your rows an unique id like sRow + a counter from 0 onwards sRow0 sRow1...


问:
Loop over Regex to extract columns by multiple name-value combination
I have a dataframe with column names like v1,...,v99, tm1,...tm99 and so on. Not for every number exists a column though (mybe v42 is missing). The letters can vary from a to zzz. I have written a method to filter my columns according to a letter combination (like 'v' or 'tm') followed by a figure. This looks like

```<code>def create_required_dataset(df, var_filter):
    persDf = df.filter(regex=('^' + var_filter + r'[0-9]+$'))
    return persDf
</code>```

This works create_required_dataset('v') and I receive a dataframe with all columns starting with v followed by a number.

and works fine. But now I have to deliver not only one letter combination ('tm', 'zzz') but as many  as the user puts in.

So the query should look like:

```<code>create_required_dataset('v', 'tm', 'zz')
</code>```

What I have tried is to work with *args so I have rewritten my method to

```<code>def create_required_dataset(df, *args):
    persDf = df.filter(regex=('^' + args + r'[0-9]+$'))
    return persD
</code>```

But this does not work, even if I transform the tuple into a list. Obviously since the regex only takes one string. I thought about a Lambda-Apply Method that applies the regex function but could not get this to work as well. I just have no idea how to accomplish this now and need some help. I

答:
You may use an alternation based pattern, just wrap the alternatives with a non-capturing group

```<code>persDf = df.filter(regex=('^(?:{})[0-9]+$'.format('|'.join(args))))
</code>```

This will create a regex like ^(?:v|tm|zz)[0-9]+$ that means:

^ - start of string

(?:v|tm|zz) - any of the alternatives: v, ortm, orzz

[0-9]+ - 1+ digits

$ - end of string.

See the regex demo and its graph:

Body:
I have a dataframe with column names like v1,...,v99, tm1,...tm99 and so on. Not for every number exists a column though (mybe v42 is missing). The letters can vary from a to zzz. I have written a method to filter my columns according to a letter combination (like 'v' or 'tm') followed by a figure. This looks like

def create_required_dataset(df, var_filter):
    persDf = df.filter(regex=('^' + var_filter + r'[0-9]+$'))
    return persDf

This works create_required_dataset('v') and I receive a dataframe with all columns starting with v followed by a number.

and works fine. But now I have to deliver not only one letter combination ('tm', 'zzz') but as many  as the user puts in.

So the query should look like:

create_required_dataset('v', 'tm', 'zz')

What I have tried is to work with *args so I have rewritten my method to

def create_required_dataset(df, *args):
    persDf = df.filter(regex=('^' + args + r'[0-9]+$'))
    return persD

But this does not work, even if I transform the tuple into a list. Obviously since the regex only takes one string. I thought about a Lambda-Apply Method that applies the regex function but could not get this to work as well. I just have no idea how to accomplish this now and need some help. I

Body:
You may use an alternation based pattern, just wrap the alternatives with a non-capturing group

persDf = df.filter(regex=('^(?:{})[0-9]+$'.format('|'.join(args))))

This will create a regex like ^(?:v|tm|zz)[0-9]+$ that means:

^ - start of string

(?:v|tm|zz) - any of the alternatives: v, ortm, orzz

[0-9]+ - 1+ digits

$ - end of string.

See the regex demo and its graph:


问:
How can I estimate mu and sigma parameters for logNormal distribution with the data of quantiles in Python
I have the data:

```<code>[11043.000000   14565.625000    15901.000000    18104.0 22458.000000    26990.000000    31825.600000    38803.500000    42934.285714    47751.111111    64975.333333]
</code>```

for the quantiles

```<code>[0.1,0.2,0.25,0.3,0.4,0.5,0.6,0.7,0.75,0.8,0.9]
</code>```

and I need obtain estimated values for mu and sigma of a logNormal distribution using python.

Any idea?

答:
You need first fit function to you data, then extract parameters:

```<code>from scipy import stats
import numpy as np

y_data = [11043, 14565, 15901, 18104, 22458, 26990, 31825.6, 38803.5, 42934.285714, 47751.111111, 64975.333333]

# fit data
sigma, loc, scale = stats.lognorm.fit(y_data, floc=0)

# get mu
mu = np.log(scale)
</code>```

Output:

```<code>mu = 10.186710603314205
sigma =  0.5326712155979726
</code>```

Body:
I have the data:

[11043.000000   14565.625000    15901.000000    18104.0 22458.000000    26990.000000    31825.600000    38803.500000    42934.285714    47751.111111    64975.333333]

for the quantiles

[0.1,0.2,0.25,0.3,0.4,0.5,0.6,0.7,0.75,0.8,0.9]

and I need obtain estimated values for mu and sigma of a logNormal distribution using python.

Any idea?

Body:
You need first fit function to you data, then extract parameters:

from scipy import stats
import numpy as np

y_data = [11043, 14565, 15901, 18104, 22458, 26990, 31825.6, 38803.5, 42934.285714, 47751.111111, 64975.333333]

# fit data
sigma, loc, scale = stats.lognorm.fit(y_data, floc=0)

# get mu
mu = np.log(scale)

Output:

mu = 10.186710603314205
sigma =  0.5326712155979726


问:
Project ERROR: Cannot run compiler 'g++'. Maybe you forgot to setup the environment whithin gitlab env
I've a strange phenomenom happening that I don't know how to investigate.
I hope someone already encountered this an can provide tips

I'm using gitlab CI to build some Qt based projects.
gitlab runner calls a script named build.sh that works just fine when I run it manually as "me" in my env dev.
However runner raises an error stating "Project ERROR: Cannot run compiler 'g++'. Maybe you forgot to setup the environment".
So I made sure g++ was available (g++ -version is OK) and in g++ is in PATH but pbm is still there.

here is part of the script where the problem resides and the investigation I performed

```<code>echo ">>>>>> now generating makefiles for  ${PROJECT_FILE} <<<<<<"
export QTDIR=/usr/lib64/qt5
echo $QTDIR
echo QMAKESPEC is
qmake-qt5 -query QMAKE_SPEC
echo gcc version is
gcc --version
g++ --version

echo $PWD
whoami
$cmd_qMake -v
$cmd_qMake -makefile -o qMakefile ../src/${PROJECT_FILE}

echo PATH is $PATH
echo QMAKESPEC is
qmake-qt5 -query QMAKE_SPEC
echo gcc version is
gcc --version
g++ --version

</code>```

and here is the output (sorry; this is in debug mode)

```<code>>>>>>> now generating makefiles for  Communication.pro <<<<<<
+ export QTDIR=/usr/lib64/qt5
+ QTDIR=/usr/lib64/qt5
+ echo /usr/lib64/qt5
/usr/lib64/qt5
+ echo QMAKESPEC is
QMAKESPEC is
+ qmake-qt5 -query QMAKE_SPEC
linux-g++
+ echo gcc version is
gcc version is
+ gcc --version
gcc (GCC) 7.3.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

+ g++ --version
g++ (GCC) 7.3.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

+ echo /root/builds/3188cf72/0/EGNOS_V3/AIV-P/AIV-P/Shared/Communication/.buildchain
/root/builds/3188cf72/0/EGNOS_V3/AIV-P/AIV-P/Shared/Communication/.buildchain
+ whoami
root
+ qmake-qt5 -v
QMake version 3.1
Using Qt version 5.9.2 in /usr/lib64
+ qmake-qt5 -makefile -o qMakefile ../src/Communication.pro
Project ERROR: Cannot run compiler 'g++'. Maybe you forgot to setup the environment?
+ echo PATH is /opt/gcc-7.3.0/bin:/usr/bin:/usr/sbin:/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/sbin:/usr/bin:/bin
PATH is /opt/gcc-7.3.0/bin:/usr/bin:/usr/sbin:/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/sbin:/usr/bin:/bin
+ echo QMAKESPEC is
QMAKESPEC is
+ qmake-qt5 -query QMAKE_SPEC
linux-g++
+ echo gcc version is
gcc version is
+ gcc --version
gcc (GCC) 7.3.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

+ g++ --version
g++ (GCC) 7.3.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

+ for target in '"${TARGETS[@]}"'
</code>```

As you can see, g++ seems available un runner's root PATH
So why is qMake failing?

Thanks for your help

Zaluum

答: I had the same error sudo apt install build-essential worked for me.

Body:
I've a strange phenomenom happening that I don't know how to investigate.
I hope someone already encountered this an can provide tips

I'm using gitlab CI to build some Qt based projects.
gitlab runner calls a script named build.sh that works just fine when I run it manually as "me" in my env dev.
However runner raises an error stating "Project ERROR: Cannot run compiler 'g++'. Maybe you forgot to setup the environment".
So I made sure g++ was available (g++ -version is OK) and in g++ is in PATH but pbm is still there.

here is part of the script where the problem resides and the investigation I performed

echo ">>>>>> now generating makefiles for  ${PROJECT_FILE} <<<<<<"
export QTDIR=/usr/lib64/qt5
echo $QTDIR
echo QMAKESPEC is
qmake-qt5 -query QMAKE_SPEC
echo gcc version is
gcc --version
g++ --version

echo $PWD
whoami
$cmd_qMake -v
$cmd_qMake -makefile -o qMakefile ../src/${PROJECT_FILE}

echo PATH is $PATH
echo QMAKESPEC is
qmake-qt5 -query QMAKE_SPEC
echo gcc version is
gcc --version
g++ --version

and here is the output (sorry; this is in debug mode)

>>>>>> now generating makefiles for  Communication.pro <<<<<<
+ export QTDIR=/usr/lib64/qt5
+ QTDIR=/usr/lib64/qt5
+ echo /usr/lib64/qt5
/usr/lib64/qt5
+ echo QMAKESPEC is
QMAKESPEC is
+ qmake-qt5 -query QMAKE_SPEC
linux-g++
+ echo gcc version is
gcc version is
+ gcc --version
gcc (GCC) 7.3.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

+ g++ --version
g++ (GCC) 7.3.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

+ echo /root/builds/3188cf72/0/EGNOS_V3/AIV-P/AIV-P/Shared/Communication/.buildchain
/root/builds/3188cf72/0/EGNOS_V3/AIV-P/AIV-P/Shared/Communication/.buildchain
+ whoami
root
+ qmake-qt5 -v
QMake version 3.1
Using Qt version 5.9.2 in /usr/lib64
+ qmake-qt5 -makefile -o qMakefile ../src/Communication.pro
Project ERROR: Cannot run compiler 'g++'. Maybe you forgot to setup the environment?
+ echo PATH is /opt/gcc-7.3.0/bin:/usr/bin:/usr/sbin:/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/sbin:/usr/bin:/bin
PATH is /opt/gcc-7.3.0/bin:/usr/bin:/usr/sbin:/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/sbin:/usr/bin:/bin
+ echo QMAKESPEC is
QMAKESPEC is
+ qmake-qt5 -query QMAKE_SPEC
linux-g++
+ echo gcc version is
gcc version is
+ gcc --version
gcc (GCC) 7.3.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

+ g++ --version
g++ (GCC) 7.3.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

+ for target in '"${TARGETS[@]}"'

As you can see, g++ seems available un runner's root PATH
So why is qMake failing?

Thanks for your help

Zaluum


问:
Wrap content with a div after each h2
Anyone can give me some ideas how can i wrap any content with a
 after each
 tag and give it a unique id, done with jquery?

Im trying to do this:

```<code><h2>Test</h2>
 <div id="wrap_1"> // This is the wrapper im trying to add
   <p>Bla bla</p>
   <p>More Bla bla</p>
 </div>
<h2>Another test</h2>
 <div id="wrap_2"> // This is the wrapper im trying to add
   <p>Bla bla</p>
   <p>More Bla bla</p>
 </div>
</code>```

Thanks in advance

答:
Like this:

```<code>$('h2').each(function(index) {
    $(this).nextUntil('h2').wrapAll('<div id="wrap' + index + '"></div>');
});
</code>```

Demo

Title: Wrap content with a div after each h2

Body:
Anyone can give me some ideas how can i wrap any content with a
 after each
 tag and give it a unique id, done with jquery?

Im trying to do this:

Test

 // This is the wrapper im trying to add

Bla bla

More Bla bla

Another test

 // This is the wrapper im trying to add

Bla bla

More Bla bla

Thanks in advance

Body:
Like this:

$('h2').each(function(index) {
    $(this).nextUntil('h2').wrapAll('<div id="wrap' + index + '"></div>');
});

Demo


问:
How do I enable geolocation support in chromedriver?
I need to test a JS geolocation functionality with Selenium and I am using chromedriver to run the test on the latest Chrome.

The problem is now that Chrome prompts me to enable Geolocation during the test and that I don't know how to click that little bar on runtime, so I am desperately looking for a way to start the chromedriver and chrome with some option or trigger to enable this by default. All I could find here was however how I can disable geolocation altogether.

How can I solve this issue?

答:
I took your method but it can not working. I did not find "BaseUrls.Root.AbsoluteUri" in Chrome's Preferences config. And use a script for test</p>

```<code>chromeOptions = webdriver.ChromeOptions()
    chromeOptions.add_argument("proxy-server=http://127.0.0.1:1087")
    prefs = {
        'profile.default_content_setting_values':
            {
                'notifications': 1,
                'geolocation': 1
            },
        'devtools.preferences': {
            'emulation.geolocationOverride': "\"11.111698@-122.222954:\"",
        },
        'profile.content_settings.exceptions.geolocation':{
            'BaseUrls.Root.AbsoluteUri': {
                'last_modified': '13160237885099795',
                'setting': '1'
            }
        },
        'profile.geolocation.default_content_setting': 1

    }

    chromeOptions.add_experimental_option('prefs', prefs)
    chromedriver_path = os.path.join(BASE_PATH, 'utils/driver/chromedriver')
    log_path = os.path.join(BASE_PATH, 'utils/driver/test.log')
    self.driver = webdriver.Chrome(executable_path=chromedriver_path, chrome_options=chromeOptions, service_log_path=log_path)
</code>```

Body:
I took your method but it can not working. I did not find "BaseUrls.Root.AbsoluteUri" in Chrome's Preferences config. And use a script for test

chromeOptions = webdriver.ChromeOptions()
    chromeOptions.add_argument("proxy-server=http://127.0.0.1:1087")
    prefs = {
        'profile.default_content_setting_values':
            {
                'notifications': 1,
                'geolocation': 1
            },
        'devtools.preferences': {
            'emulation.geolocationOverride': "\"11.111698@-122.222954:\"",
        },
        'profile.content_settings.exceptions.geolocation':{
            'BaseUrls.Root.AbsoluteUri': {
                'last_modified': '13160237885099795',
                'setting': '1'
            }
        },
        'profile.geolocation.default_content_setting': 1

    }

    chromeOptions.add_experimental_option('prefs', prefs)
    chromedriver_path = os.path.join(BASE_PATH, 'utils/driver/chromedriver')
    log_path = os.path.join(BASE_PATH, 'utils/driver/test.log')
    self.driver = webdriver.Chrome(executable_path=chromedriver_path, chrome_options=chromeOptions, service_log_path=log_path)


问:
App crashes when attempting to swap activities
This is a basic activity swapping.

The app does not crash if i declare a local button inside the configureActivitySwap() method like this:

```<code>Button voiceBtn = (findViewById(R.id.goToVoice));
</code>```

But I have to declare the button in the global scope instead so I can use the button in other methods, mainly activating and deactivating the button when it should/should not be pressed.

I also noticed that if I remove the finish(); method and replace it with something else the app functions normally, but I have to have the finish(); method one way or another.

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

    private Button voiceBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        voiceBtn = findViewById(R.id.goToVoice);
        setContentView(R.layout.main_layout);

        // some unrelated code

        configureActivitySwap();
    }

    public void configureActivitySwap(){
        // Button voiceBtn = (findViewById(R.id.goToVoice));

        voiceBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

}
</code>```

My runtime error logs:

```<code>    E/AndroidRuntime: FATAL EXCEPTION: main
        Process: tk.gandriks.gaaudiotransform, PID: 23125
        java.lang.RuntimeException: Unable to start activity ComponentInfo{tk.gandriks.gaaudiotransform/tk.gandriks.gaaudiotransform.RecogActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
            at android.app.ActivityThread.-wrap11(Unknown Source:0)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
            at android.os.Handler.dispatchMessage(Handler.java:105)
            at android.os.Looper.loop(Looper.java:164)
            at android.app.ActivityThread.main(ActivityThread.java:6944)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
            at tk.gandriks.gaaudiotransform.RecogActivity.configureActivitySwap(RecogActivity.java:140)
            at tk.gandriks.gaaudiotransform.RecogActivity.onCreate(RecogActivity.java:124)
            at android.app.Activity.performCreate(Activity.java:7183)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
            at android.app.ActivityThread.-wrap11(Unknown Source:0)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
            at android.os.Handler.dispatchMessage(Handler.java:105)
            at android.os.Looper.loop(Looper.java:164)
            at android.app.ActivityThread.main(ActivityThread.java:6944)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
</code>```

答:
Are you setting layout before trying to find view with findViewById?
setContentView(R.layout.main_layout);</p>

Body:
This is a basic activity swapping.

The app does not crash if i declare a local button inside the configureActivitySwap() method like this:

Button voiceBtn = (findViewById(R.id.goToVoice));

But I have to declare the button in the global scope instead so I can use the button in other methods, mainly activating and deactivating the button when it should/should not be pressed.

I also noticed that if I remove the finish(); method and replace it with something else the app functions normally, but I have to have the finish(); method one way or another.

public class RecogActivity extends AppCompatActivity {

    private Button voiceBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        voiceBtn = findViewById(R.id.goToVoice);
        setContentView(R.layout.main_layout);

        // some unrelated code

        configureActivitySwap();
    }

    public void configureActivitySwap(){
        // Button voiceBtn = (findViewById(R.id.goToVoice));

        voiceBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

}

My runtime error logs:

    E/AndroidRuntime: FATAL EXCEPTION: main
        Process: tk.gandriks.gaaudiotransform, PID: 23125
        java.lang.RuntimeException: Unable to start activity ComponentInfo{tk.gandriks.gaaudiotransform/tk.gandriks.gaaudiotransform.RecogActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
            at android.app.ActivityThread.-wrap11(Unknown Source:0)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
            at android.os.Handler.dispatchMessage(Handler.java:105)
            at android.os.Looper.loop(Looper.java:164)
            at android.app.ActivityThread.main(ActivityThread.java:6944)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
            at tk.gandriks.gaaudiotransform.RecogActivity.configureActivitySwap(RecogActivity.java:140)
            at tk.gandriks.gaaudiotransform.RecogActivity.onCreate(RecogActivity.java:124)
            at android.app.Activity.performCreate(Activity.java:7183)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
            at android.app.ActivityThread.-wrap11(Unknown Source:0)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
            at android.os.Handler.dispatchMessage(Handler.java:105)
            at android.os.Looper.loop(Looper.java:164)
            at android.app.ActivityThread.main(ActivityThread.java:6944)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)


问:
How do I store objects in the store (ngrx, ngxs) that have methods
I understand that the Redux pattern requires only plain object to be stored in the Store (this is logical and understandable).
However, in the application I would like to use objects that have some functionality, eg methods such as: "hasParent", "isReadonly", "isValid", which are calculated.

Although, for example, ngrx does not prohibit the storing of such objects, this can lead to many problems

How should I deal with this objects storing problem?
I have two ideas:
A)
-before I save the object to the store, I serialize the object into plain data
-when reading from the store, I map plain data to the object (using the mapper or "manually" (with object constructor and setters))
B)
I resign from using class / objects, I use only plain data and I move the hasParent, isReadonly, isValid methods to the helpers / services.

None of these solutions is free from disadvantages :(. But which solution seems to be better?
Maybe there are other ways to deal with the above problem?

答:
How do I store objects in the store (ngrx, ngxs) that have methods
--> you don't! You store a state in the store. Functions don't belong to a state. (You seem to understand this in the question details, but I want to point this out again)

As for the functions you need:

readonly: in most cases this is a boolean flag on the object. So I
don't know why you want to use it as a function. If read only is
depending e.g. on the user role or other outside factors, move it
into a "utility function" and don't store it with the store state.
You want to keep keep the state as small as possible.

isValid: why would you store invalid data inside the store, which is then potentially used by another component? Personally I would consider data inside the store always as valid, but maybe there is a use case.

hasParent: I see this more as "parentId", from which you can get the actual parent object with a helper method. But without knowing your structure I cannot say.

Before thinking to much about it, ask yourself: Do I really need a store for this. Wouldn't a service be enough. A store is the hottest things right now, but most applications don't need it! Don't use it just because everyone is talking about it!


问:
Merge conflicts stick together after merging
When git-merging two branches which produces two merge conflicts located in non-coherent lines I wonder why the output produced by auto-merge only shows one conflict containing multiple equivalent lines.

The following shows the output after merging:

```<code>Hello
World
that
<<<<<<< HEAD
was
a
goddamn
nasty
file.
=======
will
be
a
goddamn
nasty
merge.
>>>>>>> remote
</code>```

I would expect something like this:

```<code>Hello
World
that
<<<<<<< HEAD
was
=======
will
be
>>>>>>> remote
a
goddamn
nasty
<<<<<<< HEAD
file.
=======
merge.
>>>>>>> remote
</code>```

答:
Ok I found it out myself:
Adding one equal line in both branches produces this:

```<code>Hello
World
that
<<<<<<< HEAD
was
=======
will
be
>>>>>>> remote
a
long
goddamn
nasty
<<<<<<< HEAD
file.
=======
merge.
>>>>>>> remote
</code>```

So I assume all conflicts are bound together if there is not at least a space of 4 un-conflicting lines between a conflict pair.

Body:
When git-merging two branches which produces two merge conflicts located in non-coherent lines I wonder why the output produced by auto-merge only shows one conflict containing multiple equivalent lines.

The following shows the output after merging:

Hello
World
that
<<<<<<>>>>>> remote

I would expect something like this:

Hello
World
that
<<<<<<>>>>>> remote
a
goddamn
nasty
<<<<<<>>>>>> remote

Body:
Ok I found it out myself:
Adding one equal line in both branches produces this:

Hello
World
that
<<<<<<< HEAD
was
=======
will
be
>>>>>>> remote
a
long
goddamn
nasty
<<<<<<< HEAD
file.
=======
merge.
>>>>>>> remote

So I assume all conflicts are bound together if there is not at least a space of 4 un-conflicting lines between a conflict pair.


问:
How will records in Clojure 1.3 change?
I have tried to use records in Clojure 1.2 but they seem very messy and incomplete. I was considering waiting until their API has envolved and stabilised before I use them. Does anyone know what changes are due for 1.3, or are they pretty much fixed as they are now?

Update:

As shown from the link in the answer there could still be alot of changes to records and their related features, so it is not a good idea to use records unless you are prepared to rework the code which uses records in the future

Update 2:

And just to clarify: I guess I meant that alot of the upcoming features in records are being added by "Enhanced Clojure records" and other such libraries, when really it may be better to wait for these features to be in the core as once these features are in the core of clojure then the code will end up being rewritten to use the clojure core version of records

Title: How will records in Clojure 1.3 change?


问:
Cannot resolve symbol 'logger' on DuplicateKeyException
In short: the object "logger" is not recognized unlike in many tutorials.

The problem on its own is not very serious and I can easily go around it. However it is very frustrating to see this "logger" stays in red in my intellIj editor. I am going through docs and blogs and I don't see what the problem is.

My snippet:

```<code>@Override
public void insertTicketStatut(TicketStatut pTicketStatut) {
    String vSQL = "INSERT INTO statut {id, libelle} VALUES {:id, :libelle}";

    BeanPropertySqlParameterSource vParams = new BeanPropertySqlParameterSource(pTicketStatut);
    NamedParameterJdbcTemplate vJdbcTemplate = new NamedParameterJdbcTemplate(getDataSource());

    try {
        vJdbcTemplate.update(vSQL, vParams);
    } catch (DuplicateKeyException pE){
        logger.error("Le TicketStatut existe déjà ! id="+ pTicketStatut.getId(),pE);
    }
}
</code>```

Hovering over logger shows "Cannot resolve symbol 'logger'
Thanks for your help.

答:
The logger needs to be either instantiated or better injected. It seems that you did not do that. When you use some kind of logging framework like log4j the initialisation would look like this:

```<code>static Logger logger = Logger.getLogger(MainApp.class.getName());
</code>```

When you show us the whole class we can see more details and can guess better.

An tutorial for log4j and spring can be found here.

Body:
In short: the object "logger" is not recognized unlike in many tutorials.

The problem on its own is not very serious and I can easily go around it. However it is very frustrating to see this "logger" stays in red in my intellIj editor. I am going through docs and blogs and I don't see what the problem is.

My snippet:

@Override
public void insertTicketStatut(TicketStatut pTicketStatut) {
    String vSQL = "INSERT INTO statut {id, libelle} VALUES {:id, :libelle}";

    BeanPropertySqlParameterSource vParams = new BeanPropertySqlParameterSource(pTicketStatut);
    NamedParameterJdbcTemplate vJdbcTemplate = new NamedParameterJdbcTemplate(getDataSource());

    try {
        vJdbcTemplate.update(vSQL, vParams);
    } catch (DuplicateKeyException pE){
        logger.error("Le TicketStatut existe déjà ! id="+ pTicketStatut.getId(),pE);
    }
}

Hovering over logger shows "Cannot resolve symbol 'logger'
Thanks for your help.

Body:
The logger needs to be either instantiated or better injected. It seems that you did not do that. When you use some kind of logging framework like log4j the initialisation would look like this:

static Logger logger = Logger.getLogger(MainApp.class.getName());

When you show us the whole class we can see more details and can guess better.

An tutorial for log4j and spring can be found here.


问:
Laravel command called from Laravel job
I have a command named MyCommand, and I am calling it from a job named MyJob. I cannot see the command outputs when it's called from job. But if I run the command directly from command line, command output is seen.

MyCommand.php code:

```<code>namespace App\Console\Commands;

use Illuminate\Console\Command;

class MyCommand extends Command
{

    protected $signature = 'mycommand:doit';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $this->info('Process started');

        //Some process is done here

        $this->info('Process completed');
    }
}
</code>```

MyJob.php code:

```<code>namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Artisan;

class MyJob implements ShouldQueue
{
    public function __construct()
    {

    }

    public function handle()
    {
        Artisan::call('mycommand:doit');
    }
}
</code>```

答:
As in theory, you are not in a terminal with you run your job (Job may for example, be queued or scheduled), output is not saved when run outside a terminal.

However, you can still get the output buffer with Artisan::output();

Example:

```<code>namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Artisan;

class MyJob implements ShouldQueue
{
    public function __construct()
    {

    }

    public function handle()
    {
        Artisan::call('mycommand:doit');
        $output = Artisan::output(); // $output is a string

        // Do whatever you want with $output
    }
}
</code>```

Update: synchronous output

You may try this:
Example of command:

class SlowCommand extends Command
{
    protected $signature = "slow";

    public function handle()
    {
        $max = 10;

        for ($i = 0; $i < $max; $i++) {
            $this->line($i);
            sleep(1);
        }
    }
}
```

```// Synchronous output
Artisan::call("slow");
echo Artisan::output();

// Asynchronous output
$buffer = new ConsoleOutput();
Artisan::call("slow", [], $buffer);
```

Title: Laravel command called from Laravel job

Body:
I have a command named MyCommand, and I am calling it from a job named MyJob. I cannot see the command outputs when it's called from job. But if I run the command directly from command line, command output is seen.

MyCommand.php code:

namespace App\Console\Commands;

use Illuminate\Console\Command;

class MyCommand extends Command
{

    protected $signature = 'mycommand:doit';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $this->info('Process started');

        //Some process is done here

        $this->info('Process completed');
    }
}

MyJob.php code:

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Artisan;

class MyJob implements ShouldQueue
{
    public function __construct()
    {

    }

    public function handle()
    {
        Artisan::call('mycommand:doit');
    }
}

Body:
As in theory, you are not in a terminal with you run your job (Job may for example, be queued or scheduled), output is not saved when run outside a terminal.

However, you can still get the output buffer with Artisan::output();

Example:

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Artisan;

class MyJob implements ShouldQueue
{
    public function __construct()
    {

    }

    public function handle()
    {
        Artisan::call('mycommand:doit');
        $output = Artisan::output(); // $output is a string

        // Do whatever you want with $output
    }
}

Update: synchronous output

You may try this:
Example of command:

class SlowCommand extends Command
{
    protected $signature = "slow";

    public function handle()
    {
        $max = 10;

        for ($i = 0; $i < $max; $i++) {
            $this->line($i);
            sleep(1);
        }
    }
}

// Synchronous output
Artisan::call("slow");
echo Artisan::output();

// Asynchronous output
$buffer = new ConsoleOutput();
Artisan::call("slow", [], $buffer);


问:
Sqlalchemy filter by calculated datetime hybrid_property
I have a model Prescription.

```<code>from datetime import timedelta
from sqlalchemy.ext.hybrid import hybrid_property

class Prescription(db.Model):
    """ docstring """
    ID = db.column(db.Integer, primary_key=True)
    date = db.Column(db.DateTime)
    duration = db.Column(db.SmallInteger)

    @hybrid_property
    def expiration_date(self):
        # return self.date + timedelta(days=self.duration)
        return self.date + timedelta(days=7)

    @classmethod
    def actual(cls ):
        """ docstring """
        today = datetime.today()

        return cls.query.filter(Prescription.expiration_date>=today)
</code>```

I want to get only actual prescriptions in my actual method, and when I specify

```<code>@hybrid_property
def expiration_date(self):
    return self.date + timedelta(days=7)
</code>```

everything works like a charm.

But every prescription has a different duration, and when I specify

```<code>@hybrid_property
def expiration_date(self):
     return self.date + timedelta(days=self.duration)
</code>```

I've got an error

```<code>TypeError: unsupported type for timedelta days component: InstrumentedAttribute
</code>```

I tried to make a little hack like this

```<code>@property
def days(self):
    return int(self.duration)
</code>```

but no luck.
Can anyone tell some workaround, or creating some lazy object for duration field or maybe another way get actual prescriptions, filtering by calculated expiration_date?

答:
You might be trying to calculate a DATEDIFF:
Calculate DATEDIFF in POSTGRES using SQLAlchemy

Here, is_expired will generate a SQL query part which calculates difference in days between the start date and utcnow(), and compares the result with self.duration

This works in PostgreSQL, but I have not tested on other RDBMS.

from datetime import datetime
import sqlalchemy as sa

class Prescription:
    ID = db.column(db.Integer, primary_key=True)
    date = db.Column(db.DateTime)
    duration = db.Column(db.SmallInteger)

    @hybrid_property
    def is_expired(self):
        days_since_published = sa.func.trunc((
            sa.extract('epoch', datetime.utcnow()) -
            sa.extract('epoch', self.date)
        ) / 3600 / 24)

        return days_since_published >= self.duration

    @classmethod
    def active(cls):
        return cls.query.filter(is_expired=False)

```

Body:
I have a model Prescription.

from datetime import timedelta
from sqlalchemy.ext.hybrid import hybrid_property

class Prescription(db.Model):
    """ docstring """
    ID = db.column(db.Integer, primary_key=True)
    date = db.Column(db.DateTime)
    duration = db.Column(db.SmallInteger)

    @hybrid_property
    def expiration_date(self):
        # return self.date + timedelta(days=self.duration)
        return self.date + timedelta(days=7)

    @classmethod
    def actual(cls ):
        """ docstring """
        today = datetime.today()

        return cls.query.filter(Prescription.expiration_date>=today)

I want to get only actual prescriptions in my actual method, and when I specify

@hybrid_property
def expiration_date(self):
    return self.date + timedelta(days=7)

everything works like a charm.

But every prescription has a different duration, and when I specify

@hybrid_property
def expiration_date(self):
     return self.date + timedelta(days=self.duration)

I've got an error

TypeError: unsupported type for timedelta days component: InstrumentedAttribute

I tried to make a little hack like this

@property
def days(self):
    return int(self.duration)

but no luck.
Can anyone tell some workaround, or creating some lazy object for duration field or maybe another way get actual prescriptions, filtering by calculated expiration_date?


问:
Testing EditText errors with Espresso on Android
I want to test if an EditText field has an error (set with editText.setError("Cannot be blank!")).

I've created an Espresso test case with the new AndroidStudio 2.2 feature, to record Espresso tests. So the code is pretty much auto-generated. But for now it only checks if the editText is displayed.

```<code>@RunWith(AndroidJUnit4.class)
public class CreateNoteActivityTitleCannotBeBlank {

    @Rule
    public ActivityTestRule<CreateNoteActivity> mActivityTestRule = new ActivityTestRule<>(CreateNoteActivity.class);

    @Test
    public void createNoteActivityTitleCannotBeBlank() {
        ViewInteraction floatingActionButton = onView(
                allOf(withId(R.id.fab_add_note),
                        withParent(allOf(withId(R.id.activity_create_note),
                                withParent(withId(android.R.id.content)))),
                        isDisplayed()));
        floatingActionButton.perform(click());

        ViewInteraction editText = onView(
                allOf(withId(R.id.tiet_note_title),
                        childAtPosition(
                                childAtPosition(
                                        withId(R.id.til_title),
                                        0),
                                0),
                        isDisplayed()));
        editText.check(matches(isDisplayed()));

    }

    private static Matcher<View> childAtPosition(
            final Matcher<View> parentMatcher, final int position) {

        return new TypeSafeMatcher<View>() {
            @Override
            public void describeTo(Description description) {
                description.appendText("Child at position " + position + " in parent ");
                parentMatcher.describeTo(description);
            }

            @Override
            public boolean matchesSafely(View view) {
                ViewParent parent = view.getParent();
                return parent instanceof ViewGroup && parentMatcher.matches(parent)
                        && view.equals(((ViewGroup) parent).getChildAt(position));
            }
        };
    }
}
</code>```

Is there a way to test if the error is displayed?

答:
This worked for me under </p>

```<code>        onView(withId(R.id.signin_email)).check(matches(hasErrorText("Email not valid")));
</code>```

Body:
I want to test if an EditText field has an error (set with editText.setError("Cannot be blank!")).

I've created an Espresso test case with the new AndroidStudio 2.2 feature, to record Espresso tests. So the code is pretty much auto-generated. But for now it only checks if the editText is displayed.

@RunWith(AndroidJUnit4.class)
public class CreateNoteActivityTitleCannotBeBlank {

    @Rule
    public ActivityTestRule<CreateNoteActivity> mActivityTestRule = new ActivityTestRule<>(CreateNoteActivity.class);

    @Test
    public void createNoteActivityTitleCannotBeBlank() {
        ViewInteraction floatingActionButton = onView(
                allOf(withId(R.id.fab_add_note),
                        withParent(allOf(withId(R.id.activity_create_note),
                                withParent(withId(android.R.id.content)))),
                        isDisplayed()));
        floatingActionButton.perform(click());

        ViewInteraction editText = onView(
                allOf(withId(R.id.tiet_note_title),
                        childAtPosition(
                                childAtPosition(
                                        withId(R.id.til_title),
                                        0),
                                0),
                        isDisplayed()));
        editText.check(matches(isDisplayed()));

    }

    private static Matcher<View> childAtPosition(
            final Matcher<View> parentMatcher, final int position) {

        return new TypeSafeMatcher<View>() {
            @Override
            public void describeTo(Description description) {
                description.appendText("Child at position " + position + " in parent ");
                parentMatcher.describeTo(description);
            }

            @Override
            public boolean matchesSafely(View view) {
                ViewParent parent = view.getParent();
                return parent instanceof ViewGroup && parentMatcher.matches(parent)
                        && view.equals(((ViewGroup) parent).getChildAt(position));
            }
        };
    }
}

Is there a way to test if the error is displayed?

Body:
This worked for me under

        onView(withId(R.id.signin_email)).check(matches(hasErrorText("Email not valid")));


问:
When should i use @android:id/?
I've found some code examples with the @android:id/xyz attribute set instead of @+id/xyz.

When and why is it necessary to use Android ids instead of the user's id?

答:
@android is used to access the default resources of Android .
For example see this:

```<code>android:background="@android:color/transparent"
</code>```

Using + sign means this resource must be added in R.java file while not using + sign means the resource already exist in R.java.

Title: When should i use @android:id/?

Body:
@android is used to access the default resources of Android .
For example see this:

android:background="@android:color/transparent"

Using + sign means this resource must be added in R.java file while not using + sign means the resource already exist in R.java.


问:
BeautifulSoup responses - Beautiful Soup is not an HTTP client
The script should find the addresses of subpages with articles and collect the necessary data from them. The data should go to the database.
Data should be collected by processing HTML documents.

exactly what it should: 1.
find the 10 most common words with their numbers. 2. find
The 10 most common words with their numbers per author. 3.
posts authors with their name

I'm not sure the rest of the code works well but for now I'm getting the following error:

```<code>import requests
from bs4 import BeautifulSoup as bs
from selenium import webdriver
import psycopg2 as pg2
from sqlalchemy.dialects.postgresql import psycopg2

url = 'https://teonite.com/blog/page/{}/index.html'
all_links = []

headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'User-Agent': 'Mozilla/5.0'
}
with requests.Session() as s:
    r = s.get('https://teonite.com/blog/')
    soup = bs(r.content, 'lxml')
    article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')]
    all_links.append(article_links)
    num_pages = int(soup.select_one('.page-number').text.split('/')[1])

    for page in range(2, num_pages + 1):
        r = s.get(url.format(page))
        soup = bs(r.content, 'lxml')
        article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')]
        all_links.append(article_links)

    all_links = [item for i in all_links for item in i]

    d = webdriver.Chrome()

    for article in all_links:
        d.get(article)
        soup = bs(d.page_source, 'lxml')
        [t.extract() for t in soup(['style', 'script', '[document]', 'head', 'title'])]
        visible_text = soup.getText()

        try:
            print(soup.select_one('.post-title').text)
        except:
            print(article)
            print(soup.select_one('h1').text)
            break

    # nie moj !!!!!!

    # 2.2. Post contents
    contents = []
    for article_links in all_links:
        soup = bs((article), 'html.parser')
        content = soup.find('section', attrs={'class': 'post-content'})
        contents.append(content)

    # 2.1. Authors

    authors = []
    for article in all_links:
        soup = bs(article, 'html.parser')
        author = soup.find('span', attrs={'class': 'author-content'})
        authors.append(author)

    # POSTGRESQL CONNECTION
    # 1. Connect to local database using psycopg2

    import psycopg2

    hostname = 'balarama.db.elephantsql.com'
    username = 'yagoiucf'
    password = 'jxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    database = 'yagoiucf'

    conn = psycopg2.connect(host='balarama.db.elephantsql.com', user='yagoiucf',
                            password='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', dbname='yagoiucf')
    conn.close()
</code>```

答:
Multiple problems:

look at this part of your code

```<code># 2.2. Post contents
contents = []
for article_links in all_links:
    soup = bs((article), 'html.parser')
    content = soup.find('section', attrs={'class': 'post-content'})
    contents.append(content)

# 2.1. Authors

authors = []
for article in all_links:
    soup = bs(article, 'html.parser')
    author = soup.find('span', attrs={'class': 'author-content'})
    authors.append(author)
</code>```

in the first loop you have article_links, but then you pass article to BeautifulSoup. First of all article is an artefact from a previous loop and represent an url. I guess you actually want to pass article_links instead.

Second, in the code above that snippet you use selenium to retrieve the page source.

```<code>d = webdriver.Chrome()

for article in all_links:
    d.get(article)
    soup = bs(d.page_source, 'lxml')
</code>```

You need to do the same again (or use requests if you can)

Body:
The script should find the addresses of subpages with articles and collect the necessary data from them. The data should go to the database.
Data should be collected by processing HTML documents.

exactly what it should: 1.
find the 10 most common words with their numbers. 2. find
The 10 most common words with their numbers per author. 3.
posts authors with their name

I'm not sure the rest of the code works well but for now I'm getting the following error:

import requests
from bs4 import BeautifulSoup as bs
from selenium import webdriver
import psycopg2 as pg2
from sqlalchemy.dialects.postgresql import psycopg2

url = 'https://teonite.com/blog/page/{}/index.html'
all_links = []

headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'User-Agent': 'Mozilla/5.0'
}
with requests.Session() as s:
    r = s.get('https://teonite.com/blog/')
    soup = bs(r.content, 'lxml')
    article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')]
    all_links.append(article_links)
    num_pages = int(soup.select_one('.page-number').text.split('/')[1])

    for page in range(2, num_pages + 1):
        r = s.get(url.format(page))
        soup = bs(r.content, 'lxml')
        article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')]
        all_links.append(article_links)

    all_links = [item for i in all_links for item in i]

    d = webdriver.Chrome()

    for article in all_links:
        d.get(article)
        soup = bs(d.page_source, 'lxml')
        [t.extract() for t in soup(['style', 'script', '[document]', 'head', 'title'])]
        visible_text = soup.getText()

        try:
            print(soup.select_one('.post-title').text)
        except:
            print(article)
            print(soup.select_one('h1').text)
            break

    # nie moj !!!!!!

    # 2.2. Post contents
    contents = []
    for article_links in all_links:
        soup = bs((article), 'html.parser')
        content = soup.find('section', attrs={'class': 'post-content'})
        contents.append(content)

    # 2.1. Authors

    authors = []
    for article in all_links:
        soup = bs(article, 'html.parser')
        author = soup.find('span', attrs={'class': 'author-content'})
        authors.append(author)

    # POSTGRESQL CONNECTION
    # 1. Connect to local database using psycopg2

    import psycopg2

    hostname = 'balarama.db.elephantsql.com'
    username = 'yagoiucf'
    password = 'jxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    database = 'yagoiucf'

    conn = psycopg2.connect(host='balarama.db.elephantsql.com', user='yagoiucf',
                            password='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', dbname='yagoiucf')
    conn.close()

Body:
Multiple problems:

look at this part of your code

# 2.2. Post contents
contents = []
for article_links in all_links:
    soup = bs((article), 'html.parser')
    content = soup.find('section', attrs={'class': 'post-content'})
    contents.append(content)

# 2.1. Authors

authors = []
for article in all_links:
    soup = bs(article, 'html.parser')
    author = soup.find('span', attrs={'class': 'author-content'})
    authors.append(author)

in the first loop you have article_links, but then you pass article to BeautifulSoup. First of all article is an artefact from a previous loop and represent an url. I guess you actually want to pass article_links instead.

Second, in the code above that snippet you use selenium to retrieve the page source.

d = webdriver.Chrome()

for article in all_links:
    d.get(article)
    soup = bs(d.page_source, 'lxml')

You need to do the same again (or use requests if you can)


问:
Oracle - Transpose rows into columns
Here is a sample from the table I have been working on:

```<code>CREATE TABLE TEST_MC
(
 CLUSTER_K INTEGER,
 PROCESS_PHASE INTEGER,
 SEM_AGG CHAR(1)
);

CLUSTER_K  PROCESS_PHASE   SEM_AGG
==================================
    328          1            M
----------------------------------
    328          2            A
----------------------------------
    328          3            A
</code>```

Now, I would like to transpose and collapse rows obtaining the following result:

```<code> CLUSTER_K  SEM_AGG_1   SEM_AGG_2   SEM_AGG_3
=============================================
    328         M           A           A
</code>```

How i can achieve this (Pivot and/or analytical functions)?

Any help is greatly appreciated.

答:
if you don't Need dynamic column names you can use Pivot

```<code>with tab as(
  select 328 as CLUSTER_K, 1 as process_phase, 'M' as sem_agg from dual union all
  select 328 as CLUSTER_K, 2 as process_phase, 'A' as sem_agg from dual union all
  select 328 as CLUSTER_K, 3 as process_phase, 'A' as sem_agg from dual
)
select  *
from tab
pivot (max(sem_agg) for process_phase in (1 as sem_agg_1, 2 as sem_agg_2, 3 as sem_agg_3))
</code>```

db<>fiddle here

Title: Oracle - Transpose rows into columns

Body:
Here is a sample from the table I have been working on:

CREATE TABLE TEST_MC
(
 CLUSTER_K INTEGER,
 PROCESS_PHASE INTEGER,
 SEM_AGG CHAR(1)
);

CLUSTER_K  PROCESS_PHASE   SEM_AGG
==================================
    328          1            M
----------------------------------
    328          2            A
----------------------------------
    328          3            A

Now, I would like to transpose and collapse rows obtaining the following result:

 CLUSTER_K  SEM_AGG_1   SEM_AGG_2   SEM_AGG_3
=============================================
    328         M           A           A

How i can achieve this (Pivot and/or analytical functions)?

Any help is greatly appreciated.

Body:
if you don't Need dynamic column names you can use Pivot

with tab as(
  select 328 as CLUSTER_K, 1 as process_phase, 'M' as sem_agg from dual union all
  select 328 as CLUSTER_K, 2 as process_phase, 'A' as sem_agg from dual union all
  select 328 as CLUSTER_K, 3 as process_phase, 'A' as sem_agg from dual
)
select  *
from tab
pivot (max(sem_agg) for process_phase in (1 as sem_agg_1, 2 as sem_agg_2, 3 as sem_agg_3))

db<>fiddle here


问:
How to embed a public report using filters?
I would like to embed a report in my website, using filters and i want this report to be public

I saw that you can use the "Publish to web" option to do that but you can't use filters (I read that but i'm not sure)

and with the new "Embed" option you can filter but you need to have a account to see the report.

Is there a way to do both filtering and enable access to anyone on the internet ?

Thanks

答:
When you use "Publish to web" the filtering pane will not be visible, but you can always add slicers to your report, which will allow your visitors to filter the data.

The proper way to do this is to actually embed the report into your site. You can see it in action in Power BI Embedded Playground. When embedding, there are two scenarios - "user owns data", in which each visitor needs Power BI Pro account to see the report, and "app owns data", in which your application uses one Power BI Pro account to authenticate itself, but your users don't need to have Power BI accounts at all. In your case you need the later one.

Simply download Microsoft's sample application and configure it. You need to register Azure AD application to be used in your app. Then your app will authenticate itself and use Power BI REST API to get report's embedUrl and use it with Power BI JavaScript client to embed it in an empty
 in a web page.

Body:
When you use "Publish to web" the filtering pane will not be visible, but you can always add slicers to your report, which will allow your visitors to filter the data.

The proper way to do this is to actually embed the report into your site. You can see it in action in Power BI Embedded Playground. When embedding, there are two scenarios - "user owns data", in which each visitor needs Power BI Pro account to see the report, and "app owns data", in which your application uses one Power BI Pro account to authenticate itself, but your users don't need to have Power BI accounts at all. In your case you need the later one.

Simply download Microsoft's sample application and configure it. You need to register Azure AD application to be used in your app. Then your app will authenticate itself and use Power BI REST API to get report's embedUrl and use it with Power BI JavaScript client to embed it in an empty <div> in a web page.


问:
How to stop programme from reading if -1 is entered, and calculate average accordingly
I'm a beginner in C, and my task is to:
Write a program that reads in an array of up to 10 integers representing peoples ages in years and calculates and prints the maximum age and the minimum age and the average age. Your program should stop reading when either the 10th number is entered or the user enters -1. If the user enters any other negative number or a value above 150, they should be warned and prompted again for a valid age.

My code can find the maximum and minimum numbers and calculate the average, as well as ensuring the value is between 0 to 150. However I can't get the programme to stop if -1 is entered. My average, minimum, and maximum also just consider that 10 values are entered, so I need help in counting the amount of values entered by the user before (/if) -1 is entered, so they can be accurate.

```<code>int ages[10];
int i, j;
double sum=0;

for (i=0; i<10; i++){
    printf("Enter number %d: ",i+1);
    scanf("%d", &ages[i]);
    if (ages[i]<-2 || ages[i]>150){
        printf("Invalid number, enter again: ");
            scanf("%d",&ages[i]);
        while (ages[i]==-1){
            break;
        }
    }
}

for (i=0; i<10; i++){
    sum=sum+ages[i];
}
printf("Average: %f \n", (sum/10));
int min=ages[0];
int max=ages[0];

for (j=0; j<10;j++){
    if (ages[j]>max){
       max=ages[j];
    }
    else if (ages[j]<min){
        min=ages[j];
    }
}
printf("Minimum: %d. Maximum: %d. \n", min, max);
</code>```

答:
You may use this snippet to achieve what you want.

```<code>int ages[10],i=0,input,flag=0,j,min,max,sum=0,avg;
do{
    printf("Enter number %d: ",i+1);
    scanf("%d",&input);
    if(input == -1){
        flag = 1;
        break;
    }else if(input < -2 || input > 150){
        printf("Invalid number\n");
        continue;
    }
    ages[i] = input;
    i++;
}while(i < 10);

// Calculating avg, min, max
min=ages[0];
max=ages[0];
for(j=0;j<i;j++){
    sum+=ages[j];
    if(ages[j] > max){
        max = ages[j];
    }else if(ages[j] < min){
        min = ages[j];
    }
}
avg = sum/i;
printf(" Max: %d, Min: %d, Avg: %d \n", max,min,avg);
</code>```

Note i is only increased and ages array is updated when a valid age has been provided. In case -1 has been entered then we have to exit the do while loop.

In case that a number  < -2 and > 150 has been provided, we invoke continue to move over next iteration without increasing i or assigning ages array a new value.

This way we ensure that our array will hold valid values. flag indicates whether -1 has been provided in the loop. You may omit it if you don't need it anyway.

Body:
I'm a beginner in C, and my task is to:
Write a program that reads in an array of up to 10 integers representing peoples ages in years and calculates and prints the maximum age and the minimum age and the average age. Your program should stop reading when either the 10th number is entered or the user enters -1. If the user enters any other negative number or a value above 150, they should be warned and prompted again for a valid age.

My code can find the maximum and minimum numbers and calculate the average, as well as ensuring the value is between 0 to 150. However I can't get the programme to stop if -1 is entered. My average, minimum, and maximum also just consider that 10 values are entered, so I need help in counting the amount of values entered by the user before (/if) -1 is entered, so they can be accurate.

int ages[10];
int i, j;
double sum=0;

for (i=0; i<10; i++){
    printf("Enter number %d: ",i+1);
    scanf("%d", &ages[i]);
    if (ages[i]<-2 || ages[i]>150){
        printf("Invalid number, enter again: ");
            scanf("%d",&ages[i]);
        while (ages[i]==-1){
            break;
        }
    }
}

for (i=0; i<10; i++){
    sum=sum+ages[i];
}
printf("Average: %f \n", (sum/10));
int min=ages[0];
int max=ages[0];

for (j=0; j<10;j++){
    if (ages[j]>max){
       max=ages[j];
    }
    else if (ages[j]<min){
        min=ages[j];
    }
}
printf("Minimum: %d. Maximum: %d. \n", min, max);

Body:
You may use this snippet to achieve what you want.

int ages[10],i=0,input,flag=0,j,min,max,sum=0,avg;
do{
    printf("Enter number %d: ",i+1);
    scanf("%d",&input);
    if(input == -1){
        flag = 1;
        break;
    }else if(input < -2 || input > 150){
        printf("Invalid number\n");
        continue;
    }
    ages[i] = input;
    i++;
}while(i < 10);

// Calculating avg, min, max
min=ages[0];
max=ages[0];
for(j=0;j<i;j++){
    sum+=ages[j];
    if(ages[j] > max){
        max = ages[j];
    }else if(ages[j] < min){
        min = ages[j];
    }
}
avg = sum/i;
printf(" Max: %d, Min: %d, Avg: %d \n", max,min,avg);

Note i is only increased and ages array is updated when a valid age has been provided. In case -1 has been entered then we have to exit the do while loop.

In case that a number  < -2 and > 150 has been provided, we invoke continue to move over next iteration without increasing i or assigning ages array a new value.

This way we ensure that our array will hold valid values. flag indicates whether -1 has been provided in the loop. You may omit it if you don't need it anyway.


问:
How often to call commit on an offline Solr/Lucene index?
I know there have been some semi-similar questions, but in this case, I am building an index which is offline, until build is complete.  I am building from scratch two cores, one has about 300k records with alot of citation information and large blocks of full text (this is the document index) and another core which has about 6.6 Million records, with full text (this is the page index).

Given this index is being built offline, the only real performance issue is speed of building.  Noone should be querying this data.

The auto-commit would apparently fire if I stop adding items for 50 seconds?  Which I don't do.  I am adding ten at a time and they are added every couple seconds.

So, should I commit more often?  I feel like the longer this runs the slower it gets, at least in my test case of 6k documents to index.

With noone searching this index, how often would anyone suggest I commit?

Should say I am using Solr 3.1 and SolrNet.

答:
Although it's commits that are taking time for you, you might want to consider looking into other tweaking than commit frequency.

Is it the indexing core that also does searching, or is it replicated somewhere else after indexing concludes? If the latter is the case, then turning off caches might have a very noticeable impact on performance (solr rebuilds caches every time you commit).


问:
Dynamically passed function parameter for JS through php, is showing error that undefined
I have passed a parameter for js function in onclick event through php, but on click it is saying in console that parameter is undefined.

code in php

```<code><?php
echo "<div style='background-image: url($thumbnail);' onclick='showImageInDiv(dfds)'></div>";

?>

function showImageInDiv(dfdss){

        alert(dfdss);
}
</code>```

Error:

```<code>Uncaught ReferenceError: dfds is not defined
</code>```

答:
In your code you are passing a variable

```<code>onclick='showImageInDiv(dfds)'
</code>```

Instead of passing a string

```<code>onclick='showImageInDiv(\'dfds\')'
</code>```

That's why it's saying

error: Uncaught ReferenceError: dfds is not defined

Because dfds is not a string but a variable

Body:
I have passed a parameter for js function in onclick event through php, but on click it is saying in console that parameter is undefined.

code in php

<?php
echo "

";

?>

function showImageInDiv(dfdss){

        alert(dfdss);
}

Error:

Uncaught ReferenceError: dfds is not defined

Body:
In your code you are passing a variable

onclick='showImageInDiv(dfds)'

Instead of passing a string

onclick='showImageInDiv(\'dfds\')'

That's why it's saying

error: Uncaught ReferenceError: dfds is not defined

Because dfds is not a string but a variable


问:
How to verify an ES256 JWT token using Web Crypto when public key is distributed in PEM?
I need to verify ES256 JWT tokens in a Cloudflare Worker. To my understanding they do not run Node.js there and I will have to make everything work with the Web Crypto API (available in browsers, too, as window.crypto.subtle). However, I am expecting to receive the public keys as PEM files and I think I am having problems importing them.

I have been trying to modify an existing open source JWT implementation that only supports HS256 to support ES256.

In addition to trying to use the actual tokens and keys, and keys generated in browsers and OpenSSL, I have tried to use a working example from the JWT.io website (after converting it to JWK format using node-jose), since it should validate correctly. But I am not getting any errors, my code running in browser just tells me the token is not valid.

Here is my Node REPL session I used for converting the key from JWT.io to JWK:

> const jose = require('node-jose')
> const publicKey = `-----BEGIN PUBLIC KEY-----
... MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEVs/o5+uQbTjL3chynL4wXgUg2R9
... q9UU8I5mEovUf86QZ7kOBIjJwqnzD1omageEHWwHdBO6B+dFabmdT9POxg==
... -----END PUBLIC KEY-----`
> const keyStore = jose.JWK.createKeyStore()
> keyStore.add(publicKey, 'pem')
> keyStore.toJSON()
{
  keys: [
    {
      kty: 'EC',
      kid: '19J8y7Zprt2-QKLjF2I5pVk0OELX6cY2AfaAv1LC_w8',
      crv: 'P-256',
      x: 'EVs_o5-uQbTjL3chynL4wXgUg2R9q9UU8I5mEovUf84',
      y: 'kGe5DgSIycKp8w9aJmoHhB1sB3QTugfnRWm5nU_TzsY'
    }
  ]
}
>
```

<p>Here is the failing validation, based on code from <code>webcrypto-jwt</code> package:</p>

<pre class="lang-js prettyprint-override"><code>function utf8ToUint8Array(str) {
    // Adapted from https://chromium.googlesource.com/chromium/blink/+/master/LayoutTests/crypto/subtle/hmac/sign-verify.html
    var Base64URL = {
        stringify: function (a) {
        var base64string = btoa(String.fromCharCode.apply(0, a));
        return base64string.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
        },
        parse: function (s) {
        s = s.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '');
        return new Uint8Array(Array.prototype.map.call(atob(s), function (c) { return c.charCodeAt(0); }));
        }
    };
    str = btoa(unescape(encodeURIComponent(str)));
    return Base64URL.parse(str);
}

var cryptoSubtle = (crypto && crypto.subtle) ||
(crypto && crypto.webkitSubtle) ||
(window.msCrypto && window.msCrypto.Subtle);

// Token from JWT.io
var tokenParts = [
    'eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9',
    'eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0',
    'tyh-VfuzIxCyGYDlkBA7DfyjrqmSHu6pQ2hoZuFqUSLPNY2N0mpHb3nk5K17HWP_3cYHBw7AhHale5wky6-sVA'
];

// Public key from JWT.io converted in Node using node-jose
var publicKey = {
    kty: 'EC',
    kid: '19J8y7Zprt2-QKLjF2I5pVk0OELX6cY2AfaAv1LC_w8',
    crv: 'P-256',
    x: 'EVs_o5-uQbTjL3chynL4wXgUg2R9q9UU8I5mEovUf84',
    y: 'kGe5DgSIycKp8w9aJmoHhB1sB3QTugfnRWm5nU_TzsY'
};

var importAlgorithm = {
    name: 'ECDSA',
    namedCurve: 'P-256',
    hash: 'SHA-256',
};

cryptoSubtle.importKey(
    "jwk",
    publicKey,
    importAlgorithm,
    false,
    ["verify"]
).then(function (key) {
    var partialToken = tokenParts.slice(0,2).join('.');
    var signaturePart = tokenParts[2];

    cryptoSubtle.verify(
        importAlgorithm,
        key,
        utf8ToUint8Array(signaturePart),
        utf8ToUint8Array(partialToken)
    ).then(function (ok) {
        if (ok) {
            console.log("I think it's valid");
        } else {
            console.log("I think it isn't valid");
        }
    }).catch(function (err) {
        console.log("error verifying", err);
    });
}).catch(function(err) {
    console.log("error importing", err);
});
</code>```

Since I copied a valid key and a valid token from JWT.io, I am expecting the code to log "I think it's valid" without errors. It does not show any errors, indeed, but it ends up in "I think it isn't valid" branch.

答:
Answered here How to verify a signed JWT with SubtleCrypto of the Web Crypto API?

So, if I understood correctly, the problem was that base64 encoding included in the open source upstream just does not work correctly in one of the directions, since it uses the browser's btoa. Adapting https://github.com/swansontec/rfc4648.js instead works.

Body:
I need to verify ES256 JWT tokens in a Cloudflare Worker. To my understanding they do not run Node.js there and I will have to make everything work with the Web Crypto API (available in browsers, too, as window.crypto.subtle). However, I am expecting to receive the public keys as PEM files and I think I am having problems importing them.

I have been trying to modify an existing open source JWT implementation that only supports HS256 to support ES256.

In addition to trying to use the actual tokens and keys, and keys generated in browsers and OpenSSL, I have tried to use a working example from the JWT.io website (after converting it to JWK format using node-jose), since it should validate correctly. But I am not getting any errors, my code running in browser just tells me the token is not valid.

Here is my Node REPL session I used for converting the key from JWT.io to JWK:

> const jose = require('node-jose')
> const publicKey = `-----BEGIN PUBLIC KEY-----
... MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEVs/o5+uQbTjL3chynL4wXgUg2R9
... q9UU8I5mEovUf86QZ7kOBIjJwqnzD1omageEHWwHdBO6B+dFabmdT9POxg==
... -----END PUBLIC KEY-----`
> const keyStore = jose.JWK.createKeyStore()
> keyStore.add(publicKey, 'pem')
> keyStore.toJSON()
{
  keys: [
    {
      kty: 'EC',
      kid: '19J8y7Zprt2-QKLjF2I5pVk0OELX6cY2AfaAv1LC_w8',
      crv: 'P-256',
      x: 'EVs_o5-uQbTjL3chynL4wXgUg2R9q9UU8I5mEovUf84',
      y: 'kGe5DgSIycKp8w9aJmoHhB1sB3QTugfnRWm5nU_TzsY'
    }
  ]
}
>

Here is the failing validation, based on code from webcrypto-jwt package:

function utf8ToUint8Array(str) {
    // Adapted from https://chromium.googlesource.com/chromium/blink/+/master/LayoutTests/crypto/subtle/hmac/sign-verify.html
    var Base64URL = {
        stringify: function (a) {
        var base64string = btoa(String.fromCharCode.apply(0, a));
        return base64string.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
        },
        parse: function (s) {
        s = s.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '');
        return new Uint8Array(Array.prototype.map.call(atob(s), function (c) { return c.charCodeAt(0); }));
        }
    };
    str = btoa(unescape(encodeURIComponent(str)));
    return Base64URL.parse(str);
}

var cryptoSubtle = (crypto && crypto.subtle) ||
(crypto && crypto.webkitSubtle) ||
(window.msCrypto && window.msCrypto.Subtle);

// Token from JWT.io
var tokenParts = [
    'eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9',
    'eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0',
    'tyh-VfuzIxCyGYDlkBA7DfyjrqmSHu6pQ2hoZuFqUSLPNY2N0mpHb3nk5K17HWP_3cYHBw7AhHale5wky6-sVA'
];

// Public key from JWT.io converted in Node using node-jose
var publicKey = {
    kty: 'EC',
    kid: '19J8y7Zprt2-QKLjF2I5pVk0OELX6cY2AfaAv1LC_w8',
    crv: 'P-256',
    x: 'EVs_o5-uQbTjL3chynL4wXgUg2R9q9UU8I5mEovUf84',
    y: 'kGe5DgSIycKp8w9aJmoHhB1sB3QTugfnRWm5nU_TzsY'
};

var importAlgorithm = {
    name: 'ECDSA',
    namedCurve: 'P-256',
    hash: 'SHA-256',
};

cryptoSubtle.importKey(
    "jwk",
    publicKey,
    importAlgorithm,
    false,
    ["verify"]
).then(function (key) {
    var partialToken = tokenParts.slice(0,2).join('.');
    var signaturePart = tokenParts[2];

    cryptoSubtle.verify(
        importAlgorithm,
        key,
        utf8ToUint8Array(signaturePart),
        utf8ToUint8Array(partialToken)
    ).then(function (ok) {
        if (ok) {
            console.log("I think it's valid");
        } else {
            console.log("I think it isn't valid");
        }
    }).catch(function (err) {
        console.log("error verifying", err);
    });
}).catch(function(err) {
    console.log("error importing", err);
});

Since I copied a valid key and a valid token from JWT.io, I am expecting the code to log "I think it's valid" without errors. It does not show any errors, indeed, but it ends up in "I think it isn't valid" branch.


问:
Android Espresso. How to check ErrorText in TextInputLayout
Basically I am trying to test that after login incorrectly I have an error showing in the email field.

The view is:

```<code><android.support.design.widget.TextInputLayout
    android:id="@+id/ti_email"
    android:paddingEnd="10dp"
    android:paddingTop="10dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingStart="10dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/et_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/authentication_email_placeholder"
        android:inputType="textEmailAddress"
        android:maxLines="1"
        android:textSize="16sp"
        tools:text="@string/placeholder_email"/>

</android.support.design.widget.TextInputLayout>
</code>```

I try to do it like this:

```<code>onView(withId(R.id.et_email))
    .check(matches(hasErrorText(
        ctx.getString(R.string.authentication_error_empty_email))));
</code>```

答:
Its working :) </p>

```<code>onView(withId(R.id.et_email)).check(matches(hasErrorText("Error Message")));
</code>```

Body:
Basically I am trying to test that after login incorrectly I have an error showing in the email field.

The view is:

<android.support.design.widget.TextInputLayout
    android:id="@+id/ti_email"
    android:paddingEnd="10dp"
    android:paddingTop="10dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingStart="10dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/et_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/authentication_email_placeholder"
        android:inputType="textEmailAddress"
        android:maxLines="1"
        android:textSize="16sp"
        tools:text="@string/placeholder_email"/>

</android.support.design.widget.TextInputLayout>

I try to do it like this:

onView(withId(R.id.et_email))
    .check(matches(hasErrorText(
        ctx.getString(R.string.authentication_error_empty_email))));

Body:
Its working :)

onView(withId(R.id.et_email)).check(matches(hasErrorText("Error Message")));


问:
Linq retrive the parent object
Im using entityframework and the parent object MyObject already exist in my context (and childs loaded).

    public class MyObject
    {
        public int id { get; set; }
        public string name { get; set; }
        public IEnumerable<Child> child { get; set; }
    }

    public class Child
    {
        public int id { get; set; }
        public string name { get; set; }
        public IEnumerable<Child2> child2 { get; set; }
    }

    public class Child2
    {
        public int id { get; set; }
        public string name { get; set; }
    }
```

I want to make a condition on a Child2 property with keeping an instance of the Parent object.

var myFiletredMyObject = myObject.child.Where(c => c.child2.Any(c2 => c2.id == 1));
This gives me back a collection of Child object, how can I do to get the parent : MyObject ?

答:
Considering EntityFramework will return list of models from database you can filter your EF object like this.

```<code>var filterResult = myObject.Where(x => x.child.Any(a=>a.child2.Any(c2 => c2.id == 1))).ToList();
</code>```

Filter Result will be of type MyObject.

if your Object of type  MyObject  you can use ternary operator to apply criteria.

```<code>var filterResult = myObject.child.Where(a => a.child2.Any(c2 => c2.id == 1)).ToList().Count > 0 ? myObject : null;
</code>```

Title: Linq retrive the parent object

Body:
Im using entityframework and the parent object MyObject already exist in my context (and childs loaded).

    public class MyObject
    {
        public int id { get; set; }
        public string name { get; set; }
        public IEnumerable<Child> child { get; set; }
    }

    public class Child
    {
        public int id { get; set; }
        public string name { get; set; }
        public IEnumerable<Child2> child2 { get; set; }
    }

    public class Child2
    {
        public int id { get; set; }
        public string name { get; set; }
    }

I want to make a condition on a Child2 property with keeping an instance of the Parent object.

var myFiletredMyObject = myObject.child.Where(c => c.child2.Any(c2 => c2.id == 1));
This gives me back a collection of Child object, how can I do to get the parent : MyObject ?

Body:
Considering EntityFramework will return list of models from database you can filter your EF object like this.

var filterResult = myObject.Where(x => x.child.Any(a=>a.child2.Any(c2 => c2.id == 1))).ToList();

Filter Result will be of type MyObject.

if your Object of type  MyObject  you can use ternary operator to apply criteria.

var filterResult = myObject.child.Where(a => a.child2.Any(c2 => c2.id == 1)).ToList().Count > 0 ? myObject : null;


答:
Check quotes, you need to give quotes or else it will consider it as javascript variable, which is undefined.</p>

```<code>echo "<div class='fl-product-page-single-gallery-container'
style='background-image: url($thumbnail);'
onclick='showImageInDiv(\"$thumbnail\")'></div>";
</code>```

Title: Dynamically passed function parameter for JS through php, is showing error that undefined

Body:
Check quotes, you need to give quotes or else it will consider it as javascript variable, which is undefined.

echo "<div class='fl-product-page-single-gallery-container'
style='background-image: url($thumbnail);'
onclick='showImageInDiv(\"$thumbnail\")'></div>";