问:
Call php function from different class, namespace and file using include
I am aware that this question is very similar if not exactly the same as a few others but I seem to have problems Calling the function even after following those advises. Thanks for your understanding.

I'm trying set the username with "setUserName" function from this file Calling the function from Another file as shown below. I seem to be missunderstanding how to call classes and namespaces.

```<code>namespace StructType;

use \WsdlToPhp\PackageBase\AbstractStructBase;

/**
 * This class stands for webExport StructType
 * @subpackage Structs
 */
class WebExport extends AbstractStructBase
{
    /**
     * The userName
     * Meta informations extracted from the WSDL
     * - nillable: true
     * @var string
     */
    public $userName;
    /**
     * The passwordMd5
     * Meta informations extracted from the WSDL
     * - nillable: true
     * @var string
     */
    public $passwordMd5;
    /**
     * The ecfFile
     * Meta informations extracted from the WSDL
     * - nillable: true
     * @var string
     */
    public $ecfFile;
    /**
     * Constructor method for webExport
     * @uses WebExport::setUserName()
     * @uses WebExport::setPasswordMd5()
     * @uses WebExport::setEcfFile()
     * @param string $userName
     * @param string $passwordMd5
     * @param string $ecfFile
     */
    public function __construct($userName = null, $passwordMd5 = null, $ecfFile = null)
    {
        $this
            ->setUserName($userName)
            ->setPasswordMd5($passwordMd5)
            ->setEcfFile($ecfFile);
    }
    /**
     * Get userName value
     * @return string|null
     */
    public function getUserName()
    {
        return $this->userName;
    }
    /**
     * Set userName value
     * @param string $userName
     * @return \StructType\WebExport
     */
    public function setUserName($userName = null)
    {
        // validation for constraint: string
        if (!is_null($userName) && !is_string($userName)) {
            throw new \InvalidArgumentException(sprintf('Invalid value, please provide a string, "%s" given', gettype($userName)), __LINE__);
        }
        $this->userName = $userName;
        return $this;
    }
    /**
     * Get passwordMd5 value
     * @return string|null
     */
    public function getPasswordMd5()
    {
        return $this->passwordMd5;
    }
    /**
     * Set passwordMd5 value
     * @param string $passwordMd5
     * @return \StructType\WebExport
     */
    public function setPasswordMd5($passwordMd5 = null)
    {
        // validation for constraint: string
        if (!is_null($passwordMd5) && !is_string($passwordMd5)) {
            throw new \InvalidArgumentException(sprintf('Invalid value, please provide a string, "%s" given', gettype($passwordMd5)), __LINE__);
        }
        $this->passwordMd5 = $passwordMd5;
        return $this;
    }
    /**
     * Get ecfFile value
     * @return string|null
     */
    public function getEcfFile()
    {
        return $this->ecfFile;
    }
    /**
     * Set ecfFile value
     * @param string $ecfFile
     * @return \StructType\WebExport
     */
    public function setEcfFile($ecfFile = null)
    {
        // validation for constraint: string
        if (!is_null($ecfFile) && !is_string($ecfFile)) {
            throw new \InvalidArgumentException(sprintf('Invalid value, please provide a string, "%s" given', gettype($ecfFile)), __LINE__);
        }
        $this->ecfFile = $ecfFile;
        return $this;
    }
    /**
     * Method called when an object has been exported with var_export() functions
     * It allows to return an object instantiated with the values
     * @see AbstractStructBase::__set_state()
     * @uses AbstractStructBase::__set_state()
     * @param array $array the exported values
     * @return \StructType\WebExport
     */
    public static function __set_state(array $array)
    {
        return parent::__set_state($array);
    }
    /**
     * Method returning the class name
     * @return string __CLASS__
     */
    public function __toString()
    {
        return __CLASS__;
    }
}
</code>```

Heres how im trying to set the username Calling the function from Another file.

```<code><?php

require_once __DIR__ . '/vendor/autoload.php';

    class Class2{
        use \StructType\webExport;
        public static function staticFunction(){
            setUserName("webservice");
        }
    }
</code>```

Where am i going wrong? Everything works as intended if I set the password directly in the consctruct as following:

```<code> public function __construct($userName = "ws", $passwordMd5 = "qwerty", $ecfFile = null)
</code>```

Last error message:

Fatal error: Class2 cannot use StructType\WebExport - it is not a trait in index.php on line 289

答:
you use a use inside class, that represent of using Traits, if you want to create an object of WebExport you can use keyword new to create an object of WebExport, example:

```<code>public static function staticFunction() {
    $webExport = new \StructType\WebExport();
    $webExport->setUserName('webservice');
    $webExport->setPasswordMd5('somemd5password');
    $webExport->setEcfFile(somefile)'
}
</code>```

Traits: http://php.net/manual/en/language.oop5.traits.php

Body:
I am aware that this question is very similar if not exactly the same as a few others but I seem to have problems Calling the function even after following those advises. Thanks for your understanding.

I'm trying set the username with "setUserName" function from this file Calling the function from Another file as shown below. I seem to be missunderstanding how to call classes and namespaces.

namespace StructType;

use \WsdlToPhp\PackageBase\AbstractStructBase;

/**
 * This class stands for webExport StructType
 * @subpackage Structs
 */
class WebExport extends AbstractStructBase
{
    /**
     * The userName
     * Meta informations extracted from the WSDL
     * - nillable: true
     * @var string
     */
    public $userName;
    /**
     * The passwordMd5
     * Meta informations extracted from the WSDL
     * - nillable: true
     * @var string
     */
    public $passwordMd5;
    /**
     * The ecfFile
     * Meta informations extracted from the WSDL
     * - nillable: true
     * @var string
     */
    public $ecfFile;
    /**
     * Constructor method for webExport
     * @uses WebExport::setUserName()
     * @uses WebExport::setPasswordMd5()
     * @uses WebExport::setEcfFile()
     * @param string $userName
     * @param string $passwordMd5
     * @param string $ecfFile
     */
    public function __construct($userName = null, $passwordMd5 = null, $ecfFile = null)
    {
        $this
            ->setUserName($userName)
            ->setPasswordMd5($passwordMd5)
            ->setEcfFile($ecfFile);
    }
    /**
     * Get userName value
     * @return string|null
     */
    public function getUserName()
    {
        return $this->userName;
    }
    /**
     * Set userName value
     * @param string $userName
     * @return \StructType\WebExport
     */
    public function setUserName($userName = null)
    {
        // validation for constraint: string
        if (!is_null($userName) && !is_string($userName)) {
            throw new \InvalidArgumentException(sprintf('Invalid value, please provide a string, "%s" given', gettype($userName)), __LINE__);
        }
        $this->userName = $userName;
        return $this;
    }
    /**
     * Get passwordMd5 value
     * @return string|null
     */
    public function getPasswordMd5()
    {
        return $this->passwordMd5;
    }
    /**
     * Set passwordMd5 value
     * @param string $passwordMd5
     * @return \StructType\WebExport
     */
    public function setPasswordMd5($passwordMd5 = null)
    {
        // validation for constraint: string
        if (!is_null($passwordMd5) && !is_string($passwordMd5)) {
            throw new \InvalidArgumentException(sprintf('Invalid value, please provide a string, "%s" given', gettype($passwordMd5)), __LINE__);
        }
        $this->passwordMd5 = $passwordMd5;
        return $this;
    }
    /**
     * Get ecfFile value
     * @return string|null
     */
    public function getEcfFile()
    {
        return $this->ecfFile;
    }
    /**
     * Set ecfFile value
     * @param string $ecfFile
     * @return \StructType\WebExport
     */
    public function setEcfFile($ecfFile = null)
    {
        // validation for constraint: string
        if (!is_null($ecfFile) && !is_string($ecfFile)) {
            throw new \InvalidArgumentException(sprintf('Invalid value, please provide a string, "%s" given', gettype($ecfFile)), __LINE__);
        }
        $this->ecfFile = $ecfFile;
        return $this;
    }
    /**
     * Method called when an object has been exported with var_export() functions
     * It allows to return an object instantiated with the values
     * @see AbstractStructBase::__set_state()
     * @uses AbstractStructBase::__set_state()
     * @param array $array the exported values
     * @return \StructType\WebExport
     */
    public static function __set_state(array $array)
    {
        return parent::__set_state($array);
    }
    /**
     * Method returning the class name
     * @return string __CLASS__
     */
    public function __toString()
    {
        return __CLASS__;
    }
}

Heres how im trying to set the username Calling the function from Another file.

<?php

require_once __DIR__ . '/vendor/autoload.php';

    class Class2{
        use \StructType\webExport;
        public static function staticFunction(){
            setUserName("webservice");
        }
    }

Where am i going wrong? Everything works as intended if I set the password directly in the consctruct as following:

 public function __construct($userName = "ws", $passwordMd5 = "qwerty", $ecfFile = null)

Last error message:

Fatal error: Class2 cannot use StructType\WebExport - it is not a trait in index.php on line 289

Body:
you use a use inside class, that represent of using Traits, if you want to create an object of WebExport you can use keyword new to create an object of WebExport, example:

public static function staticFunction() {
    $webExport = new \StructType\WebExport();
    $webExport->setUserName('webservice');
    $webExport->setPasswordMd5('somemd5password');
    $webExport->setEcfFile(somefile)'
}

Traits: http://php.net/manual/en/language.oop5.traits.php


来源: stackexchange

问:
SSIS expressions using ODBC
I'm trying to execute a query against an ODBC source using an Execute SQL Task. This is my statement:

```<code>"select * from RoomType where zz__Timestamp_Modification_UTC__lcm >=  TIMESTAMP '" +@[User::LastJobRunDateTimeUtc]+ "'"
</code>```

in expression builder when I press "Evaluate Expression" button I get this error:

I've tried various escape characters but nothing is working. I found a post or two on this like this one. From what I can see I'm doing the same thing.
 How to pass SSIS variables in ODBC SQLCommand expression?

答:
My variable @[User::LastJobRunDateTimeUtc] was of type DateTime and apparently expression builder does not like that when using + to combine strings with variables other than string so I cast @[User::LastJobRunDateTimeUtc] to a string and it worked.

```<code>(DT_WSTR,50)@[User::LastJobRunDateTimeUtc]
</code>```

ContentLicense: CC BY-SA 3.0

Title: SSIS expressions using ODBC

Body:
I'm trying to execute a query against an ODBC source using an Execute SQL Task. This is my statement:

"select * from RoomType where zz__Timestamp_Modification_UTC__lcm >=  TIMESTAMP '" +@[User::LastJobRunDateTimeUtc]+ "'"

in expression builder when I press "Evaluate Expression" button I get this error:

I've tried various escape characters but nothing is working. I found a post or two on this like this one. From what I can see I'm doing the same thing.
 How to pass SSIS variables in ODBC SQLCommand expression?

Body:
My variable @[User::LastJobRunDateTimeUtc] was of type DateTime and apparently expression builder does not like that when using + to combine strings with variables other than string so I cast @[User::LastJobRunDateTimeUtc] to a string and it worked.

(DT_WSTR,50)@[User::LastJobRunDateTimeUtc]


问:
What's the relationship between sed, grep, find, awk, gawk, which one is preferred?
I'm new to Linux/Unix. I find some task can be accomplished by many ways using these commands. Is there some relationship between them? Or which one is preferred? Which one is outdated?

Thanks.

答:
Listed in order of how often I use them, appended with comment. For more details, try man command, eg man grep at the command line for more details.

grep - print lines matching a pattern * I personally find this the most useful.

```<code>grep foo *.txt
grep 192.168.1.1 output.log
grep -i steve */*.txt
</code>```

find - walk a file hierarchy * can be used to find files in subdirectories or
       execute shell commands on files

```<code>find . -name lost.txt -print
find . -name "*.txt" -print
find . -type f -exec chmod 0644 {} \;
</code>```

sed - stream editor * helps automate simple text edits on batches of files

```<code>sed "s/abc/ABC/" foo.txt
</code>```

awk - pattern-directed scanning and processing language * haven't used it for a long time.
      If it gets to the point I need to use awk, I generally use something like Ruby.

ContentLicense: CC BY-SA 2.5

Body:
Listed in order of how often I use them, appended with comment. For more details, try man command, eg man grep at the command line for more details.

grep - print lines matching a pattern * I personally find this the most useful.

grep foo *.txt
grep 192.168.1.1 output.log
grep -i steve */*.txt

find - walk a file hierarchy * can be used to find files in subdirectories or
       execute shell commands on files

find . -name lost.txt -print
find . -name "*.txt" -print
find . -type f -exec chmod 0644 {} \;

sed - stream editor * helps automate simple text edits on batches of files

sed "s/abc/ABC/" foo.txt

awk - pattern-directed scanning and processing language * haven't used it for a long time.
      If it gets to the point I need to use awk, I generally use something like Ruby.


问:
DbFunctions.TruncateTime() still producing "type member 'Date' is not supported" error
I'm really having trouble with the LINQ query below. I did a lot of research on this error and almost everything i have found references the use of DbFunctions.TruncateTime(), however this still does not seem to be working for me. I'm hoping someone can take a look at this and let me know where i am going wrong. All i am trying to do is compare only the date portion of the datetime but i continue to get the Exception: The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

```<code>if (!db.MaintenanceWindows.Any(x => x.Id == Id &
DbFunctions.TruncateTime(x.BlockedDay) == DateTime.UtcNow.Date &
x.IsDeleted.Value == false))
{
...
}
</code>```

TIA

答:
It's not complaining about the DbFunctions.TruncateTime. It's complaining about the  DateTime.UtcNow.Date

Suggestion A:
(not recommended)

```<code>if (!db.MaintenanceWindows.Any(x => x.Id == Id &&
    DbFunctions.TruncateTime(x.BlockedDay) == DbFunctions.TruncateTime(DateTime.UtcNow) &&
    x.IsDeleted.Value == false))
</code>```

Suggestion B:

```<code>var utcNow = DateTime.UtcNow.Date;
if (!db.MaintenanceWindows.Any(x => x.Id == Id &&
    DbFunctions.TruncateTime(x.BlockedDay) == utcNow &&
    x.IsDeleted.Value == false))
</code>```

Also, you are going to want the "logical AND"  (&&) in the expression.

Body:
I'm really having trouble with the LINQ query below. I did a lot of research on this error and almost everything i have found references the use of DbFunctions.TruncateTime(), however this still does not seem to be working for me. I'm hoping someone can take a look at this and let me know where i am going wrong. All i am trying to do is compare only the date portion of the datetime but i continue to get the Exception: The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

if (!db.MaintenanceWindows.Any(x => x.Id == Id &
DbFunctions.TruncateTime(x.BlockedDay) == DateTime.UtcNow.Date &
x.IsDeleted.Value == false))
{
...
}

TIA

Body:
It's not complaining about the DbFunctions.TruncateTime. It's complaining about the  DateTime.UtcNow.Date

Suggestion A:
(not recommended)

if (!db.MaintenanceWindows.Any(x => x.Id == Id &&
    DbFunctions.TruncateTime(x.BlockedDay) == DbFunctions.TruncateTime(DateTime.UtcNow) &&
    x.IsDeleted.Value == false))

Suggestion B:

var utcNow = DateTime.UtcNow.Date;
if (!db.MaintenanceWindows.Any(x => x.Id == Id &&
    DbFunctions.TruncateTime(x.BlockedDay) == utcNow &&
    x.IsDeleted.Value == false))

Also, you are going to want the "logical AND"  (&&) in the expression.

ContentLicense: CC BY-SA 4.0


问:
Time comeplexity difference in between inner loop and by calling function
This is a question regarding Complexity of algorithm. If I am creating a loop ('for' loop for instance) and want to test the primality of the values returned (after some operations definitely) in this loop and therefore, I run an inner loop. Instead of that, if I create a function to test primality and then call that function during the first loop, still, the time complexity remains same right?
And what is the complexity in both cases? How to calculate that?

Thanks

答:
Complexcity of a code is measured in terms of space and time. Lets try to understand the time complexcity.

Lets see one way to measure time Complexcity, it is most famous and called Big O notqtion. As per wikipedia "Big O notation is a mathematical notation that describes the limiting behavior of a function when the argument tends towards a particular value or infinity. "

Suppose there is an operation (which may be performed by few lines of code) whose single execution takes T units of time. Time complexcity is the function of number of input values and represents the time taken to execute the operation for those input items.

If the time taken is always T irrespective of the number of inputs then it is said to be a constant function and time complexcity is said to be O(1).

If the time taken increases linearly with respect to the number of input then it is linear function amd time complexcity is O(N)

Lets see a simple example

```<code>public int sumOfFirstNNumbersWayOne( int n ){
    int sum = 0;
     for (int i = 1; i <= n; i++){
           sum += i; // this loops executes as per the number n
     }
     return sum;
}

  public int sumOfFirstNNumbersWayTwo( int n ){
       int sum = n*(n+1)/2; // the number of times this operation is executed is independent of the input n
      return sum;
 }
</code>```

Time complexcity of sumOfFirstNNumbersWayOne is O(n) and for
sumOfFirstNNumbersWayTwo is O(1).

It does not matter if the operation os performed within loops or a method is called in measuring time complexcity. ( Overhead of method call, method call's entry in stack, are negligible)

```<code> public int sumOfFirstNNumbersWayThree( int n ){
     int sum = 0;
     for (int i = 1; i <= n; i++){
           sum = sum( sum, i);
     }
     return sum;
 }

public int sum(int a , int b){
     return a+b;
}
</code>```

Time compelxcity of sumOfFirstNNumbersWayThree is still O(n).

Similarly suppose the number of times a particular set of operations gets increased exponentially as the number of input is increased then time complexcity is said to be exponential.

Other famous time complexcites are O(log(n)), O(n^2), O(nlog(n)), O(n!), [ n is the reference and it can be number of input with respect to which we want to measure the time complexcity, it can be size of the input array, number of bits of input number, number of digits of input number, length of input string, number of lines in a file, etc]

Body:
Complexcity of a code is measured in terms of space and time. Lets try to understand the time complexcity.

Lets see one way to measure time Complexcity, it is most famous and called Big O notqtion. As per wikipedia "Big O notation is a mathematical notation that describes the limiting behavior of a function when the argument tends towards a particular value or infinity. "

Suppose there is an operation (which may be performed by few lines of code) whose single execution takes T units of time. Time complexcity is the function of number of input values and represents the time taken to execute the operation for those input items.

If the time taken is always T irrespective of the number of inputs then it is said to be a constant function and time complexcity is said to be O(1).

If the time taken increases linearly with respect to the number of input then it is linear function amd time complexcity is O(N)

Lets see a simple example

public int sumOfFirstNNumbersWayOne( int n ){
    int sum = 0;
     for (int i = 1; i <= n; i++){
           sum += i; // this loops executes as per the number n
     }
     return sum;
}

  public int sumOfFirstNNumbersWayTwo( int n ){
       int sum = n*(n+1)/2; // the number of times this operation is executed is independent of the input n
      return sum;
 }

Time complexcity of sumOfFirstNNumbersWayOne is O(n) and for
sumOfFirstNNumbersWayTwo is O(1).

It does not matter if the operation os performed within loops or a method is called in measuring time complexcity. ( Overhead of method call, method call's entry in stack, are negligible)

 public int sumOfFirstNNumbersWayThree( int n ){
     int sum = 0;
     for (int i = 1; i <= n; i++){
           sum = sum( sum, i);
     }
     return sum;
 }

public int sum(int a , int b){
     return a+b;
}

Time compelxcity of sumOfFirstNNumbersWayThree is still O(n).

Similarly suppose the number of times a particular set of operations gets increased exponentially as the number of input is increased then time complexcity is said to be exponential.

Other famous time complexcites are O(log(n)), O(n^2), O(nlog(n)), O(n!), [ n is the reference and it can be number of input with respect to which we want to measure the time complexcity, it can be size of the input array, number of bits of input number, number of digits of input number, length of input string, number of lines in a file, etc]


问:
Ionic transitions getting white page only in ios
Im developing an app in ionic and its working perfectly fine in android, emulators and web (with ionic serve). But when is running in ios devices in transitions between pages suddenly it shows a white view instead the view that it have to display. This doesn't happen all time and i didn't figured out when specifically happen. </p>

<p>I appreciate any help. </p>

答: Simply use can-swipe-back="false" on your ion-view element.

Body:
Im developing an app in ionic and its working perfectly fine in android, emulators and web (with ionic serve). But when is running in ios devices in transitions between pages suddenly it shows a white view instead the view that it have to display. This doesn't happen all time and i didn't figured out when specifically happen.

I appreciate any help.


问:
Return both string and integer from a template function in C++
I am trying to write a generic function, using template, that is able to return bool, integer or char* or string.

```<code>template<typename entryType>
entryType getEntry(xml_node node, const char* entryKey)
{
    ...

    if (is_same<entryType, bool>::value) {
         return boolvalue; //returning a boolean
    }
    else if(is_same<entryType, int>::value) {
         return a; //this is an integer
    }
    else if (is_same<entryType, char*>::value) {
         return result; //this is a char*
    }
}
</code>```

and I would like to be able to call it like:

```<code>bool bPublisher = getEntry<bool>(node, "Publisher");
int QoS = getEntry<int>(node, "QualityOfService");
char* sBrokerUrl = getEntry<char*>(node, "BrokerUrl");
</code>```

as an alternative for the char*, a string would be also fine:

```<code>string sBrokerUrl = getEntry<string>(node, "BrokerUrl");
</code>```

I get errors like: "cannot convert from 'bool' to 'char*'. I understand the problem, the compiler is not able to detect that the code execution branch depends on the type I give. I just can't find a solution for that. Could anyone help me? Thanks.

答:
If C++17 is not available to you, template specialization would probably do what you want:

```<code>template<typename entryType>
entryType getEntry(xml_node node, const char* entryKey) {}

template<>
bool getEntry<bool>(xml_node node, const char* entryKey) {
   return true;
}

template<>
int getEntry<int>(xml_node node, const char* entryKey) {
   return 1;
}
</code>```

You could put any shared code in a helper function called from each specialization:

```<code>void shared_code(xml_node node, const char* entryKey) {
   // ...
}

template<>
bool getEntry<bool>(xml_node node, const char* entryKey) {
   shared_code(node, entryKey);
   return true;
}

template<>
int getEntry<int>(xml_node node, const char* entryKey) {
   shared_code(node, entryKey);
   return 1;
}
</code>```

Body:
I am trying to write a generic function, using template, that is able to return bool, integer or char* or string.

template<typename entryType>
entryType getEntry(xml_node node, const char* entryKey)
{
    ...

    if (is_same<entryType, bool>::value) {
         return boolvalue; //returning a boolean
    }
    else if(is_same<entryType, int>::value) {
         return a; //this is an integer
    }
    else if (is_same<entryType, char*>::value) {
         return result; //this is a char*
    }
}

and I would like to be able to call it like:

bool bPublisher = getEntry<bool>(node, "Publisher");
int QoS = getEntry<int>(node, "QualityOfService");
char* sBrokerUrl = getEntry<char*>(node, "BrokerUrl");

as an alternative for the char*, a string would be also fine:

string sBrokerUrl = getEntry<string>(node, "BrokerUrl");

I get errors like: "cannot convert from 'bool' to 'char*'. I understand the problem, the compiler is not able to detect that the code execution branch depends on the type I give. I just can't find a solution for that. Could anyone help me? Thanks.

Body:
If C++17 is not available to you, template specialization would probably do what you want:

template<typename entryType>
entryType getEntry(xml_node node, const char* entryKey) {}

template<>
bool getEntry<bool>(xml_node node, const char* entryKey) {
   return true;
}

template<>
int getEntry<int>(xml_node node, const char* entryKey) {
   return 1;
}

You could put any shared code in a helper function called from each specialization:

void shared_code(xml_node node, const char* entryKey) {
   // ...
}

template<>
bool getEntry<bool>(xml_node node, const char* entryKey) {
   shared_code(node, entryKey);
   return true;
}

template<>
int getEntry<int>(xml_node node, const char* entryKey) {
   shared_code(node, entryKey);
   return 1;
}


问:
<source> media attribute - width of container rather than screen?
I'm using the <picture></picture> tag to responsively display an image after assessing the size of the container it's in.

Some example code:

```<code><picture>
            <source media="(max-width: 70px)" srcset="IMAGE_URL">
            <source media="(min-width: 71px) and (max-width: 170px)" srcset="IMAGE_URL">
            <source media="(min-width: 171px) and (max-width: 270px)" srcset="IMAGE_URL">
            . . .
            <img src="IMAGE_URL" alt="An image">
</picture>
</code>```

However, the <source media="(MEDIA_QUERY)" ... > part in an implementation of the format above considers the width of the entire screen, rather than the container that the <picture></picture> is currently inside.

Help on this is appriciated.

答:
There is unfortunately no standard way (yet) to base responsive behavior upon a container instead of the browser viewport.

There are community efforts around Container Queries, but nothing has yet been defined, that could eventually become a standard.

There are several JavaScript libraries, like EQCSS, trying to provide solutions, but requiring JavaScript for a presentation —hence CSS— job is often not a good idea.

You can also look at CSS Conditions, but it also requires JavaScript.

Body:
I'm using the <picture></picture> tag to responsively display an image after assessing the size of the container it's in.

Some example code:

<picture>
            <source media="(max-width: 70px)" srcset="IMAGE_URL">
            <source media="(min-width: 71px) and (max-width: 170px)" srcset="IMAGE_URL">
            <source media="(min-width: 171px) and (max-width: 270px)" srcset="IMAGE_URL">
            . . .

</picture>

However, the <source media="(MEDIA_QUERY)" ... > part in an implementation of the format above considers the width of the entire screen, rather than the container that the <picture></picture> is currently inside.

Help on this is appriciated.


问:
SQL Update Statement for all values of column when value equals certain value
How would I update all row values of a SQL table in a column when the value equals a certain value?

For Example (TableA):

```<code>ColumnA | ColumnB | ColumnC
---------------------------
a       | b       | c
a       | x       | c
a       | x       | c
a       | x       | c
a       | b       | c
a       | b       | c
</code>```

I would I rename all x in ColumnB to y?

答:
If I understand correctly, this is simple update:</p>

```<code>update tableA
    set columnb = 'y'
    where columnb = 'x';
</code>```

Body:
How would I update all row values of a SQL table in a column when the value equals a certain value?

For Example (TableA):

ColumnA | ColumnB | ColumnC
---------------------------
a       | b       | c
a       | x       | c
a       | x       | c
a       | x       | c
a       | b       | c
a       | b       | c

I would I rename all x in ColumnB to y?

Body:
If I understand correctly, this is simple update:

update tableA
    set columnb = 'y'
    where columnb = 'x';


问:
How does data shape change during Conv2D and Dense in Keras?
Just as the title says. This code only works Using:

```<code>x = Flatten()(x)
</code>```

Between the convolutional layer and the dense layer.

```<code>import numpy as np
import keras
from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Flatten, Input
from keras.layers import Conv2D, MaxPooling2D
from keras.optimizers import SGD

# Generate dummy data
x_train = np.random.random((100, 100, 100, 3))
y_train = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10)

#Build Model
input_layer = Input(shape=(100, 100, 3))
x = Conv2D(32, (3, 3), activation='relu')(input_layer)
x = Dense(256, activation='relu')(x)
x = Dense(10, activation='softmax')(x)
model = Model(inputs=[input_layer],outputs=[x])

#compile network
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd)

#train network
model.fit(x_train, y_train, batch_size=32, epochs=10)
</code>```

Otherwise, I receive this error:

```<code>Traceback (most recent call last):

File "/home/michael/practice_example.py", line 44, in <module>
    model.fit(x_train, y_train, batch_size=32, epochs=10)

File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1435, in fit
    batch_size=batch_size)

File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1315, in _standardize_user_data
    exception_prefix='target')

File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 127, in _standardize_input_data
    str(array.shape))

ValueError: Error when checking target: expected dense_2 to have 4 dimensions, but got array with shape (100, 10)
</code>```

Why would the output have 4 dimensions without the flatten() layer?

答:
From Dense documentation one may read that in case when an input to a Dense has more than two dimensions - it's applied only to a last one - and all other dimensions are kept:

```<code># shape=(100, 100, 100, 3)

x = Conv2D(32, (3, 3), activation='relu')(input_layer)
# shape=(100, row, col, 32)

x = Dense(256, activation='relu')(x)
# shape=(100, row, col, 256)

x = Dense(10, activation='softmax')(x)
# shape=(100, row, col, 10)
</code>```

That's why a 4d target is expected.

Body:
Just as the title says. This code only works Using:

x = Flatten()(x)

Between the convolutional layer and the dense layer.

import numpy as np
import keras
from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Flatten, Input
from keras.layers import Conv2D, MaxPooling2D
from keras.optimizers import SGD

# Generate dummy data
x_train = np.random.random((100, 100, 100, 3))
y_train = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10)

#Build Model
input_layer = Input(shape=(100, 100, 3))
x = Conv2D(32, (3, 3), activation='relu')(input_layer)
x = Dense(256, activation='relu')(x)
x = Dense(10, activation='softmax')(x)
model = Model(inputs=[input_layer],outputs=[x])

#compile network
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd)

#train network
model.fit(x_train, y_train, batch_size=32, epochs=10)

Otherwise, I receive this error:

Traceback (most recent call last):

File "/home/michael/practice_example.py", line 44, in <module>
    model.fit(x_train, y_train, batch_size=32, epochs=10)

File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1435, in fit
    batch_size=batch_size)

File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1315, in _standardize_user_data
    exception_prefix='target')

File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 127, in _standardize_input_data
    str(array.shape))

ValueError: Error when checking target: expected dense_2 to have 4 dimensions, but got array with shape (100, 10)

Why would the output have 4 dimensions without the flatten() layer?

Body:
From Dense documentation one may read that in case when an input to a Dense has more than two dimensions - it's applied only to a last one - and all other dimensions are kept:

# shape=(100, 100, 100, 3)

x = Conv2D(32, (3, 3), activation='relu')(input_layer)
# shape=(100, row, col, 32)

x = Dense(256, activation='relu')(x)
# shape=(100, row, col, 256)

x = Dense(10, activation='softmax')(x)
# shape=(100, row, col, 10)

That's why a 4d target is expected.


问:
Node Express Server Cannot GET "/"
I am writing some code for my node server and everything is working fine locally. However, when I deploy it, I get the infamous "Cannot GET /" 404 error. All of the other routes which I have written work successfully (Both locally and in the cloud).

I have included the code below. I've checked my environment variables and all of them properly align. If any of you have any theories concerning the cause of this, it would be much appreciated.

//Use this route to make the entire app secure.  This forces login for any path in the entire app.
  app.use('/', passport.authenticate('main', {
    noredirect: false //Don't redirect a user to the authentication page, just show an error
  }),
    express.static(path.join(__dirname, '../public'))
  );```

答:
It doesn't look like you are serving any files to the user when they navigate to that route. Do you have an index.html or some other file? If so, you can use this inside your app.use function:</p>

```<code>res.sendFile('index.html')
</code>```

Title: Node Express Server Cannot GET "/"

Body:
It doesn't look like you are serving any files to the user when they navigate to that route. Do you have an index.html or some other file? If so, you can use this inside your app.use function:

res.sendFile('index.html')


问:
How can I get a full dump of a REST API
I want to have a full dump of a rest API. Now I have to query on everything but I just want to have everything of the API in one file (csv or json).

How can I do this?

Thanks!

答: "full dump of a rest API" do you mean you want to have file specification of API? If so, you can a have a look at this tool (http://editor.swagger.io/#/) for describing rest api interfaces.</p>

Title: How can I get a full dump of a REST API


问:
Php after echo displayed blank screen
After echo is displayed, when you click 'ok', it just goes to the php file which displays nothing (so I end up with a blank screen), this happens twice, how can I fix it?

After the second echo is displayed, when you click 'ok', it must go back to the page so the user can do the reCAPTCHA, now it just goes to the php file which displays nothing (so I end up with a blank screen again)

```<code><?php
// grab recaptcha library
require_once "recaptchalib.php";

// your secret key
$secret = "secretkey";

// empty response
$response = null;

// check secret key
$reCaptcha = new ReCaptcha($secret);

// if submitted check response
if ($_POST["g-recaptcha-response"]) {
$response = $reCaptcha->verifyResponse(
    $_SERVER["REMOTE_ADDR"],
    $_POST["g-recaptcha-response"]
);
}

if ($response != null && $response->success) {
if(isset($_POST['submit'])) {
$to = "mail@hotmail.com";
$subject = "Voorstel ---.synology.me";
$suggest = $_POST['comment'];

$body = " NL\n Suggestie: $suggest\n";

echo "<script>alert('Je voorstel is verstuurd, wij proberen dit zo snel mogelijk te verwezelijken!');</script>";
//after previous echo is displayed, when you click 'ok', it just goes to the php file which displays nothing (so I end up with a blank screen)
$headers = "From: mail2@hotmail.com" . "\r\n";
mail($to, $subject, $body, $headers);
} else {
echo "Er ging iets mis, probeer opnieuw of contacteer de administrator op mail2@hotmail.com!";
}

} else {
echo "<script>alert('Vul de Captcha correct in!');</script>";
//after previous echo is displayed, when you click 'ok', it must go back to the page so the user can do the reCAPTCHA
//now it just goes to the php file which displays nothing (so I end up with a blank screen)
}
?>
</code>```

答:
Instead an alert, how about a confirm that redirects the page?

```<code><script>
if(confirm('Vul de Captcha correct in!')){
  window.location.href = "yourpage.php";
}
</script>
</code>```

Don't forget to make sure your echo is correctly formatted.

```<code>echo "<script>
    if(confirm('Vul de Captcha correct in!')){
        window.location.href = 'yourpage.php';
    }
</script>";
</code>```

To have the same effect regardless of the choice simply account for it with the if statement.

```<code><script>
    if(confirm('Vul de Captcha correct in!')){
      window.location.href = "yourpage.php";
    }else{
      window.location.href = "yourpage.php";
    }
 </script>
</code>```

Title: Php after echo displayed blank screen

Body:
After echo is displayed, when you click 'ok', it just goes to the php file which displays nothing (so I end up with a blank screen), this happens twice, how can I fix it?

After the second echo is displayed, when you click 'ok', it must go back to the page so the user can do the reCAPTCHA, now it just goes to the php file which displays nothing (so I end up with a blank screen again)

<?php
// grab recaptcha library
require_once "recaptchalib.php";

// your secret key
$secret = "secretkey";

// empty response
$response = null;

// check secret key
$reCaptcha = new ReCaptcha($secret);

// if submitted check response
if ($_POST["g-recaptcha-response"]) {
$response = $reCaptcha->verifyResponse(
    $_SERVER["REMOTE_ADDR"],
    $_POST["g-recaptcha-response"]
);
}

if ($response != null && $response->success) {
if(isset($_POST['submit'])) {
$to = "mail@hotmail.com";
$subject = "Voorstel ---.synology.me";
$suggest = $_POST['comment'];

$body = " NL\n Suggestie: $suggest\n";

echo "";
//after previous echo is displayed, when you click 'ok', it just goes to the php file which displays nothing (so I end up with a blank screen)
$headers = "From: mail2@hotmail.com" . "\r\n";
mail($to, $subject, $body, $headers);
} else {
echo "Er ging iets mis, probeer opnieuw of contacteer de administrator op mail2@hotmail.com!";
}

} else {
echo "";
//after previous echo is displayed, when you click 'ok', it must go back to the page so the user can do the reCAPTCHA
//now it just goes to the php file which displays nothing (so I end up with a blank screen)
}
?>

Body:
Instead an alert, how about a confirm that redirects the page?

<script>
if(confirm('Vul de Captcha correct in!')){
  window.location.href = "yourpage.php";
}
</script>

Don't forget to make sure your echo is correctly formatted.

echo "<script>
    if(confirm('Vul de Captcha correct in!')){
        window.location.href = 'yourpage.php';
    }
</script>";

To have the same effect regardless of the choice simply account for it with the if statement.

<script>
    if(confirm('Vul de Captcha correct in!')){
      window.location.href = "yourpage.php";
    }else{
      window.location.href = "yourpage.php";
    }
 </script>


问:
Java Properties file to JSON using Jackson
I would like to convert a Java Properties file into JSON with nested objects. I followed an example I found here but I can't get it to work.

For example, given:

```<code>objectA.version=1.0
objectA.hostname=192.168.0.11
objectA.port=9989
objectB.hostname=10.0.2.15
objectB.port=9998
</code>```

I want:

```<code>{
  “objectA” : {
             "version” : "1.0"
             "host” : “192.168.0.11”,
             "port" : 9989
           },
  “objectB” : {
             "host” : “10.0.2.15”,
             "port" : 9998
           }
}
</code>```

This is what I have so far:

```<code>static class Endpoint
{
    @JsonProperty("objectA")
    public ObjectA objectA;

    @JsonProperty("objectB")
    public ObjectB objectB;

}
static class ObjectA
{
    public String hostname;
    public String port;
    public String version;
}

static class ObjectB
{
    public String hostname;
    public String port;
}

try (InputStream input = getClass().getClassLoader().getResourceAsStream("file.properties"))
{
    JavaPropsMapper mapper = new JavaPropsMapper();
    Endpoint host = mapper.readValue(input, Endpoint.class);
    String asText = mapper.writeValueAsString(host);
    System.out.println(asText);
}
</code>```

The output looks like this:

```<code>objectA.version=1.0
objectA.hostname=192.168.0.11
objectA.port=9989
objectB.hostname=10.0.2.15
objectB.port=9998
</code>```

答:
I figured it out.</p>

```<code>try (InputStream input = getClass().getClassLoader().getResourceAsStream("file.properties"))
{
    JavaPropsMapper mapper = new JavaPropsMapper();
    Endpoint host = mapper.readValue(input, Endpoint.class);
    // String asText = mapper.writeValueAsString(host);

    // add this
    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    String asText = ow.writeValueAsString(host);
    //

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

Body:
I would like to convert a Java Properties file into JSON with nested objects. I followed an example I found here but I can't get it to work.

For example, given:

objectA.version=1.0
objectA.hostname=192.168.0.11
objectA.port=9989
objectB.hostname=10.0.2.15
objectB.port=9998

I want:

{
  “objectA” : {
             "version” : "1.0"
             "host” : “192.168.0.11”,
             "port" : 9989
           },
  “objectB” : {
             "host” : “10.0.2.15”,
             "port" : 9998
           }
}

This is what I have so far:

static class Endpoint
{
    @JsonProperty("objectA")
    public ObjectA objectA;

    @JsonProperty("objectB")
    public ObjectB objectB;

}
static class ObjectA
{
    public String hostname;
    public String port;
    public String version;
}

static class ObjectB
{
    public String hostname;
    public String port;
}

try (InputStream input = getClass().getClassLoader().getResourceAsStream("file.properties"))
{
    JavaPropsMapper mapper = new JavaPropsMapper();
    Endpoint host = mapper.readValue(input, Endpoint.class);
    String asText = mapper.writeValueAsString(host);
    System.out.println(asText);
}

The output looks like this:

objectA.version=1.0
objectA.hostname=192.168.0.11
objectA.port=9989
objectB.hostname=10.0.2.15
objectB.port=9998

Body:
I figured it out.

try (InputStream input = getClass().getClassLoader().getResourceAsStream("file.properties"))
{
    JavaPropsMapper mapper = new JavaPropsMapper();
    Endpoint host = mapper.readValue(input, Endpoint.class);
    // String asText = mapper.writeValueAsString(host);

    // add this
    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    String asText = ow.writeValueAsString(host);
    //

    System.out.println(asText);
}


问:
My ASP.NET Application - Drives me crazy, can't remove it
So I edited:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        #AboutMeSection {
            border-right: 1px dashed #333;
                min-height:100px;
                height:100px;
        }

    </style>
    <title>@ViewBag.Title - Adam Kościelniak</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("//tinymce.cachefly.net/4.0/tinymce.min.js")
    <script>
    tinymce.init({ selector: 'textarea' });
    </script>

</head>
</code>```

of _Layout.cshtml

in the view I simply do:

```<code>@model KoscielniakInfo.ViewModels.CV
@{
    ViewBag.Title = "My Virtual CV";
}
</code>```

Even changed the _ViewStart.cshtml so it explicitly changes it:

```<code>@{
    ViewBag.Title = "Adam Kościelniak Homepage";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
</code>```

NOTHING still after a 10 deploys I go to my domain:
adamkoscielniak.pl
and see this:

Where else can I change this? What am I missing?
The full project is on github...
https://github.com/Tackgnol/KoscielniakInfo

Web Deploy Screenshot:

答:
I am sure this is coming from _Layout.cshtml

```<code><title>@ViewBag.Title - My ASP.NET Application</title>
</code>```

Make some changes in the file and try publishing again (add some dummy text). Because unchanged file will be skipped when you are deploying.

Body:
So I edited:

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>@ViewBag.Title - Adam Kościelniak</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("//tinymce.cachefly.net/4.0/tinymce.min.js")

of _Layout.cshtml

in the view I simply do:

@model KoscielniakInfo.ViewModels.CV
@{
    ViewBag.Title = "My Virtual CV";
}

Even changed the _ViewStart.cshtml so it explicitly changes it:

@{
    ViewBag.Title = "Adam Kościelniak Homepage";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

NOTHING still after a 10 deploys I go to my domain:
adamkoscielniak.pl
and see this:

Where else can I change this? What am I missing?
The full project is on github...
https://github.com/Tackgnol/KoscielniakInfo

Web Deploy Screenshot:

Body:
I am sure this is coming from _Layout.cshtml

<title>@ViewBag.Title - My ASP.NET Application</title>

Make some changes in the file and try publishing again (add some dummy text). Because unchanged file will be skipped when you are deploying.


问:
Why create a table is faster than update a field?
if I create a new table with one week data is 30 seconds faster:

```<code>-- Executing query:
CREATE TABLE avl_tracker.avl2 as
SELECT *  -- here can change the has_link to false
FROM avl_tracker.avl
Query returned successfully: 6998969 rows affected, 52587 ms execution time.
</code>```

Than just update one day, even when there is one index for event_time:

```<code>-- Executing query:
UPDATE avl_tracker.avl
SET  has_link = false
WHERE event_time >= '2017-06-16 00:00:00'::timestamp without time zone
  AND event_time <  '2017-06-17 00:00:00'::timestamp without time zone
Query returned successfully: 1646479 rows affected, 84109 ms execution time.
</code>```

And recreate the index on the new table doesnt take 30 seconds

Is there something I should check? Im doing something wrong?

答:
It is to be expected that it is faster to insert data on a table without index and then create the index than to update the same amount of data on a table with an index.

Index maintenance is expensive.

Body:
if I create a new table with one week data is 30 seconds faster:

-- Executing query:
CREATE TABLE avl_tracker.avl2 as
SELECT *  -- here can change the has_link to false
FROM avl_tracker.avl
Query returned successfully: 6998969 rows affected, 52587 ms execution time.

Than just update one day, even when there is one index for event_time:

-- Executing query:
UPDATE avl_tracker.avl
SET  has_link = false
WHERE event_time >= '2017-06-16 00:00:00'::timestamp without time zone
  AND event_time <  '2017-06-17 00:00:00'::timestamp without time zone
Query returned successfully: 1646479 rows affected, 84109 ms execution time.

And recreate the index on the new table doesnt take 30 seconds

Is there something I should check? Im doing something wrong?


问:
How to track users without authentication on nodeJS
I developed a mobile web application using nodeJS. All users have an access to data(foods,menus etc) without authentication. They can list products, like them, or mark them as a favorite ..etc What I want is giving them unique IDs (on first visit) to recognize them on every time they visit and track their actions by storing those actions in my database I want that because when they are revisit my app, I'm gonna say
"You have marked 3 products as a favorite this month!" or
"Apperantly you like hamburgers (listed hamburger category 22 times)

In short, when user visiting my web app for the first time

Define (or assign) unique ID and store the ID on client-side

when user visiting my web app second time

Check if there is any ID on client-side storage

If its true then list the users recent activities for example;

```<code>var uID = "ID data on client-side."
db.users.findOne({ userID: uID }, function(err, user){
   if(err){
   res.send("you are here for the first time!");
   // >>> create new unique ID HERE and assign it to the user !!<<<
 } else {
   res.send("you were here before");
   // already have an ID, go on
    }
})
</code>```

Quick Note: ID must be there all the time (on client-side) until user remove it somehow.

答:
If this is a browser-based application, then you have two main options, cookies and local storage. Both are not entirely permanent (can be cleared by user or by browser maintenance), but will generally serve your purpose.

The advantage of cookies is that they will be automatically shared with the server on every request so the server can tell who the user is.

The disadvantage of not using a user login is that the same user cannot represent themselves as themself on different devices or if they get a new device (such as switch to a new phone).

If you are using Express on the server, then you can use express-session combined with a persistent session store and then express-session will automatically create the cookie and you can store whatever user-specific data you want in the session and it will persist for as long as the cookie lasts (actually the data will last longer, but you can only associate it with the user as long as the cookie lasts).  This would also allow you to "extend" your functionality in the future by support a non-login world, but also to allow the user to add a login so they could even access their info from other devices.

Body:
I developed a mobile web application using nodeJS. All users have an access to data(foods,menus etc) without authentication. They can list products, like them, or mark them as a favorite ..etc What I want is giving them unique IDs (on first visit) to recognize them on every time they visit and track their actions by storing those actions in my database I want that because when they are revisit my app, I'm gonna say
"You have marked 3 products as a favorite this month!" or
"Apperantly you like hamburgers (listed hamburger category 22 times)

In short, when user visiting my web app for the first time

Define (or assign) unique ID and store the ID on client-side

when user visiting my web app second time

Check if there is any ID on client-side storage

If its true then list the users recent activities for example;

var uID = "ID data on client-side."
db.users.findOne({ userID: uID }, function(err, user){
   if(err){
   res.send("you are here for the first time!");
   // >>> create new unique ID HERE and assign it to the user !!<<<
 } else {
   res.send("you were here before");
   // already have an ID, go on
    }
})

Quick Note: ID must be there all the time (on client-side) until user remove it somehow.


问:
How check why I can't send xml file using eBay API?
I am sending xml files using Bulk Sell and I have success on start processing file but job status is failed:

Failed: the Bulk Data Exchange job has not completed successfully, due to incorrect data format, request errors, or Bulk Data Exchange API errors.

I checked my xml code is not hidden chars in ansi etc. Maybe i need add more requeried files. Or maybe someone knows some tools to check XML format on ebay

```<code><?xml version="1.0" encoding="UTF-8"?>
<BulkDataExchangeRequests xmlns="urn:ebay:apis:eBLBaseComponents">
  <Header>
    <Version>1019</Version>
    <SiteID>UK</SiteID>
  </Header>
<AddFixedPriceItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">
  <ErrorLanguage>en_GB</ErrorLanguage>
  <WarningLevel>High</WarningLevel>
  <Version>1019</Version>
  <Item>
    <Title>My ebay title</Title>
    <Description>Test description</Description>
    <PrimaryCategory>
      <CategoryID>42899</CategoryID>
    </PrimaryCategory>
    <StartPrice>96.00</StartPrice>
    <CategoryMappingAllowed>true</CategoryMappingAllowed>
    <ConditionID>1000</ConditionID>
    <Country>GB</Country>
    <Currency>GBP</Currency>
    <DispatchTimeMax>2</DispatchTimeMax>
    <ListingDuration>Days_7</ListingDuration>
    <ListingType>FixedPriceItem</ListingType>
    <PaymentMethods>PayPal</PaymentMethods>
    <PayPalEmailAddress>abc@abc.com</PayPalEmailAddress>
    <PictureDetails>
    <GalleryType>Gallery</GalleryType>
      <PictureURL>link to pictures</PictureURL>
    </PictureDetails>
    <PostalCode>abc def</PostalCode>
    <ProductListingDetails>
      <BrandMPN>
        <Brand>New brand</Brand>
        <MPN>ASM/KKD</MPN>
      </BrandMPN>
    </ProductListingDetails>
    <Quantity>1</Quantity>
    <ReturnPolicy>
      <ReturnsAcceptedOption>ReturnsAccepted</ReturnsAcceptedOption>
      <ReturnsWithinOption>Days_14</ReturnsWithinOption>
      <ShippingCostPaidByOption>Buyer</ShippingCostPaidByOption>
    </ReturnPolicy>
    <Site>UK</Site>
  </Item>
</AddFixedPriceItemRequest>
</BulkDataExchangeRequests>
</code>```

答: Have you checked that you haven't set your data format (REQUEST-DATA-FORMAT) to JSON, it may be expecting another format to the one you are sending. Basing this  from the error responce you posted "due to incorrect data format".</p>

Body:
I am sending xml files using Bulk Sell and I have success on start processing file but job status is failed:

Failed: the Bulk Data Exchange job has not completed successfully, due to incorrect data format, request errors, or Bulk Data Exchange API errors.

I checked my xml code is not hidden chars in ansi etc. Maybe i need add more requeried files. Or maybe someone knows some tools to check XML format on ebay

<?xml version="1.0" encoding="UTF-8"?>
<BulkDataExchangeRequests xmlns="urn:ebay:apis:eBLBaseComponents">

    <Version>1019</Version>
    <SiteID>UK</SiteID>

<AddFixedPriceItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">
  <ErrorLanguage>en_GB</ErrorLanguage>
  <WarningLevel>High</WarningLevel>
  <Version>1019</Version>
  <Item>
    <Title>My ebay title</Title>
    <Description>Test description</Description>
    <PrimaryCategory>
      <CategoryID>42899</CategoryID>
    </PrimaryCategory>
    <StartPrice>96.00</StartPrice>
    <CategoryMappingAllowed>true</CategoryMappingAllowed>
    <ConditionID>1000</ConditionID>
    <Country>GB</Country>
    <Currency>GBP</Currency>
    <DispatchTimeMax>2</DispatchTimeMax>
    <ListingDuration>Days_7</ListingDuration>
    <ListingType>FixedPriceItem</ListingType>
    <PaymentMethods>PayPal</PaymentMethods>
    <PayPalEmailAddress>abc@abc.com</PayPalEmailAddress>
    <PictureDetails>
    <GalleryType>Gallery</GalleryType>
      <PictureURL>link to pictures</PictureURL>
    </PictureDetails>
    <PostalCode>abc def</PostalCode>
    <ProductListingDetails>
      <BrandMPN>
        <Brand>New brand</Brand>
        <MPN>ASM/KKD</MPN>
      </BrandMPN>
    </ProductListingDetails>
    <Quantity>1</Quantity>
    <ReturnPolicy>
      <ReturnsAcceptedOption>ReturnsAccepted</ReturnsAcceptedOption>
      <ReturnsWithinOption>Days_14</ReturnsWithinOption>
      <ShippingCostPaidByOption>Buyer</ShippingCostPaidByOption>
    </ReturnPolicy>
    <Site>UK</Site>
  </Item>
</AddFixedPriceItemRequest>
</BulkDataExchangeRequests>


问:
Changing type in abap
I have an internal table of type string.

```<code>it_fields TYPE STANDARD TABLE OF string
</code>```

Inside this there are some values which I need to parse and then store it in it_final.

```<code>it_final TYPE STANDARD TABLE OF dd03l-fieldname
</code>```

dd03l has a column name field name with datatype char 30.

Is parsing possible in ABAP?

答:
```<code>DATA: ls_final like line of it_final.
LOOP at it_fields into data(lv_field).
   ls_final = lv_field.
   APPEND ls_final TO it_final.
   CLEAR:ls_final .
ENDLOOP.
</code>```

This one works too, i guess.

Title: Changing type in abap

Body:
I have an internal table of type string.

it_fields TYPE STANDARD TABLE OF string

Inside this there are some values which I need to parse and then store it in it_final.

it_final TYPE STANDARD TABLE OF dd03l-fieldname

dd03l has a column name field name with datatype char 30.

Is parsing possible in ABAP?

Body:
DATA: ls_final like line of it_final.
LOOP at it_fields into data(lv_field).
   ls_final = lv_field.
   APPEND ls_final TO it_final.
   CLEAR:ls_final .
ENDLOOP.

This one works too, i guess.


问:
Access Violation when starting debug
I added an event handler to one of my forms. Nothing complicated, only a textbox click event and .Text property set. Now when I try to run my application, everything still complies and starts to run for a second or two but then debugging just stops. This is in my debug output:

```<code>Exception thrown: 'System.Threading.WaitHandleCannotBeOpenedException' in mscorlib.dll
SIOS Open Failed
ReadProperty<T>(CalibrationFile)
Exception thrown: 'System.NotImplementedException' in myappname.exe
The program '[3300] myappname.vshost.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'.
</code>```

I did some googling and the only thing that I found that makes any sense at all was someone who'se antivirus was interfering and causing a similar problem. Has anyone seen this before? I'm not running any antivirus aside from whatever Windows has on it's own.

Something to note: Visual Studio is running as Administrator. (hardware controllers that could break expensive equipment if this isn't the case) Now, this doesn't matter during debug as this hardware isn't actually connected but the check will not let the application run if it is not "as administrator."

答:
You seem to have a line of code containing throw new System.NotImplementedException();.

Find that line, then put something useful there instead.

Title: Access Violation when starting debug

Body:
I added an event handler to one of my forms. Nothing complicated, only a textbox click event and .Text property set. Now when I try to run my application, everything still complies and starts to run for a second or two but then debugging just stops. This is in my debug output:

Exception thrown: 'System.Threading.WaitHandleCannotBeOpenedException' in mscorlib.dll
SIOS Open Failed
ReadProperty<T>(CalibrationFile)
Exception thrown: 'System.NotImplementedException' in myappname.exe
The program '[3300] myappname.vshost.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'.

I did some googling and the only thing that I found that makes any sense at all was someone who'se antivirus was interfering and causing a similar problem. Has anyone seen this before? I'm not running any antivirus aside from whatever Windows has on it's own.

Something to note: Visual Studio is running as Administrator. (hardware controllers that could break expensive equipment if this isn't the case) Now, this doesn't matter during debug as this hardware isn't actually connected but the check will not let the application run if it is not "as administrator."


问:
How to store in file outputs of a c/c++ program in unix
I have a program made on c++, let's call it program, which has a lot of output while running. I want to log that output on a file so is easier then to look at it. I tried already ./program & > file ./program & |tee file but it doesnt work (I want to run it in background if posible).

any idea?

Thanks

EDIT: It doesnt work ./program > file. I tried putting it on background, on foreground, but the file is empty....

答:
You might try

```<code> program >& somefile &
</code>```

then ending & means you want to put that job in the background and (with bash or zsh) the >& redirects both stdout and stderr

Then you could use tail -f somefile (perhaps in a different terminal window) to look at that growing somefile. See tail(1)

BTW, there are other possibilities. Look perhaps into batch command (you may need to install the at package to have it) and into nohup(1).

Body:
You might try

 program >& somefile &

then ending & means you want to put that job in the background and (with bash or zsh) the >& redirects both stdout and stderr

Then you could use tail -f somefile (perhaps in a different terminal window) to look at that growing somefile. See tail(1)

BTW, there are other possibilities. Look perhaps into batch command (you may need to install the at package to have it) and into nohup(1).


问:
How create menu automaticaly by php

 tag with nested set model
I see nested set model method for create hierarchy category in database with MYSQL in this page :

mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

But i didn't understand how can i make nested list for site category menu with these mysql result.

For example if , my table is like this :

```<code>+-------------+----------------------+-----+-----+
| category_id | name                 | lft | rgt |
+-------------+----------------------+-----+-----+
|           1 | ELECTRONICS          |   1 |  20 |
|           2 | TELEVISIONS          |   2 |   9 |
|           3 | TUBE                 |   3 |   4 |
|           4 | LCD                  |   5 |   6 |
|           5 | PLASMA               |   7 |   8 |
|           6 | PORTABLE ELECTRONICS |  10 |  19 |
|           7 | MP3 PLAYERS          |  11 |  14 |
|           8 | FLASH                |  12 |  13 |
|           9 | CD PLAYERS           |  15 |  16 |
|          10 | 2 WAY RADIOS         |  17 |  18 |
+-------------+----------------------+-----+-----+
</code>```

I want make category menu with php and

 automaticaly.

答:
just get all the categories on mysql with a query like:

```<code>"SELECT name from category"
</code>```

don't know if you are using PDO or any other any driver like mysqli, I assume the table's name is called category.
set the content to a variable and loop through it.

```<code><ul>
    <?php  foreach ($categories as $category): ?>
        <li><?=$category ?></li>
    <?php endforeach; ?>;
</ul>
</code>```

Title: How create menu automaticaly by php <ul> <li> tag with nested set model

Body:
I see nested set model method for create hierarchy category in database with MYSQL in this page :

mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

But i didn't understand how can i make nested list for site category menu with these mysql result.

For example if , my table is like this :

+-------------+----------------------+-----+-----+
| category_id | name                 | lft | rgt |
+-------------+----------------------+-----+-----+
|           1 | ELECTRONICS          |   1 |  20 |
|           2 | TELEVISIONS          |   2 |   9 |
|           3 | TUBE                 |   3 |   4 |
|           4 | LCD                  |   5 |   6 |
|           5 | PLASMA               |   7 |   8 |
|           6 | PORTABLE ELECTRONICS |  10 |  19 |
|           7 | MP3 PLAYERS          |  11 |  14 |
|           8 | FLASH                |  12 |  13 |
|           9 | CD PLAYERS           |  15 |  16 |
|          10 | 2 WAY RADIOS         |  17 |  18 |
+-------------+----------------------+-----+-----+

I want make category menu with php and

 automaticaly.

Body:
just get all the categories on mysql with a query like:

"SELECT name from category"

don't know if you are using PDO or any other any driver like mysqli, I assume the table's name is called category.
set the content to a variable and loop through it.

<ul>
    <?php  foreach ($categories as $category): ?>
        <li><?=$category ?></li>
    <?php endforeach; ?>;
</ul>


问:
How to query multi values of enum field in ActiveRecord?
mymodel.rb

```<code>enum status: { posted: 1, failed: 2, suspended: 3 }
</code>```

mycontroller.rb

```<code>def filter_params
  params.fetch(:mymodel, {}).
  permit(
    :status => []
    )
end
</code>```

And i have params like mymodel[:status] => ["failed", "suspended"]

How can i get all results by status is failed and suspended

Something like: Mymodel.where(status: filter_params[:status])

Thanks a lot!

And when a call:

```<code>@mymodel = Mymodel.new(filter_params)
</code>```

I got this error:

```<code>'["failed", "suspended"]' is not a valid status
</code>```

答:
In Rails 5 you can now pass a string array to the query, e.g:

```<code>Mymodel.where(status: ['failed', 'suspended'])
</code>```

For earlier versions, just convert your array values to symbols:

```<code>statuses = filter_params[:status].map(&:to_sym)
Mymodel.where(status: statuses)
</code>```

Body:
mymodel.rb

enum status: { posted: 1, failed: 2, suspended: 3 }

mycontroller.rb

def filter_params
  params.fetch(:mymodel, {}).
  permit(
    :status => []
    )
end

And i have params like mymodel[:status] => ["failed", "suspended"]

How can i get all results by status is failed and suspended

Something like: Mymodel.where(status: filter_params[:status])

Thanks a lot!

And when a call:

@mymodel = Mymodel.new(filter_params)

I got this error:

'["failed", "suspended"]' is not a valid status

Body:
In Rails 5 you can now pass a string array to the query, e.g:

Mymodel.where(status: ['failed', 'suspended'])

For earlier versions, just convert your array values to symbols:

statuses = filter_params[:status].map(&:to_sym)
Mymodel.where(status: statuses)


问:
Add gutter on masonry with the bootstrap3 grid
I'm having trouble with coding gutter on masonry with the bootstrap3 grid.

This is my jsfiddle.   https://jsfiddle.net/shelly_W/bg67fdjm/

```<code><div class="container bg">
<h1>Masonry - Bootstrap 3 grid media queries</h1>
<!-- add extra container element for Masonry -->
<div class="grid">
<div class="grid-sizer col-xs-6 col-sm-4"></div>
<div class="grid-item col-xs-12 col-sm-8 col-md-8 ">
<!-- add inner element for column content -->
<div class="grid-item-content grid-item-content--height400">1</div>
</div>
<div class="grid-item col-xs-12 col-sm-4 col-md-4">
<div class="grid-item-content grid-item-content--height230">2</div>
</div>
<div class="grid-item col-xs-12 col-sm-4 col-md-4">
<div class="grid-item-content grid-item-content--height443">3</div>
</div>
<div class="grid-item col-xs-12 col-sm-4 col-md-4">
<div class="grid-item-content grid-item-content--height230">4</div>
</div>
<div class="grid-item col-xs-12 col-sm-4 col-md-4">
<div class="grid-item-content grid-item-content--height518">5</div>
</div>
<div class="grid-item col-xs-12 col-sm-4 col-md-4">
<div class="grid-item-content grid-item-content--height518">6</div>
</div>
<div class="grid-item col-xs-12 col-sm-4 col-md-4">
<div class="grid-item-content grid-item-content--height230">7</div>
</div>
<div class="grid-item col-xs-12 col-sm-8 col-md-8">
<div class="grid-item-content grid-item-content--height230">8</div>
</div>
</div>
</code>```

Source is: https://masonry.desandro.com/

What I’m trying to achieve is having 15px gutters between the masonry grid. I want to create a space between grid 1 and grid 2. I don’t want padding on either of the outer container div edges of grid 1 or grid 2.
I attempted to insert a 15px gutter by js, but this approach breaks the bootstrap responsive columns.

I’ve been trying to work this out for some time, but I can't figure out the right approach. Does anyone have any suggestions on how I might resolve this issue?

Please let me know if you need any further information.
Thank you in advance for your help!

答:
All you have to do is remove your current padding declarations on your .grid-size selector and use margin-bottom instead.

```<code>.grid-size {
    margin-bottom: 4%;
}
</code>```

You can use a static value if you'd prefer; I used it a percentage here because you're going for a responsive design.

Here you can see your fiddle updated and in action.

Body:
I'm having trouble with coding gutter on masonry with the bootstrap3 grid.

This is my jsfiddle.   https://jsfiddle.net/shelly_W/bg67fdjm/

Masonry - Bootstrap 3 grid media queries

1

2

3

4

5

6

7

8

Source is: https://masonry.desandro.com/

What I’m trying to achieve is having 15px gutters between the masonry grid. I want to create a space between grid 1 and grid 2. I don’t want padding on either of the outer container div edges of grid 1 or grid 2.
I attempted to insert a 15px gutter by js, but this approach breaks the bootstrap responsive columns.

I’ve been trying to work this out for some time, but I can't figure out the right approach. Does anyone have any suggestions on how I might resolve this issue?

Please let me know if you need any further information.
Thank you in advance for your help!

Body:
All you have to do is remove your current padding declarations on your .grid-size selector and use margin-bottom instead.

.grid-size {
    margin-bottom: 4%;
}

You can use a static value if you'd prefer; I used it a percentage here because you're going for a responsive design.

Here you can see your fiddle updated and in action.


答:
```<code>UPDATE [TableA]
SET [ColumnB] = 'y'
WHERE [ColumnB] = 'x'
</code>```

Title: SQL Update Statement for all values of column when value equals certain value

Body:
How would I update all row values of a SQL table in a column when the value equals a certain value?

For Example (TableA):

ColumnA | ColumnB | ColumnC
---------------------------
a       | b       | c
a       | x       | c
a       | x       | c
a       | x       | c
a       | b       | c
a       | b       | c

I would I rename all x in ColumnB to y?


问:
Resizing a Webbrowser control hosted by an Explorer Bar in IE
I have a custom explorer bar (a band object) that hosts a webbrowser control. I can initialize the WebBrowser control properly and have it display web pages.

However, I've noticed that when I resize the explorer bar, the webbrowser control doesn't resize appropriately to the size of the bar:

Before Resize:

After Resize:

I'm not sure what events I need to handle and what can resize the browser control. I have some experience in .NET programming, and none really in Windows programming.

I've also included my source code here if you would like to poke aorund it more.

答: Typically, when a container hosting an OLE control is resized, it queries the embedded object for its IOleInPlaceObject interface, and uses the SetObjectRects() on that interface to tell the control its new size.</p>

OwnerDisplayName: Chris Becke


问:
Error in my PDO execute function
I have the following query:

```<code>SELECT case when card_type='A'  then name else  CONCAT_WS(' ',firstname,lastname)  end
                     as cname ,cardid,card_type,isDeck,userid_from,status,cards.gibid,message ,userid_to,description,tagline,gibs.preview_thumb
                    ,case when  userid_from=userid_to then 'my card ' else 'other 'end as owner
            FROM cards LEFT JOIN gibs ON gibs.gibid=cards.gibid
                left join users on users.userid=cards.userid_from
            WHERE userid_to=? and cards.deleted='N'  and (case when card_type='A'  then name else  CONCAT_WS(' ',firstname,lastname)  end)  like '%?%'
            order by status,card_type desc,owner,cname,isDeck desc
</code>```

and array passed in execute function is :

```<code>Array
(
    [0] => 1
    [1] => rahul
)
</code>```

it is giving me error ..

```<code>Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in /var/www/ryapi/Db.php on line 176

Fatal error: Uncaught exception 'PDOException' with message 'Database error [HY093]: , driver error code is ' in /var/www/ryapi/Db.php:179
Stack trace:
#0 /var/www/ryapi/Db.php(93): Db::_query('SELECT case whe...', Array)
#1 /var/www/ryapi/card.php(152): Db::getResult('SELECT case whe...', Array)
#2 /var/www/ryapi/index.php(103): Card->getcardlist('1', '', 'rahul')
#3 {main}
  thrown in /var/www/ryapi/Db.php on line 179
</code>```

why this error is coming please suggest.

答:
```<code>CONCAT_WS(' ',firstname,lastname)  end)  like '%?%'
</code>```

Here, '%?%' is not a pdo param.
You should make it:

```<code>CONCAT_WS(' ',firstname,lastname)  end)  like ?
</code>```

Then bind:

```<code>Array
(
    [0] => 1
    [1] => '%rahul%'
)
</code>```

Title: Error in my PDO execute function

Body:
I have the following query:

SELECT case when card_type='A'  then name else  CONCAT_WS(' ',firstname,lastname)  end
                     as cname ,cardid,card_type,isDeck,userid_from,status,cards.gibid,message ,userid_to,description,tagline,gibs.preview_thumb
                    ,case when  userid_from=userid_to then 'my card ' else 'other 'end as owner
            FROM cards LEFT JOIN gibs ON gibs.gibid=cards.gibid
                left join users on users.userid=cards.userid_from
            WHERE userid_to=? and cards.deleted='N'  and (case when card_type='A'  then name else  CONCAT_WS(' ',firstname,lastname)  end)  like '%?%'
            order by status,card_type desc,owner,cname,isDeck desc

and array passed in execute function is :

Array
(
    [0] => 1
    [1] => rahul
)

it is giving me error ..

Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in /var/www/ryapi/Db.php on line 176

Fatal error: Uncaught exception 'PDOException' with message 'Database error [HY093]: , driver error code is ' in /var/www/ryapi/Db.php:179
Stack trace:
#0 /var/www/ryapi/Db.php(93): Db::_query('SELECT case whe...', Array)
#1 /var/www/ryapi/card.php(152): Db::getResult('SELECT case whe...', Array)
#2 /var/www/ryapi/index.php(103): Card->getcardlist('1', '', 'rahul')
#3 {main}
  thrown in /var/www/ryapi/Db.php on line 179

why this error is coming please suggest.

Body:
CONCAT_WS(' ',firstname,lastname)  end)  like '%?%'

Here, '%?%' is not a pdo param.
You should make it:

CONCAT_WS(' ',firstname,lastname)  end)  like ?

Then bind:

Array
(
    [0] => 1
    [1] => '%rahul%'
)


问:
How to get dynamic short link that the user clicked on, in Firebase Android?
I have created a dynamic link in Firebase console. It has a short url that directs the user to an Activity inside the application.

I have done the same in iOS, using the code:

```<code> func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool
{

    if let incomingUrl = userActivity.webpageURL
    {
     print(incomingUrl) //Here I get the url that the user clicked on
    }
}
</code>```

I'm trying to get the exact output in Android when the user clicks on the dynamic short link.
Currently, I have :

```<code>       FirebaseDynamicLinks.getInstance()
             .getDynamicLink(getIntent())
            .addOnSuccessListener(this, new OnSuccessListener<PendingDynamicLinkData>() {
                @Override
                public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) {
                    // Get deep link from result (may be null if no link is found)
                    Uri deepLink = null;
                    if (pendingDynamicLinkData != null)
                    {
                        deepLink = pendingDynamicLinkData.getLink();

                    }

                    // Handle the deep link. For example, open the linked
                    // content, or apply promotional credit to the user's
                    // account.
                    // ...

                    // ...
                }
            })
            .addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.w(TAG, "getDynamicLink:onFailure", e);
                }
            });
</code>```

Here, I can get the deep link, I have no clear idea of fetching the short link in Android.

Thank you.

答:
You are misunderstanding the way platforms like Dynamic Links and Branch.io (full disclosure: I'm on the Branch team) work. Your Android implementation is correct — the iOS one is wrong. You'll want to review the Dynamic Links setup guide for iOS to make sure you're all set.

One of the major benefits of using hosted deep links is you don't need the actual URL the user clicked. There are two good reasons for this:

The URL is never available for the deferred deep link use case (when the app isn't already installed).

The URL arrives differently when the app is opened via Universal Links/App Links than via custom URI scheme.

The hosted link platform abstracts those technical details away, so that you can implement your own functionality without worrying about them. If you try to bypass the intended usage, it actually makes things much harder.

Body:
I have created a dynamic link in Firebase console. It has a short url that directs the user to an Activity inside the application.

I have done the same in iOS, using the code:

 func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool
{

    if let incomingUrl = userActivity.webpageURL
    {
     print(incomingUrl) //Here I get the url that the user clicked on
    }
}

I'm trying to get the exact output in Android when the user clicks on the dynamic short link.
Currently, I have :

       FirebaseDynamicLinks.getInstance()
             .getDynamicLink(getIntent())
            .addOnSuccessListener(this, new OnSuccessListener<PendingDynamicLinkData>() {
                @Override
                public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) {
                    // Get deep link from result (may be null if no link is found)
                    Uri deepLink = null;
                    if (pendingDynamicLinkData != null)
                    {
                        deepLink = pendingDynamicLinkData.getLink();

                    }

                    // Handle the deep link. For example, open the linked
                    // content, or apply promotional credit to the user's
                    // account.
                    // ...

                    // ...
                }
            })
            .addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.w(TAG, "getDynamicLink:onFailure", e);
                }
            });

Here, I can get the deep link, I have no clear idea of fetching the short link in Android.

Thank you.


问:
Incremental unique identifier in excel
I'm trying to set sheet up with an automatically generated unique reference number. The following array formula has worked well in providing a unique number, as well as adding an initial string of text "410-" to the begging when a drop down is triggered in column P, producing an output is similar to "401-00001" etc.

```<code>=arrayformula( if( len(P2:P), "410-" & text(row(A2:A) - row(C2) + 1, "00000"), iferror(1/0) ) )
</code>```

However, the limitation of the above is that it does not scan the column and continue sequentially from the last used number, it just assigns a number based on the row used. I need the unique reference numbers to be assigned in the order they are activated, which won't necessarily be in a sorted order in the sheet.

How can I adapt this formula to identify the largest number and add one, while keeping the same formatting etc?

(Similar to using a function such as =ArrayFormula(MAX((A2:A)+1)) )

Any help would be greatly appreciated

答:
The function similar to

=ArrayFormula(MAX((A2:A)+1)))

would be

=arrayformula("410-" & text(max(value(right(A$2:A,5)))+1,"00000"))

and this would create the next unique identifier.  The problem you have is that you can't use A$2:A in the same column as your list of unique IDs as it will create a circular reference and produce an error.

You can use

A$2:A2 in cells A3 and fill down but even when you surround this with an if statement, if column P has a value, it will still renumber the IDs according to their position on the sheet.

While it is useful to have a formula to generate the ID, the ID needs to be fixed once it has been generated.

You could put the formula that generates the next ID at the top of your sheet and copy and paste values when required.

Maybe use a google script to copy the value automatically onchange in column P

Title: Incremental unique identifier in excel

Body:
I'm trying to set sheet up with an automatically generated unique reference number. The following array formula has worked well in providing a unique number, as well as adding an initial string of text "410-" to the begging when a drop down is triggered in column P, producing an output is similar to "401-00001" etc.

=arrayformula( if( len(P2:P), "410-" & text(row(A2:A) - row(C2) + 1, "00000"), iferror(1/0) ) )

However, the limitation of the above is that it does not scan the column and continue sequentially from the last used number, it just assigns a number based on the row used. I need the unique reference numbers to be assigned in the order they are activated, which won't necessarily be in a sorted order in the sheet.

How can I adapt this formula to identify the largest number and add one, while keeping the same formatting etc?

(Similar to using a function such as =ArrayFormula(MAX((A2:A)+1)) )

Any help would be greatly appreciated


问:
Strange error during running GWT 2.7 in DevMode
What is wrong?

I founded some discussion about it but without solution
https://plus.googleapis.com/communities/116543000751323604177/stream/1cf77106-8055-472e-abb2-ac58a512b663

```<code>09:43:36.128 [ERROR] [MyApplication] Exception initializing module
java.lang.IllegalArgumentException: null
    at org.objectweb.asm.ClassVisitor.<init>(Unknown Source)
    at org.objectweb.asm.ClassVisitor.<init>(Unknown Source)
    at com.google.gwt.dev.javac.BytecodeSignatureMaker$CompileDependencyVisitor.<init>(BytecodeSignatureMaker.java:59)
    at com.google.gwt.dev.javac.BytecodeSignatureMaker.visitCompileDependenciesInBytecode(BytecodeSignatureMaker.java:227)
    at com.google.gwt.dev.javac.BytecodeSignatureMaker.getCompileDependencySignature(BytecodeSignatureMaker.java:209)
    at com.google.gwt.dev.javac.CompiledClass.getSignatureHash(CompiledClass.java:166)
    at com.google.gwt.dev.javac.Dependencies$Ref.<init>(Dependencies.java:42)
    at com.google.gwt.dev.javac.Dependencies$Ref.<init>(Dependencies.java:37)
    at com.google.gwt.dev.javac.Dependencies.resolve(Dependencies.java:114)
    at com.google.gwt.dev.javac.CompilationStateBuilder$CompileMoreLater.compile(CompilationStateBuilder.java:366)
    at com.google.gwt.dev.javac.CompilationStateBuilder.doBuildFrom(CompilationStateBuilder.java:580)
    at com.google.gwt.dev.javac.CompilationStateBuilder.buildFrom(CompilationStateBuilder.java:513)
    at com.google.gwt.dev.javac.CompilationStateBuilder.buildFrom(CompilationStateBuilder.java:499)
    at com.google.gwt.dev.cfg.ModuleDef.getCompilationState(ModuleDef.java:668)
    at com.google.gwt.dev.DevModeBase$UiBrowserWidgetHostImpl.createModuleSpaceHost(DevModeBase.java:101)
</code>```

答:
The classpath may have some misconfiguration. In my case, I had a 2.8 project that worked just fine, but newer projects had that stackt race for a some reason. I don't know what caused this, but the solution in my case was to change this part of the .classpath:

```<code>    <classpathentry kind="con" path="com.google.appengine.eclipse.core.GAE_CONTAINER/App Engine"/>
    <classpathentry kind="con" path="com.google.gwt.eclipse.core.GWT_CONTAINER"/>
</code>```

to:

```<code>   <classpathentry kind="con" path="com.google.appengine.eclipse.core.GAE_CONTAINER"/>
   <classpathentry kind="con" path="com.google.gwt.eclipse.core.GWT_CONTAINER/GWT"/>
</code>```

Body:
What is wrong?

I founded some discussion about it but without solution
https://plus.googleapis.com/communities/116543000751323604177/stream/1cf77106-8055-472e-abb2-ac58a512b663

09:43:36.128 [ERROR] [MyApplication] Exception initializing module
java.lang.IllegalArgumentException: null
    at org.objectweb.asm.ClassVisitor.<init>(Unknown Source)
    at org.objectweb.asm.ClassVisitor.<init>(Unknown Source)
    at com.google.gwt.dev.javac.BytecodeSignatureMaker$CompileDependencyVisitor.<init>(BytecodeSignatureMaker.java:59)
    at com.google.gwt.dev.javac.BytecodeSignatureMaker.visitCompileDependenciesInBytecode(BytecodeSignatureMaker.java:227)
    at com.google.gwt.dev.javac.BytecodeSignatureMaker.getCompileDependencySignature(BytecodeSignatureMaker.java:209)
    at com.google.gwt.dev.javac.CompiledClass.getSignatureHash(CompiledClass.java:166)
    at com.google.gwt.dev.javac.Dependencies$Ref.<init>(Dependencies.java:42)
    at com.google.gwt.dev.javac.Dependencies$Ref.<init>(Dependencies.java:37)
    at com.google.gwt.dev.javac.Dependencies.resolve(Dependencies.java:114)
    at com.google.gwt.dev.javac.CompilationStateBuilder$CompileMoreLater.compile(CompilationStateBuilder.java:366)
    at com.google.gwt.dev.javac.CompilationStateBuilder.doBuildFrom(CompilationStateBuilder.java:580)
    at com.google.gwt.dev.javac.CompilationStateBuilder.buildFrom(CompilationStateBuilder.java:513)
    at com.google.gwt.dev.javac.CompilationStateBuilder.buildFrom(CompilationStateBuilder.java:499)
    at com.google.gwt.dev.cfg.ModuleDef.getCompilationState(ModuleDef.java:668)
    at com.google.gwt.dev.DevModeBase$UiBrowserWidgetHostImpl.createModuleSpaceHost(DevModeBase.java:101)

Body:
The classpath may have some misconfiguration. In my case, I had a 2.8 project that worked just fine, but newer projects had that stackt race for a some reason. I don't know what caused this, but the solution in my case was to change this part of the .classpath:

    <classpathentry kind="con" path="com.google.appengine.eclipse.core.GAE_CONTAINER/App Engine"/>
    <classpathentry kind="con" path="com.google.gwt.eclipse.core.GWT_CONTAINER"/>

to:

   <classpathentry kind="con" path="com.google.appengine.eclipse.core.GAE_CONTAINER"/>
   <classpathentry kind="con" path="com.google.gwt.eclipse.core.GWT_CONTAINER/GWT"/>


问:
Error code 135, Error message Could not fingd update-config.json. Run webdriver-manager update to download the binaries
I am trying to execute my tests in nodejs using protractor.

Example protractor protractor.conf
When I run protractor protractor.conf, I get error  Error code 135, Error message Could not fingd update-config.json. Run webdriver-manager update to download the binaries

I ran the following command but still get the above error message

```<code>webdriver-manager update -- proxy http://
</code>```

protractor.conf.js

```<code>/*global jasmine */
var SpecReporter = require('jasmine-spec-reporter');
var TfsReporter = require('jasmine-tfs-reporter');

exports.config = {
  allScriptsTimeout: 11000,
  specs: [
    './src/tests/*spec.js'
  ],
  capabilities: {
    'browserName': 'chrome',
    /*'browserName': 'phantomjs',
    'phantomjs.binary.path': require('phantomjs-prebuilt').path,
    'phantomjs.ghostdriver.cli.args': ['--loglevel=DEBUG']*/
  },
  directConnect: true,
  baseUrl: 'http://localhost:4200/',
  framework: 'jasmine',
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000,
    print: function() {}
  },
  useAllAngular2AppRoots: false,
  beforeLaunch: function() {
    require('ts-node').register({
      project: '../PartyAndIndustryDataMigration'
    });
  },
  onPrepare: function() {
    jasmine.getEnv().addReporter(new SpecReporter());
    jasmine.getEnv().addReporter(new TfsReporter());
  }
};
</code>```

答:
I guess chrome driver & update-config.json couldn't downloaded at the time of webdriver-manager update.

Just for verification go to
  node_modules\protractor\node_modules\webdriver-manager\selenium\
  location and look if everything downloaded properly?

If there is problem on downloading chrome driver you can check chrome-response.xml in same location for reason. One reason could be chrome driver website is in blacklisted or behind the proxy.

Body:
I am trying to execute my tests in nodejs using protractor.

Example protractor protractor.conf
When I run protractor protractor.conf, I get error  Error code 135, Error message Could not fingd update-config.json. Run webdriver-manager update to download the binaries

I ran the following command but still get the above error message

webdriver-manager update -- proxy http://

protractor.conf.js

/*global jasmine */
var SpecReporter = require('jasmine-spec-reporter');
var TfsReporter = require('jasmine-tfs-reporter');

exports.config = {
  allScriptsTimeout: 11000,
  specs: [
    './src/tests/*spec.js'
  ],
  capabilities: {
    'browserName': 'chrome',
    /*'browserName': 'phantomjs',
    'phantomjs.binary.path': require('phantomjs-prebuilt').path,
    'phantomjs.ghostdriver.cli.args': ['--loglevel=DEBUG']*/
  },
  directConnect: true,
  baseUrl: 'http://localhost:4200/',
  framework: 'jasmine',
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000,
    print: function() {}
  },
  useAllAngular2AppRoots: false,
  beforeLaunch: function() {
    require('ts-node').register({
      project: '../PartyAndIndustryDataMigration'
    });
  },
  onPrepare: function() {
    jasmine.getEnv().addReporter(new SpecReporter());
    jasmine.getEnv().addReporter(new TfsReporter());
  }
};


问:
Column limit in H2O data frame?
I am working with a data set in R which contains 42,457 rows and 785 columns.  The first column is a binary response variable (called label) and the remaining columns are binary features.

I tried to fit a logistic regression model using rsparkling  (described here) but got errors.  I traced this to a step that converts a Spark version of this table to an H2O data frame.

Here's the function I'm using for testing.  The Spark instance sc is up and running and df is the raw data set as a standard R data frame:

```<code>load_h2o <- function(df, rows = nrow(df), cols = ncol(df)) {
        df <- df[1:rows, 1:cols]
        copy_to(sc, df, "df", overwrite = TRUE)
        df_tbl <- tbl(sc, "df")
        h2o_tbl <- as_h2o_frame(sc, df_tbl, strict_version_check=FALSE)
        return(h2o_tbl)
}
</code>```

The head of df$label is 1 1 1 0 0 0.  However if I load the full data set, i.e. load_h2o(raw_data) the head of the resulting label column is 0 0 0 0 0 0; in fact all values in the H2O data frame are 0.  If I restrict the number of columns to 200 (i.e. load_h2o(raw_data, cols = 200)), then the resulting H2O data frame contains all the data as expected.  If cols = 201, we're back to all zeros.

Finally, if I load the data set directly from disk with h2o::h2o.importFile, then the full data set comes through with no problem and I'm able to fit the logistic regression.  However I'd like to be able to load it from an R data frame in order to distribute the object within a package.

Is there a limit on the maximum number of columns for this workflow?

答:
There is no explicit column limit in H2O (certainly not at 785, which is not big).  Spark 1.6 is very old now, I recommend moving forward.

See if what you're seeing might be related to this problem:

https://0xdata.atlassian.net/browse/PUBDEV-3808

If so, one workaround that was discovered was to .cache() the dataframe in Spark before passing it to H2O.

Title: Column limit in H2O data frame?

Body:
I am working with a data set in R which contains 42,457 rows and 785 columns.  The first column is a binary response variable (called label) and the remaining columns are binary features.

I tried to fit a logistic regression model using rsparkling  (described here) but got errors.  I traced this to a step that converts a Spark version of this table to an H2O data frame.

Here's the function I'm using for testing.  The Spark instance sc is up and running and df is the raw data set as a standard R data frame:

load_h2o <- function(df, rows = nrow(df), cols = ncol(df)) {
        df <- df[1:rows, 1:cols]
        copy_to(sc, df, "df", overwrite = TRUE)
        df_tbl <- tbl(sc, "df")
        h2o_tbl <- as_h2o_frame(sc, df_tbl, strict_version_check=FALSE)
        return(h2o_tbl)
}

The head of df$label is 1 1 1 0 0 0.  However if I load the full data set, i.e. load_h2o(raw_data) the head of the resulting label column is 0 0 0 0 0 0; in fact all values in the H2O data frame are 0.  If I restrict the number of columns to 200 (i.e. load_h2o(raw_data, cols = 200)), then the resulting H2O data frame contains all the data as expected.  If cols = 201, we're back to all zeros.

Finally, if I load the data set directly from disk with h2o::h2o.importFile, then the full data set comes through with no problem and I'm able to fit the logistic regression.  However I'd like to be able to load it from an R data frame in order to distribute the object within a package.

Is there a limit on the maximum number of columns for this workflow?


Title: Division of a pandas data frame without the same length

Body:
I need to do an division of two different data frames.

They have the same column name and number, but the length is different.

The division consists in divide each value of this data frame:

df1

      2017-06-01    2017-06-02  2017-06-05  2017-06-06  2017-06-07
INDEX
   0    82449.0     -177507.0   -421443.0    70893.0     -122562.0
   1    95634.0      13662.0     25806.0     253506.0     211002.0
   2   -40956.3     -24179.4    -214666.0    68121.9      66225.6
   3    22950.0     -4590.0     -30600.0    -1530.0      -61200.0
   4   -18608.0      211408.0    284360.0   -88744.0     -64328.0
   5    73830.2      38480.7     21186.9    -68776.2      8437.9
   6   -69682.0     -4080.0     -263273.0    124479.0    -1728.0
   7    11869.0      137352.0    249828.0   -114608.0    -32129.5
   8    36384.6      4565.4      256868.0   -129041.0     89649.0

By each of this:

df2

        2017-06-01   2017-06-02   2017-06-05     2017-06-06   2017-06-07
 INDEX
    0   51970500.0   52246700.0   52021600.0     51928400.0   52090500.0

Example: df1[0][0] = df1[0][0] / df2[0][0]

Body:
The default axis (columns) for the division gives you what you want:

df1.div(df2.loc[0])
Out:
       2017-06-01  2017-06-02  2017-06-05  2017-06-06  2017-06-07
INDEX
A        0.001586   -0.003397   -0.008101    0.001365   -0.002353
B        0.001840    0.000261    0.000496    0.004882    0.004051
C       -0.000788   -0.000463   -0.004126    0.001312    0.001271
D        0.000442   -0.000088   -0.000588   -0.000029   -0.001175
E       -0.000358    0.004046    0.005466   -0.001709   -0.001235
F        0.001421    0.000737    0.000407   -0.001324    0.000162
G       -0.001341   -0.000078   -0.005061    0.002397   -0.000033
H        0.000228    0.002629    0.004802   -0.002207   -0.000617
I        0.000700    0.000087    0.004938   -0.002485    0.001721

which is same as

df1 / df2.loc[0]

Note that I used df2.loc[0]  to extract it as a Series which allows broadcasting. If both of them are DataFrames, both the indices and the columns will be aligned. If one of them is Series, either columns or indices will be aligned.