问:
In C++ trying to write a newline after each operator overload cascade
this is a bit of a hard nut to crack. I'm writing a logging function that is trying to have a similar look to the std::cout

So basically the goal is to have the following code do as commented

```<code>   log << "text"; // This would output "text\n";
   log << "some " << "text"; //This would output "some text\n"
   log << "some number "<< 5; //This would output "some number 5\n"
</code>```

I've tried using variadic templates, but didn't get far.
Here's the most successful attempt so far:

```<code>#include <iostream>

// stream_newliner works by just taking the address of an ostream you
// give it, and forwarding all writes (via operator<<) to that ostream.
// Then, when it finally destructs, it writes the newline.
template <typename CharT, typename Traits>
class stream_newliner
{
public:
// The constructor just takes the address of the stream you give it.
explicit stream_newliner(std::basic_ostream<CharT, Traits>& s) :
    p_s_{&s}
{}

// Boilerplate move construction. Nothing special here.
stream_newliner(stream_newliner&& s) : p_s_{nullptr}
{
    *this = std::move(s);
}

// On destruction, write the newline. (Note we check the pointer for
// null for technical reasons.)
~stream_newliner()
{
    if (p_s_)
    {
        // If you have std::unhandled_exceptions(), you can check to
        // see if a new exception is in flight, and only do the
        // newline if there's not.

        // Note that I'm writing an X and not a newline so you can
        // see it easier.
        (*p_s_) << 'X';
    }
}

// This is where the magic happens. Any time you do "x << y" where
// x is this type, it just passes it on to the underlying stream.
// When you do "x << y1 << y2", it all works magically because it
// translates to "operator<<(operator<<(x, y1), y2)"... and this
// function just passes each call to the underlying stream.
template <typename T>
auto operator<<(T&& t) -> stream_newliner<CharT, Traits>&
{
    (*p_s_) << std::forward<T>(t);
    return *this;
}

// Boilerplate move assignment. Nothing special here.
auto operator=(stream_newliner&& s) -> stream_newliner&
{
    std::swap(p_s_, s.p_s_);
    return *this;
}

// Technically don't need these, but it doesn't hurt to be explicit.
stream_newliner(stream_newliner const&) = delete;
auto operator=(stream_newliner const&) = delete;

   private:
// You could use a reference to the stream rather than a pointer,
// but references are harder to work with as class members.
std::basic_ostream<CharT, Traits>* p_s_ = nullptr;
   };

   // Helper function to make it easier to create.
   template <typename CharT, typename Traits>
   auto line(std::basic_ostream<CharT, Traits>& s)
   {
return stream_newliner<CharT, Traits>{s};
   }

   auto main() -> int
   {
line(std::cout) << "foo";
std::cout << '\n';

line(std::cout) << 1 << ' ' << 2 << ' ' << 3;
std::cout << '\n';
   }
</code>```

答:
I think this isn't too tricky. Let's see:

```<code>struct eol_log
{
    eol_log(std::ostream& os) : os_(os) {}
    ~eol_log() { os_ << '\n'; }

    template <typename T>
    std::ostream& operator<<(const T& t) && { return os_ << t; }

    std::ostream& os_;
};
</code>```

Usage:

```<code>eol_log(std::cout) << "Foo" << "Bar" << 10;
eol_log(std::cout) << 10;
</code>```

The temporary object acts as a kind of "full-expression guard".

If you'd rather have a permanent object that acts as your log sink, then you can wrap the above in a class, but now you need to move the state of being the last element along the chain:

```<code>class EolLogger
{
    class RvalLog
    {
        friend class EolLogger;

        RvalLog(std::ostream* os) : os_(os) {}
        RvalLog(RvalLog&& rhs) : os_(rhs.os_) { rhs.os_ = nullptr; }
        std::ostream* os_;

    public:
        template <typename T>
        RvalLog operator<<(const T& t) && { *os_ << t; return std::move(*this); }

        ~RvalLog() { if (os_) *os_ << '\n'; }
    };

    std::ostream& os_;

public:
    EolLogger(std::ostream& os) : os_(os) {}

    template <typename T>
    RvalLog operator<<(const T& t) { return RvalLog(&os_) << t; }
};
</code>```

Usage:

```<code>EolLogger elog(std::cout);

elog << "Foo";
elog << 1 << 2 << 3;
</code>```

Body:
this is a bit of a hard nut to crack. I'm writing a logging function that is trying to have a similar look to the std::cout

So basically the goal is to have the following code do as commented

   log << "text"; // This would output "text\n";
   log << "some " << "text"; //This would output "some text\n"
   log << "some number "<< 5; //This would output "some number 5\n"

I've tried using variadic templates, but didn't get far.
Here's the most successful attempt so far:

#include <iostream>

// stream_newliner works by just taking the address of an ostream you
// give it, and forwarding all writes (via operator<<) to that ostream.
// Then, when it finally destructs, it writes the newline.
template <typename CharT, typename Traits>
class stream_newliner
{
public:
// The constructor just takes the address of the stream you give it.
explicit stream_newliner(std::basic_ostream<CharT, Traits>& s) :
    p_s_{&s}
{}

// Boilerplate move construction. Nothing special here.
stream_newliner(stream_newliner&& s) : p_s_{nullptr}
{
    *this = std::move(s);
}

// On destruction, write the newline. (Note we check the pointer for
// null for technical reasons.)
~stream_newliner()
{
    if (p_s_)
    {
        // If you have std::unhandled_exceptions(), you can check to
        // see if a new exception is in flight, and only do the
        // newline if there's not.

        // Note that I'm writing an X and not a newline so you can
        // see it easier.
        (*p_s_) << 'X';
    }
}

// This is where the magic happens. Any time you do "x << y" where
// x is this type, it just passes it on to the underlying stream.
// When you do "x << y1 << y2", it all works magically because it
// translates to "operator<<(operator<<(x, y1), y2)"... and this
// function just passes each call to the underlying stream.
template <typename T>
auto operator<<(T&& t) -> stream_newliner<CharT, Traits>&
{
    (*p_s_) << std::forward<T>(t);
    return *this;
}

// Boilerplate move assignment. Nothing special here.
auto operator=(stream_newliner&& s) -> stream_newliner&
{
    std::swap(p_s_, s.p_s_);
    return *this;
}

// Technically don't need these, but it doesn't hurt to be explicit.
stream_newliner(stream_newliner const&) = delete;
auto operator=(stream_newliner const&) = delete;

   private:
// You could use a reference to the stream rather than a pointer,
// but references are harder to work with as class members.
std::basic_ostream<CharT, Traits>* p_s_ = nullptr;
   };

   // Helper function to make it easier to create.
   template <typename CharT, typename Traits>
   auto line(std::basic_ostream<CharT, Traits>& s)
   {
return stream_newliner<CharT, Traits>{s};
   }

   auto main() -> int
   {
line(std::cout) << "foo";
std::cout << '\n';

line(std::cout) << 1 << ' ' << 2 << ' ' << 3;
std::cout << '\n';
   }

Body:
I think this isn't too tricky. Let's see:

struct eol_log
{
    eol_log(std::ostream& os) : os_(os) {}
    ~eol_log() { os_ << '\n'; }

    template <typename T>
    std::ostream& operator<<(const T& t) && { return os_ << t; }

    std::ostream& os_;
};

Usage:

eol_log(std::cout) << "Foo" << "Bar" << 10;
eol_log(std::cout) << 10;

The temporary object acts as a kind of "full-expression guard".

If you'd rather have a permanent object that acts as your log sink, then you can wrap the above in a class, but now you need to move the state of being the last element along the chain:

class EolLogger
{
    class RvalLog
    {
        friend class EolLogger;

        RvalLog(std::ostream* os) : os_(os) {}
        RvalLog(RvalLog&& rhs) : os_(rhs.os_) { rhs.os_ = nullptr; }
        std::ostream* os_;

    public:
        template <typename T>
        RvalLog operator<<(const T& t) && { *os_ << t; return std::move(*this); }

        ~RvalLog() { if (os_) *os_ << '\n'; }
    };

    std::ostream& os_;

public:
    EolLogger(std::ostream& os) : os_(os) {}

    template <typename T>
    RvalLog operator<<(const T& t) { return RvalLog(&os_) << t; }
};

Usage:

EolLogger elog(std::cout);

elog << "Foo";
elog << 1 << 2 << 3;


来源: stackexchange

问:
Arranging data to make a 3d surface plot
I am trying to make 3D surface plot, but I'm having trouble transforming my data into the right format.

Reshaping my Z variable gives me: 'ValueError: total size of new array must be unchanged'. The shape for Z is (2500,50). The shapes for X and Y are both (50,50). I'm not sure why this is so. Is there something obviously wrong with my code that I'm missing?

```<code>import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

def Mountain(F, P):
    TA = ((TAmax-TAmin) * (((FF**g)/((FF**g)+FFhm**g)**a)/((((FF**g)/((FF**g)+FFhm**g))**a)+(SP/SPe)**a)))
    return TA

F = np.linspace(0,120)
P = np.linspace(0,100)
Fb= int(21)
Fro= int(362)
FFhm = int(63)
g= int(3)
a = int(3)
SPmin = float(1.82)
SPbend = float(0.5)
SPe = int(10)
TAmax= int(1)
TAmin = int(0)

SP = SPmin + SPbend * np.log(1 + np.exp((P - SPmin)/SPbend))

FF= (Fb * (np.log(1 + np.exp(Fro/Fb)) - np.log(1 + np.exp((Fro-F)/Fb))))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y = np.meshgrid(F, P)
gh= list(zip(np.ravel(X), np.ravel(Y)))
zs = np.array(Mountain(F,P) for F,P in gh)
Z = zs.reshape(X.shape)

ax.plot_surface(X, Y, Z)

ax.set_xlabel('F')
ax.set_ylabel('P')
ax.set_zlabel('TA')

plt.show()
</code>```

答: Note that zs is empty. If you want to do list comprehension, you should use brackets (so np.array([Mountain(F,P) for F,P in gh])), though what you really want is zs = np.array([Mountain(X[i],Y[i]) for i in range(X.shape[0])]) instead of ravel.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to make 3D surface plot, but I'm having trouble transforming my data into the right format.

Reshaping my Z variable gives me: 'ValueError: total size of new array must be unchanged'. The shape for Z is (2500,50). The shapes for X and Y are both (50,50). I'm not sure why this is so. Is there something obviously wrong with my code that I'm missing?

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

def Mountain(F, P):
    TA = ((TAmax-TAmin) * (((FF**g)/((FF**g)+FFhm**g)**a)/((((FF**g)/((FF**g)+FFhm**g))**a)+(SP/SPe)**a)))
    return TA

F = np.linspace(0,120)
P = np.linspace(0,100)
Fb= int(21)
Fro= int(362)
FFhm = int(63)
g= int(3)
a = int(3)
SPmin = float(1.82)
SPbend = float(0.5)
SPe = int(10)
TAmax= int(1)
TAmin = int(0)

SP = SPmin + SPbend * np.log(1 + np.exp((P - SPmin)/SPbend))

FF= (Fb * (np.log(1 + np.exp(Fro/Fb)) - np.log(1 + np.exp((Fro-F)/Fb))))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y = np.meshgrid(F, P)
gh= list(zip(np.ravel(X), np.ravel(Y)))
zs = np.array(Mountain(F,P) for F,P in gh)
Z = zs.reshape(X.shape)

ax.plot_surface(X, Y, Z)

ax.set_xlabel('F')
ax.set_ylabel('P')
ax.set_zlabel('TA')

plt.show()


问:
PHP, MYSQL select row update
I want to change the ID information of the selected image. I want to make the ID number more than the last ID available.

in HTML;

```<code><form action="netting/operations.php" method="post">
<input type="hidden" value="<?php echo $unilogo['uni_logo_id'] ?>" name="uni_logo_id">
<button value="use" name="use_again">Use Again</button>
</form>
</code>```

in PHP;

```<code><?php
if(isset($_POST['use_again'])){
    $unilogoid= $_POST['uni_logo_id'];
    $lastunilogoid = mysqli_query($conn,"SELECT uni_logo_id FROM uni_logo ORDER BY uni_logo_id DESC LIMIT 1");
    $unilogosql = "UPDATE uni_logo SET uni_logo_id='".$lastunilogoid."' WHERE uni_logo_id='".$unilogoid."'";
    $unilogosira=mysqli_query($conn,$unilogosql,MYSQLI_USE_RESULT);
?>
</code>```

答:
$lastunilogoid isn't the valid of the ID, it's a mysqli_result object. You need to call mysqli_fetch_assoc:

```<code>$result = mysqli_query($conn,"SELECT uni_logo_id FROM uni_logo ORDER BY uni_logo_id DESC LIMIT 1");
$row = mysqli_fetch_assoc($result);
$lastunilogoid = $row['uni_logi_id'];
</code>```

But you can do the whole thing in one query, and you should use a prepared statement to do it.

```<code>$stmt = mysqli_prepare($conn, "
    UPDATE uni_logo AS u1
    JOIN (SELECT MAX(uni_logo_id) AS max_id
          FROM uni_logo) AS u2
    SET u1.uni_logo_id = u2.max_id + 1
    WHERE u1.uni_logo_id = ?");
mysqli_stmt_bind_param($stmt, "i", $unilogoid);
mysqli_stmt_execute($stmt);
</code>```

Title: PHP, MYSQL select row update

Body:
I want to change the ID information of the selected image. I want to make the ID number more than the last ID available.

in HTML;

<form action="netting/operations.php" method="post">
<input type="hidden" value="<?php echo $unilogo['uni_logo_id'] ?>" name="uni_logo_id">
<button value="use" name="use_again">Use Again</button>
</form>

in PHP;

<?php
if(isset($_POST['use_again'])){
    $unilogoid= $_POST['uni_logo_id'];
    $lastunilogoid = mysqli_query($conn,"SELECT uni_logo_id FROM uni_logo ORDER BY uni_logo_id DESC LIMIT 1");
    $unilogosql = "UPDATE uni_logo SET uni_logo_id='".$lastunilogoid."' WHERE uni_logo_id='".$unilogoid."'";
    $unilogosira=mysqli_query($conn,$unilogosql,MYSQLI_USE_RESULT);
?>

Body:
$lastunilogoid isn't the valid of the ID, it's a mysqli_result object. You need to call mysqli_fetch_assoc:

$result = mysqli_query($conn,"SELECT uni_logo_id FROM uni_logo ORDER BY uni_logo_id DESC LIMIT 1");
$row = mysqli_fetch_assoc($result);
$lastunilogoid = $row['uni_logi_id'];

But you can do the whole thing in one query, and you should use a prepared statement to do it.

$stmt = mysqli_prepare($conn, "
    UPDATE uni_logo AS u1
    JOIN (SELECT MAX(uni_logo_id) AS max_id
          FROM uni_logo) AS u2
    SET u1.uni_logo_id = u2.max_id + 1
    WHERE u1.uni_logo_id = ?");
mysqli_stmt_bind_param($stmt, "i", $unilogoid);
mysqli_stmt_execute($stmt);


问:
Mule: Triggering a process API that calls a System API
I have built a process API (which is a POST) that calls another system API to retrieve some information , question I have is how can I trigger the process API for testing purpose? Also if I were to add a poller , how would the poller invoke this process API?</p>

```<code>     <flow name="postData" processingStrategy="synchronous">

    <http:request config-ref="call-system-api" path="/getInfo" method="GET" doc:name="call backend">
        <http:request-builder>
            <http:query-param paramName="modifiedAfter" value="#[message.inboundProperties.'http.query.params'.get("modifiedAfter")]"/>
        </http:request-builder>
    </http:request>
</code>```

答:
For HTTP Request,
You could postman, to post request.
If you are going to add a poller, you would place the poller as the first component of the flow.
 Here is an example.</p>

```<code><poll doc:name="Poll">
   <http:request config-ref="" path="" method="" doc:name="HTTP"/>
 </poll>
</code>```

Body:
I have built a process API (which is a POST) that calls another system API to retrieve some information , question I have is how can I trigger the process API for testing purpose? Also if I were to add a poller , how would the poller invoke this process API?

     <flow name="postData" processingStrategy="synchronous">

    <http:request config-ref="call-system-api" path="/getInfo" method="GET" doc:name="call backend">
        <http:request-builder>
            <http:query-param paramName="modifiedAfter" value="#[message.inboundProperties.'http.query.params'.get("modifiedAfter")]"/>
        </http:request-builder>
    </http:request>

Body:
For HTTP Request,
You could postman, to post request.
If you are going to add a poller, you would place the poller as the first component of the flow.
 Here is an example.

<poll doc:name="Poll">
   <http:request config-ref="" path="" method="" doc:name="HTTP"/>
 </poll>


问:
How to make a textbox and a textarea same width cross-browsers?
Setting the width of both the textbox (ie. input type="text") and the textarea to 500px doesn't work in IE6 and Chrome, only works fine in FF2 (haven't tested other browsers), IE and Chrome add two pixels to the textbox.

Padding and margin is set to 0 on all elements using

```<code>*
{
margin: 0px;
padding: 0px;
}
</code>```

Changing the doctype from xhtml 1.0 transitional to strict didn't work too.

答:
```<code><!--***********************CSS**************************-->
<style>

.set_font

{

font-family:verdana;

font-size:10px;

color:#ffffff;

width:250px;

}

.set_font2

{

font-family:verdana;

font-size:10px;

color:#000000;

width:250px;

}
</style>
<!--*******************HTML**************************-->
<input type="text" size="33" class="set_font2" name="inputName" id="inputName" value="inputValue" maxlength="50">
<textarea cols="30" rows="8" class="set_font2" name="inputName" id="inputName">inputValue</textarea>
</code>```

OwnerDisplayName: Waleed Eissa

ContentLicense: CC BY-SA 2.5

Body:
Setting the width of both the textbox (ie. input type="text") and the textarea to 500px doesn't work in IE6 and Chrome, only works fine in FF2 (haven't tested other browsers), IE and Chrome add two pixels to the textbox.

Padding and margin is set to 0 on all elements using

*
{
margin: 0px;
padding: 0px;
}

Changing the doctype from xhtml 1.0 transitional to strict didn't work too.

LastEditorDisplayName: bigmattyh


问:
transforming json using recursive function
I'm trying to transform this JSON into array so that I can simply list them as key-value pairs in html. The JSON has nested properties which I want to retain but I want to stringify only those objects that contain "units" and "value". All others should be listed as children items. Please help figure what I'm doing wrong.

Here's the json input:

```<code>  {
  "clusterName": "ml6.engrlab.com-cluster",
  "statusProperties": {
    "loadProperties": {
      "loadDetail": {
        "restoreWriteLoad": {
          "value": 0,
          "units": "sec/sec"
        },
      },
      "totalLoad": {
        "value": 0.0825921967625618,
        "units": "sec/sec"
      }
    },
    "secure": {
      "value": false,
      "units": "bool"
    },
    "statusDetail": {
      "licenseKeyOption": [
        {
          "value": "conversion",
          "units": "enum"
        },
        {
          "value": "failover",
          "units": "enum"
        }
      ],
      "connectPort": 7999,
      "softwareVersion": {
        "value": 9000100,
        "units": "quantity"
      }
    },
    "rateProperties": {
      "rateDetail": {
        "largeReadRate": {
          "value": 0,
          "units": "MB/sec"
        }
      },
      "totalRate": {
        "value": 67.2446365356445,
        "units": "MB/sec"
      }
    },
    "online": {
      "value": true,
      "units": "bool"
    },
    "cacheProperties": {
      "cacheDetail": {
        "tripleCachePartitions": {
          "tripleCachePartition": [
            {
              "partitionSize": 768,
              "partitionBusy": 0,
              "partitionUsed": 0,
              "partitionFree": 100
            }
          ]
        }
      }
    }
  }
}
</code>```

my code

```<code>function isNested(obj) {
if(!obj) return false;

let propArry = Object.keys(obj)
for(let i=0; i<propArry.length; i++){
  if(obj[propArry[0]].constructor.name === 'Object') return true
}
  return false;
}

function getKeyValueAsChildren(obj) {
  let vals = [];
  for(let key in obj) {
    if(obj.hasOwnProperty(key)){
      vals.push({key:key, value: obj[key]})
    }
  }
  return vals
}

function valueAsString(obj) {
  if(typeof obj !== 'object') return obj;

  return `${obj['value']} ${obj['units']}`
}

function getChildren(key, obj) {
   if(Object.keys(obj).sort().toString() === "units,value"){
         return {key: key, value: valueAsString(obj)}
     } else {
         return {key: key, children: getKeyValueAsChildren(obj) }
   }
}

function getValues(properties, values = []) {
for(let key in properties) {
    if(properties.hasOwnProperty(key)) {
      let value =  properties[key]
      if(typeof value !== 'object') {
        values.push({key: key, value: value})
      } else if(Array.isArray(value)){
        let children = []
        value.map(v => {
          children.push(getChildren(key, v))
        })
        values.push({key: `${key}List`, children: children})
      }
      else if(value.constructor.name === 'Object' && isNested(value)){
        // I THINK THE MAIN PROBLEM IS HERE
        let keys = Object.keys(value)
        let children = [];
        keys.forEach(key => {
          children.push({key: key, children: getValues(value[key])})
        })
        values.push({key: key, children: children})
      }
       else {
          values.push(getChildren(key, value))
      }
    }
}
return values
}

getValues(hostProperties)
</code>```

this returns

```<code>    [
    {
        "key": "clusterName",
        "value": "ml6.engrlab.com-cluster"
    },
    {
        "key": "statusProperties",
        "children": [
            {
                "key": "loadProperties",
                "children": [
                    {
                        "key": "loadDetail",
                        "children": [
                            {
                                "key": "restoreWriteLoad",
                                "children": [
                                    {
                                        "key": "value",
                                        "value": 0
                                    },
                                    {
                                        "key": "units",
                                        "value": "sec/sec"
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "key": "totalLoad",
                        "value": "0.0825921967625618 sec/sec"
                    }
                ]
            },
            {
                "key": "secure",
                "children": [
                    {
                        "key": "value",
                        "value": false
                    },
                    {
                        "key": "units",
                        "value": "bool"
                    }
                ]
            },
            {
                "key": "statusDetail",
                "children": [
                    {
                        "key": "licenseKeyOptionList",
                        "children": [
                            {
                                "key": "licenseKeyOption",
                                "value": "conversion enum"
                            },
                            {
                                "key": "licenseKeyOption",
                                "value": "failover enum"
                            }
                        ]
                    },
                    {
                        "key": "connectPort",
                        "value": 7999
                    },
                ]
            },
            {
                "key": "rateProperties",
                "children": [
                    {
                        "key": "rateDetail",
                        "children": [
                            {
                                "key": "largeReadRate",
                                "children": [
                                    {
                                        "key": "value",
                                        "value": 0
                                    },
                                    {
                                        "key": "units",
                                        "value": "MB/sec"
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "key": "totalRate",
                        "value": "67.2446365356445 MB/sec"
                    }
                ]
            },
            {
                "key": "online",
                "children": [
                    {
                        "key": "value",
                        "value": true
                    },
                    {
                        "key": "units",
                        "value": "bool"
                    }
                ]
            },
            {
                "key": "cacheProperties",
                "children": [
                    {
                        "key": "cacheDetail",
                        "children": [
                            {
                                "key": "tripleCachePartitions",
                                "children": [
                                    {
                                        "key": "tripleCachePartitionList",
                                        "children": [
                                            {
                                                "key": "tripleCachePartition",
                                                "children": [
                                                    {
                                                        "key": "partitionSize",
                                                        "value": 768
                                                    },
                                                    {
                                                        "key": "partitionBusy",
                                                        "value": 0
                                                    },
                                                    {
                                                        "key": "partitionUsed",
                                                        "value": 0
                                                    },
                                                    {
                                                        "key": "partitionFree",
                                                        "value": 100
                                                    }
                                                ]
                                            }
                                        ]
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        ]
    }
]
</code>```

but I need this

```<code>[
{
    "key": "clusterName",
    "value": "ml6.engrlab.com-cluster"
},
{
    "key": "statusProperties",
    "children": [
        {
            "key": "loadProperties",
            "children": [
                {
                    "key": "loadDetail",
                    "children": [
                        {
                            "key": "restoreWriteLoad",
                            "value": "0 sec/sec"
                        }
                    ]
                },
                {
                    "key": "totalLoad",
                    "value": "0.0825921967625618 sec/sec"
                }
            ]
        },
        {
            "key": "secure",
            "value": "false bool"
        },
        {
            "key": "statusDetail",
            "children": [
                {
                    "key": "licenseKeyOptionList",
                    "children": [
                        {
                            "key": "licenseKeyOption",
                            "value": "conversion enum"
                        },
                        {
                            "key": "licenseKeyOption",
                            "value": "failover enum"
                        }
                    ]
                },
                {
                    "key": "connectPort",
                    "value": 7999
                }
            ]
        },
        {
            "key": "rateProperties",
            "children": [
                {
                    "key": "rateDetail",
                    "children": [
                        {
                            "key": "largeReadRate",
                            "value": "0 MB/sec"
                        }
                    ]
                },
                {
                    "key": "totalRate",
                    "value": "67.2446365356445 MB/sec"
                }
            ]
        },
        {
            "key": "online",
            "value": "true bool"
        },
        {
            "key": "cacheProperties",
            "children": [
                {
                    "key": "cacheDetail",
                    "children": [
                        {
                            "key": "tripleCachePartitions",
                            "children": [
                                {
                                    "key": "tripleCachePartitionList",
                                    "children": [
                                        {
                                            "key": "tripleCachePartition",
                                            "children": [
                                                {
                                                    "key": "partitionSize",
                                                    "value": 768
                                                },
                                                {
                                                    "key": "partitionBusy",
                                                    "value": 0
                                                },
                                                {
                                                    "key": "partitionUsed",
                                                    "value": 0
                                                },
                                                {
                                                    "key": "partitionFree",
                                                    "value": 100
                                                }
                                            ]
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}
</code>```

]

答:
You might have to run more tests, as what you require seems quite arbitrary, but I believe this function does what you are looking for. It works in a similar way to yours, by simply recursing the tree, and checking for object types, and if the special case is matched.

```<code>function toKeyValue(obj) {
  return Object.keys(obj).map(k => {
    var value = obj[k]
    var key = k
    var valueName = 'children'
    if(Array.isArray(value)){
      key = k + 'List'
      value = value.map(toKeyValue)
    }else if(value !== null && typeof value === 'object'){
      // check for special case
      if(Object.keys(value).sort().toString() === "units,value"){
        value = value.value + ' ' + value.units
        valueName = 'value'
      }else{
        value = toKeyValue(value)
      }
    }else{
      valueName = 'value'
    }
    return {
      key: key,
      [valueName]: value
    }
  })
}
</code>```

Fiddle here

Body:
I'm trying to transform this JSON into array so that I can simply list them as key-value pairs in html. The JSON has nested properties which I want to retain but I want to stringify only those objects that contain "units" and "value". All others should be listed as children items. Please help figure what I'm doing wrong.

Here's the json input:

  {
  "clusterName": "ml6.engrlab.com-cluster",
  "statusProperties": {
    "loadProperties": {
      "loadDetail": {
        "restoreWriteLoad": {
          "value": 0,
          "units": "sec/sec"
        },
      },
      "totalLoad": {
        "value": 0.0825921967625618,
        "units": "sec/sec"
      }
    },
    "secure": {
      "value": false,
      "units": "bool"
    },
    "statusDetail": {
      "licenseKeyOption": [
        {
          "value": "conversion",
          "units": "enum"
        },
        {
          "value": "failover",
          "units": "enum"
        }
      ],
      "connectPort": 7999,
      "softwareVersion": {
        "value": 9000100,
        "units": "quantity"
      }
    },
    "rateProperties": {
      "rateDetail": {
        "largeReadRate": {
          "value": 0,
          "units": "MB/sec"
        }
      },
      "totalRate": {
        "value": 67.2446365356445,
        "units": "MB/sec"
      }
    },
    "online": {
      "value": true,
      "units": "bool"
    },
    "cacheProperties": {
      "cacheDetail": {
        "tripleCachePartitions": {
          "tripleCachePartition": [
            {
              "partitionSize": 768,
              "partitionBusy": 0,
              "partitionUsed": 0,
              "partitionFree": 100
            }
          ]
        }
      }
    }
  }
}

my code

function isNested(obj) {
if(!obj) return false;

let propArry = Object.keys(obj)
for(let i=0; i<propArry.length; i++){
  if(obj[propArry[0]].constructor.name === 'Object') return true
}
  return false;
}

function getKeyValueAsChildren(obj) {
  let vals = [];
  for(let key in obj) {
    if(obj.hasOwnProperty(key)){
      vals.push({key:key, value: obj[key]})
    }
  }
  return vals
}

function valueAsString(obj) {
  if(typeof obj !== 'object') return obj;

  return `${obj['value']} ${obj['units']}`
}

function getChildren(key, obj) {
   if(Object.keys(obj).sort().toString() === "units,value"){
         return {key: key, value: valueAsString(obj)}
     } else {
         return {key: key, children: getKeyValueAsChildren(obj) }
   }
}

function getValues(properties, values = []) {
for(let key in properties) {
    if(properties.hasOwnProperty(key)) {
      let value =  properties[key]
      if(typeof value !== 'object') {
        values.push({key: key, value: value})
      } else if(Array.isArray(value)){
        let children = []
        value.map(v => {
          children.push(getChildren(key, v))
        })
        values.push({key: `${key}List`, children: children})
      }
      else if(value.constructor.name === 'Object' && isNested(value)){
        // I THINK THE MAIN PROBLEM IS HERE
        let keys = Object.keys(value)
        let children = [];
        keys.forEach(key => {
          children.push({key: key, children: getValues(value[key])})
        })
        values.push({key: key, children: children})
      }
       else {
          values.push(getChildren(key, value))
      }
    }
}
return values
}

getValues(hostProperties)

this returns

    [
    {
        "key": "clusterName",
        "value": "ml6.engrlab.com-cluster"
    },
    {
        "key": "statusProperties",
        "children": [
            {
                "key": "loadProperties",
                "children": [
                    {
                        "key": "loadDetail",
                        "children": [
                            {
                                "key": "restoreWriteLoad",
                                "children": [
                                    {
                                        "key": "value",
                                        "value": 0
                                    },
                                    {
                                        "key": "units",
                                        "value": "sec/sec"
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "key": "totalLoad",
                        "value": "0.0825921967625618 sec/sec"
                    }
                ]
            },
            {
                "key": "secure",
                "children": [
                    {
                        "key": "value",
                        "value": false
                    },
                    {
                        "key": "units",
                        "value": "bool"
                    }
                ]
            },
            {
                "key": "statusDetail",
                "children": [
                    {
                        "key": "licenseKeyOptionList",
                        "children": [
                            {
                                "key": "licenseKeyOption",
                                "value": "conversion enum"
                            },
                            {
                                "key": "licenseKeyOption",
                                "value": "failover enum"
                            }
                        ]
                    },
                    {
                        "key": "connectPort",
                        "value": 7999
                    },
                ]
            },
            {
                "key": "rateProperties",
                "children": [
                    {
                        "key": "rateDetail",
                        "children": [
                            {
                                "key": "largeReadRate",
                                "children": [
                                    {
                                        "key": "value",
                                        "value": 0
                                    },
                                    {
                                        "key": "units",
                                        "value": "MB/sec"
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "key": "totalRate",
                        "value": "67.2446365356445 MB/sec"
                    }
                ]
            },
            {
                "key": "online",
                "children": [
                    {
                        "key": "value",
                        "value": true
                    },
                    {
                        "key": "units",
                        "value": "bool"
                    }
                ]
            },
            {
                "key": "cacheProperties",
                "children": [
                    {
                        "key": "cacheDetail",
                        "children": [
                            {
                                "key": "tripleCachePartitions",
                                "children": [
                                    {
                                        "key": "tripleCachePartitionList",
                                        "children": [
                                            {
                                                "key": "tripleCachePartition",
                                                "children": [
                                                    {
                                                        "key": "partitionSize",
                                                        "value": 768
                                                    },
                                                    {
                                                        "key": "partitionBusy",
                                                        "value": 0
                                                    },
                                                    {
                                                        "key": "partitionUsed",
                                                        "value": 0
                                                    },
                                                    {
                                                        "key": "partitionFree",
                                                        "value": 100
                                                    }
                                                ]
                                            }
                                        ]
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

but I need this

[
{
    "key": "clusterName",
    "value": "ml6.engrlab.com-cluster"
},
{
    "key": "statusProperties",
    "children": [
        {
            "key": "loadProperties",
            "children": [
                {
                    "key": "loadDetail",
                    "children": [
                        {
                            "key": "restoreWriteLoad",
                            "value": "0 sec/sec"
                        }
                    ]
                },
                {
                    "key": "totalLoad",
                    "value": "0.0825921967625618 sec/sec"
                }
            ]
        },
        {
            "key": "secure",
            "value": "false bool"
        },
        {
            "key": "statusDetail",
            "children": [
                {
                    "key": "licenseKeyOptionList",
                    "children": [
                        {
                            "key": "licenseKeyOption",
                            "value": "conversion enum"
                        },
                        {
                            "key": "licenseKeyOption",
                            "value": "failover enum"
                        }
                    ]
                },
                {
                    "key": "connectPort",
                    "value": 7999
                }
            ]
        },
        {
            "key": "rateProperties",
            "children": [
                {
                    "key": "rateDetail",
                    "children": [
                        {
                            "key": "largeReadRate",
                            "value": "0 MB/sec"
                        }
                    ]
                },
                {
                    "key": "totalRate",
                    "value": "67.2446365356445 MB/sec"
                }
            ]
        },
        {
            "key": "online",
            "value": "true bool"
        },
        {
            "key": "cacheProperties",
            "children": [
                {
                    "key": "cacheDetail",
                    "children": [
                        {
                            "key": "tripleCachePartitions",
                            "children": [
                                {
                                    "key": "tripleCachePartitionList",
                                    "children": [
                                        {
                                            "key": "tripleCachePartition",
                                            "children": [
                                                {
                                                    "key": "partitionSize",
                                                    "value": 768
                                                },
                                                {
                                                    "key": "partitionBusy",
                                                    "value": 0
                                                },
                                                {
                                                    "key": "partitionUsed",
                                                    "value": 0
                                                },
                                                {
                                                    "key": "partitionFree",
                                                    "value": 100
                                                }
                                            ]
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

]

Body:
You might have to run more tests, as what you require seems quite arbitrary, but I believe this function does what you are looking for. It works in a similar way to yours, by simply recursing the tree, and checking for object types, and if the special case is matched.

function toKeyValue(obj) {
  return Object.keys(obj).map(k => {
    var value = obj[k]
    var key = k
    var valueName = 'children'
    if(Array.isArray(value)){
      key = k + 'List'
      value = value.map(toKeyValue)
    }else if(value !== null && typeof value === 'object'){
      // check for special case
      if(Object.keys(value).sort().toString() === "units,value"){
        value = value.value + ' ' + value.units
        valueName = 'value'
      }else{
        value = toKeyValue(value)
      }
    }else{
      valueName = 'value'
    }
    return {
      key: key,
      [valueName]: value
    }
  })
}

Fiddle here


问:
replace sed command text inline
I have this file

file.txt

```<code>unknown@mail.com||unknown@mail.com||
unknown@mail2.com||unknown@mail2.com||
unknown@mail3.com||unknown@mail3.com||
unknown@mail4.com||unknown@mail4.com||
unknownpass
unknownpass2
unknownpass3
unknownpass4
</code>```

How can I use the sed command to obtain this:

```<code>unknown@mail.com|unknownpass|unknown@mail.com|unknownpass|
unknown@mail2.com|unknownpass2|unknown@mail2.com|unknownpass2|
unknown@mail3.com|unknownpass3|unknown@mail3.com|unknownpass3|
unknown@mail4.com|unknownpass4|unknown@mail4.com|unknownpass4|
</code>```

答:
awk to the rescue!

```<code>awk 'BEGIN   {FS=OFS="|"}
     NR==FNR {if(NF==1) a[++c]=$1; next}
     NF>4    {$2=a[FNR]; $4=$2; print}' file{,}
</code>```

a two pass algorithm, caches the entries in the first round and inserts them into the empty fields, assumes the number of items match.

Here is another approach with one pass, powered by tac wrapped awk

```<code>tac file |
awk 'BEGIN {FS=OFS="|"}
     NF==1 {a[++c]=$1}
     NF>4  {$2=a[c--]; $4=$2; print}' |
tac
</code>```

Title: replace sed command text inline

Body:
I have this file

file.txt

unknown@mail.com||unknown@mail.com||
unknown@mail2.com||unknown@mail2.com||
unknown@mail3.com||unknown@mail3.com||
unknown@mail4.com||unknown@mail4.com||
unknownpass
unknownpass2
unknownpass3
unknownpass4

How can I use the sed command to obtain this:

unknown@mail.com|unknownpass|unknown@mail.com|unknownpass|
unknown@mail2.com|unknownpass2|unknown@mail2.com|unknownpass2|
unknown@mail3.com|unknownpass3|unknown@mail3.com|unknownpass3|
unknown@mail4.com|unknownpass4|unknown@mail4.com|unknownpass4|

Body:
awk to the rescue!

awk 'BEGIN   {FS=OFS="|"}
     NR==FNR {if(NF==1) a[++c]=$1; next}
     NF>4    {$2=a[FNR]; $4=$2; print}' file{,}

a two pass algorithm, caches the entries in the first round and inserts them into the empty fields, assumes the number of items match.

Here is another approach with one pass, powered by tac wrapped awk

tac file |
awk 'BEGIN {FS=OFS="|"}
     NF==1 {a[++c]=$1}
     NF>4  {$2=a[c--]; $4=$2; print}' |
tac


问:
How to get each specific value in an array?
I'm looking to be able to extract each 'hire_address' value from the following array and add it to a separate array.

```<code>var addr =
{
   "status":"success",
   "data":[
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Glasgow",
         "offer_oucu":"ac1",
         "offer_address":"Glasgow"
      },
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Poole",
         "offer_oucu":"ac1",
         "offer_address":"Poole"
      }
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Hastings",
         "offer_oucu":"ac1",
         "offer_address":"Hastings"
      }
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"London",
         "offer_oucu":"ac1",
         "offer_address":"London"
      }
   ]
};
</code>```

I currently have

```<code>var addresses = [];
$.each(addr.data.hire_address, function (index, value) {
addresses.push(value);
</code>```

But not having any luck. Any suggestions?

Thank you for the replies.

I now have

```<code>var addresses = [];
$.each(addr, function (index, value) {
    if (value == "data"){
        addresses.push(value.hire_address);
    }
}
);
</code>```

But can't seem to get it to work. Do I need the if statement? I added this because the first item is 'status' and was running into errors if I tried to add a 'hire_address' property of this because it doesn't exists.

答:
Use Array.map

```<code>addr.data.map(d => d.hire_address)
</code>```

Body:
I'm looking to be able to extract each 'hire_address' value from the following array and add it to a separate array.

var addr =
{
   "status":"success",
   "data":[
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Glasgow",
         "offer_oucu":"ac1",
         "offer_address":"Glasgow"
      },
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Poole",
         "offer_oucu":"ac1",
         "offer_address":"Poole"
      }
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Hastings",
         "offer_oucu":"ac1",
         "offer_address":"Hastings"
      }
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"London",
         "offer_oucu":"ac1",
         "offer_address":"London"
      }
   ]
};

I currently have

var addresses = [];
$.each(addr.data.hire_address, function (index, value) {
addresses.push(value);

But not having any luck. Any suggestions?

Thank you for the replies.

I now have

var addresses = [];
$.each(addr, function (index, value) {
    if (value == "data"){
        addresses.push(value.hire_address);
    }
}
);

But can't seem to get it to work. Do I need the if statement? I added this because the first item is 'status' and was running into errors if I tried to add a 'hire_address' property of this because it doesn't exists.

Body:
Use Array.map

addr.data.map(d => d.hire_address)


问:
Unique constraint between several columns derived from the same one to many relationship
I'm not sure if I titled this correctly or if it is even possible.

I have three columns that are populated from the same one to many relationship from another table.

For example:

```<code>User_Id | Security Question 1 | Security Question 2 | Security Question 3
</code>```

And a table of questions:

```<code>Id | Question
1  | Are you x?
2  | Are you y?
3  | Are you z?
</code>```

When a row is written into the first table it requires a security question from the second table. However, the possible choices are all the questions from the second table. I want to enforce a restriction that any user didn't pick any question twice.

How can I do this? Should this be relegated to my application code?

答:
This is a little tricky.  Often, it is not reasonable to store the same entity in multiple columns.  This is a case where it might make sense.

You can readily do what you want with a check constraint:

```<code>alter table t add constraint check_t_security
    check (SecurityQuestion1 <> SecurityQuestion2 and
           SecurityQuestion2 <> SecurityQuestion3 and
           SecurityQuestion3 <> SecurityQuestion1
          );
</code>```

The logic is similar but more cumbersome if NULL values are allowed for the questions.  You would have to specify if a user could have more than one NULL value.

You can shorten the logic to:

```<code>alter table t add constraint check_t_security
    check (SecurityQuestion1 not in (SecurityQuestion2, SecurityQuestion3) and
           SecurityQuestion2 not in (SecurityQuestion3)
          );
</code>```

Body:
I'm not sure if I titled this correctly or if it is even possible.

I have three columns that are populated from the same one to many relationship from another table.

For example:

User_Id | Security Question 1 | Security Question 2 | Security Question 3

And a table of questions:

Id | Question
1  | Are you x?
2  | Are you y?
3  | Are you z?

When a row is written into the first table it requires a security question from the second table. However, the possible choices are all the questions from the second table. I want to enforce a restriction that any user didn't pick any question twice.

How can I do this? Should this be relegated to my application code?

Body:
This is a little tricky.  Often, it is not reasonable to store the same entity in multiple columns.  This is a case where it might make sense.

You can readily do what you want with a check constraint:

alter table t add constraint check_t_security
    check (SecurityQuestion1 <> SecurityQuestion2 and
           SecurityQuestion2 <> SecurityQuestion3 and
           SecurityQuestion3 <> SecurityQuestion1
          );

The logic is similar but more cumbersome if NULL values are allowed for the questions.  You would have to specify if a user could have more than one NULL value.

You can shorten the logic to:

alter table t add constraint check_t_security
    check (SecurityQuestion1 not in (SecurityQuestion2, SecurityQuestion3) and
           SecurityQuestion2 not in (SecurityQuestion3)
          );


问:
What is the mime type to use for JSON Web Encryption
Looking at RFC 7515 and RFC 7516, I was trying to understand what the proper mime type for the JWE should be. It looks like JWE and JWS share the JOSE header information, and JWS defines its mime type as application/jose. JWE has no explicit media type information. But since the name is "jose" and both use JOSE header, I assume both should use the same mime type (also because JOSE stands for ... Signing and Encryption).

In this case, how do I differentiate between signed and/or encrypted messages? By value of the alg property? Or by presence/value of enc property?

To summarize:

Is "application/jose" a mime type to use for JWE? If not, then what should it be?

If yes, how to reliably tell between JWE and JWS messages?

答:
If I only paid more attention to the original RFC, I would have noticed that there is a section for this particular purpose (section 9).

In short, the code should examine presence of payload, ciphertext or enc properties, or by checking the value of alg. Alternatively, count period separators if compact serialization is used.

This also implies that the mime type for both is the same.

ContentLicense: CC BY-SA 4.0


问:
AdMob ads not displaying in Xamarin Android application
I have recently managed to complete and deploy my first Android app to Google Play, and now I am trying to add AdMob.

After a few false starts, several clean-ups and rebuilds I am at the point where the application is building but I can't get the ads to display.

So, I have created a content view called AdMobView;

```<code>using Xamarin.Forms;

namespace MyApplication
{
    public partial class AdMobView : ContentView
    {
        public AdMobView()
        {
        }
    }
}
</code>```

And then following class;

```<code>using Android.Gms.Ads;
using Xamarin.Forms;
using MyApplication;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(AdMobView), typeof(AdMobRenderer))]

namespace MyApplication
{
    public class AdMobRenderer : ViewRenderer <AdMobView, AdView>
    {
        protected override void    OnElementChanged(ElementChangedEventArgs<AdMobView> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                var ad = new Android.Gms.Ads.AdView(Forms.Context);
                ad.AdSize = Android.Gms.Ads.AdSize.Banner;
                ad.AdUnitId = "<the AdUnit id>";

                var requestbuilder = new Android.Gms.Ads.AdRequest.Builder();
                ad.LoadAd(requestbuilder.Build());

                SetNativeControl(ad);
            }
        }
    }
}
</code>```

In the XAML where I want the ad displayed, I have added

```<code><controls:AdMobView WidthRequest="320" HeightRequest="50" />
</code>```

Also in this XAML, I have added an xmln for the control

```<code>xmlns:controls="clr-namespace:MyApplication;assembly=MyApplication"
</code>```

In the MainActivity.cs I have added

```<code>MobileAds.Initialize(ApplicationContext, "<the AdUnit id>");
</code>```

In the AssemblyInfo.cs I have added;

```<code>[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.AccessNetworkState)]
</code>```

In AndroidManifest.xml I have added;

```<code>    <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
    <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
</code>```

So, as I said, this builds fine and runs in debug mode on both a real device and in emulator, but  there is nothing in the area the ads should show.  i can just see the normal background - there isn't even a "blank" box.

If anyone has any ideas, you could save me a few sleepless nights!

答:
OK, I have managed to get it working.

In case anyone else is struggling, I'm going to post the full code here, as I did not find one tutorial which worked by itself and had to piece together from several sources...

Android Manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"   package="<your package name>"
      android:versionCode="<your version code>" android:versionName="<your version number>" android:installLocation="auto">
<uses-sdk android:minSdkVersion="16" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:label="<your app title>" android:icon="@drawable/Icon">
    <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
    <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
</application>
</code>```

MainActivity.cs:

```<code> using Android.Gms.Ads;
 .
 .
 .
 MobileAds.Initialize(ApplicationContext, "<your unit id>");
 LoadApplication(new App());
</code>```

Important Note - make sure this is the app unit id and not the app id which look similiar.  The unit id is the one which has format
ca-app-pub-9nnnnnnnnnnnnnnn/nnnnnnnnnn
The app id looks similiar but has a ~ instead of a /
If you are using a LoadApplication in the main activity, make sure this is after the Initialize - thats one of the schoolboy errors i was making.  In VS2015 this actually has a green underline with a message stating it is deprecated, but I found it still is required for ads to be served.

Create a View called AdMobView.cs:

```<code>using Xamarin.Forms;

namespace FightJudgeAssistant
{
    public class AdMobView : View
    {

    }
}
</code>```

when you create a view in Visual Studio, it puts in different Using statements.  You can get rid of all these and just have the Using Xamarin.Forms

Create a class called AdViewRenderer.cs:

```<code>using Android.Widget;
using Android.Gms.Ads;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using FightJudgeAssistant;

[assembly: ExportRenderer(typeof(mynamespace.AdMobView),     typeof(AdMobRenderer))]

namespace mynamespace
{
public class AdMobRenderer : ViewRenderer<mynamespace.AdMobView, Android.Gms.Ads.AdView>
{
    protected override void OnElementChanged(ElementChangedEventArgs<mynamespace.AdMobView> e)
    {
        base.OnElementChanged(e);

        if (Control == null)
        {
            var ad = new Android.Gms.Ads.AdView(Forms.Context);
            ad.AdSize = Android.Gms.Ads.AdSize.Banner;
            ad.AdUnitId = "<your unit id>";

            var requestbuilder = new Android.Gms.Ads.AdRequest.Builder();
            ad.LoadAd(requestbuilder.Build());

            SetNativeControl(ad);
        }
    }
}
</code>```

}

On the screen you want to display the ad (in my case its an XAML within a grid view):

```<code><ContentPage.Content>
<Grid x:Name="controlGrid" RowSpacing="1" ColumnSpacing="1">

        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        .
        .
        .
        .
        <controls:AdMobView Grid.Row="6"/>
    </Grid>
</code>```

I have other content in the grid rows not shown above.  You'll notice I have set the row height for row 6 to be "auto" instead of "*" to ensure the ad takes up as much space as required.

Also added the following XMLNS in the ContentPage section:

```<code>xmlns:controls="clr-namespace:mynamespace;assembly=myAssemblyname>
</code>```

And thats about it!  To test this worked I used ca-app-pub-3940256099942544/6300978111 which is specifically for testing banner ads

Body:
I have recently managed to complete and deploy my first Android app to Google Play, and now I am trying to add AdMob.

After a few false starts, several clean-ups and rebuilds I am at the point where the application is building but I can't get the ads to display.

So, I have created a content view called AdMobView;

using Xamarin.Forms;

namespace MyApplication
{
    public partial class AdMobView : ContentView
    {
        public AdMobView()
        {
        }
    }
}

And then following class;

using Android.Gms.Ads;
using Xamarin.Forms;
using MyApplication;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(AdMobView), typeof(AdMobRenderer))]

namespace MyApplication
{
    public class AdMobRenderer : ViewRenderer <AdMobView, AdView>
    {
        protected override void    OnElementChanged(ElementChangedEventArgs<AdMobView> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                var ad = new Android.Gms.Ads.AdView(Forms.Context);
                ad.AdSize = Android.Gms.Ads.AdSize.Banner;
                ad.AdUnitId = "<the AdUnit id>";

                var requestbuilder = new Android.Gms.Ads.AdRequest.Builder();
                ad.LoadAd(requestbuilder.Build());

                SetNativeControl(ad);
            }
        }
    }
}

In the XAML where I want the ad displayed, I have added

<controls:AdMobView WidthRequest="320" HeightRequest="50" />

Also in this XAML, I have added an xmln for the control

xmlns:controls="clr-namespace:MyApplication;assembly=MyApplication"

In the MainActivity.cs I have added

MobileAds.Initialize(ApplicationContext, "<the AdUnit id>");

In the AssemblyInfo.cs I have added;

[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.AccessNetworkState)]

In AndroidManifest.xml I have added;

    <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
    <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />

So, as I said, this builds fine and runs in debug mode on both a real device and in emulator, but  there is nothing in the area the ads should show.  i can just see the normal background - there isn't even a "blank" box.

If anyone has any ideas, you could save me a few sleepless nights!

Body:
OK, I have managed to get it working.

In case anyone else is struggling, I'm going to post the full code here, as I did not find one tutorial which worked by itself and had to piece together from several sources...

Android Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"   package="<your package name>"
      android:versionCode="<your version code>" android:versionName="<your version number>" android:installLocation="auto">
<uses-sdk android:minSdkVersion="16" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:label="<your app title>" android:icon="@drawable/Icon">
    <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
    <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
</application>

MainActivity.cs:

 using Android.Gms.Ads;
 .
 .
 .
 MobileAds.Initialize(ApplicationContext, "<your unit id>");
 LoadApplication(new App());

Important Note - make sure this is the app unit id and not the app id which look similiar.  The unit id is the one which has format
ca-app-pub-9nnnnnnnnnnnnnnn/nnnnnnnnnn
The app id looks similiar but has a ~ instead of a /
If you are using a LoadApplication in the main activity, make sure this is after the Initialize - thats one of the schoolboy errors i was making.  In VS2015 this actually has a green underline with a message stating it is deprecated, but I found it still is required for ads to be served.

Create a View called AdMobView.cs:

using Xamarin.Forms;

namespace FightJudgeAssistant
{
    public class AdMobView : View
    {

    }
}

when you create a view in Visual Studio, it puts in different Using statements.  You can get rid of all these and just have the Using Xamarin.Forms

Create a class called AdViewRenderer.cs:

using Android.Widget;
using Android.Gms.Ads;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using FightJudgeAssistant;

[assembly: ExportRenderer(typeof(mynamespace.AdMobView),     typeof(AdMobRenderer))]

namespace mynamespace
{
public class AdMobRenderer : ViewRenderer<mynamespace.AdMobView, Android.Gms.Ads.AdView>
{
    protected override void OnElementChanged(ElementChangedEventArgs<mynamespace.AdMobView> e)
    {
        base.OnElementChanged(e);

        if (Control == null)
        {
            var ad = new Android.Gms.Ads.AdView(Forms.Context);
            ad.AdSize = Android.Gms.Ads.AdSize.Banner;
            ad.AdUnitId = "<your unit id>";

            var requestbuilder = new Android.Gms.Ads.AdRequest.Builder();
            ad.LoadAd(requestbuilder.Build());

            SetNativeControl(ad);
        }
    }
}

}

On the screen you want to display the ad (in my case its an XAML within a grid view):

<ContentPage.Content>
<Grid x:Name="controlGrid" RowSpacing="1" ColumnSpacing="1">

        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        .
        .
        .
        .
        <controls:AdMobView Grid.Row="6"/>
    </Grid>

I have other content in the grid rows not shown above.  You'll notice I have set the row height for row 6 to be "auto" instead of "*" to ensure the ad takes up as much space as required.

Also added the following XMLNS in the ContentPage section:

xmlns:controls="clr-namespace:mynamespace;assembly=myAssemblyname>

And thats about it!  To test this worked I used ca-app-pub-3940256099942544/6300978111 which is specifically for testing banner ads


问:
Releasing updates to your android application
I put out an android app last week, and wanted to release an update to it that will include additional phrases to a specific aspect of the app.  It isn't a big release that serves as a bug fix (no known bugs actually - fingers crossed ;p) but it will certainly add to the entertainment value of the app and add a lot of flexibility.

Is this poor practice, as new releases should include a lot of content or is this accepted for the most part?

Thanks!

答:
IMHO that's fine - in fact desirable.

Additional content is always welcome.

I use a Spanish Verbs app, and early on it had some important verbs missing, but I was glad when they came in soon after.


问:
Oracle - Extract multiple substrings from a string
I need to extract all e-mail accounts mentioned on a single string, so far I've tried with SUBSTR and INSTR, but with no success, here an example:

The string looks like this:

```<code>()
string = "User_1" {user_1@domain.com};"User_2" {user_2@domain.com};"User_3" {user_3@domain.com};"User_4" {user_4@domain.com};

select SUBSTR(string ,INSTR(string ,'<',-1,2)) EMAIL
from dual;
</code>```

What I need is something like this:

```<code>user_1@domain.com;user_2@domain.com;user_3@domain.com;user_4@domain.com;
</code>```

答:
Looking for the preceding { and the following }; which seems to appear in your string you can use:

```<code>SELECT REGEXP_REPLACE(
         '"User_1" {user_1@domain.com};"User_2" {user_2@domain.com};"User_3" {user_3@domain.com};"User_4" {user_4@domain.com};',
         '.*?\{(.*?)\};',
         '\1;'
       ) AS emails
FROM   DUAL;
</code>```

Output:

```<code>EMAILS
------------------------------------------------------------------------
user_1@domain.com;user_2@domain.com;user_3@domain.com;user_4@domain.com;
</code>```

Body:
I need to extract all e-mail accounts mentioned on a single string, so far I've tried with SUBSTR and INSTR, but with no success, here an example:

The string looks like this:

()
string = "User_1" {user_1@domain.com};"User_2" {user_2@domain.com};"User_3" {user_3@domain.com};"User_4" {user_4@domain.com};

select SUBSTR(string ,INSTR(string ,'<',-1,2)) EMAIL
from dual;

What I need is something like this:

user_1@domain.com;user_2@domain.com;user_3@domain.com;user_4@domain.com;

Body:
Looking for the preceding { and the following }; which seems to appear in your string you can use:

SELECT REGEXP_REPLACE(
         '"User_1" {user_1@domain.com};"User_2" {user_2@domain.com};"User_3" {user_3@domain.com};"User_4" {user_4@domain.com};',
         '.*?\{(.*?)\};',
         '\1;'
       ) AS emails
FROM   DUAL;

Output:

EMAILS
------------------------------------------------------------------------
user_1@domain.com;user_2@domain.com;user_3@domain.com;user_4@domain.com;


问:
Issue with changing JButton size

I'm trying to make a mine sweeper game with Swing library (just for training).
I spotted a problem when I tried to change size of a button with setSize() method (part of Container class). One of my previous program was able to handle that (with ActionListener)

```<code>import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonChanger extends JFrame {

JButton big, small, dis;
JLabel message, poof;

public ButtonChanger(){
    setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    message = new JLabel("Click to make it");
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 0;
    add(message, c);

    big =  new JButton("BIG");
    big.setSize(30, 30); // no reaction for this call
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 1;
    add(big, c);

    small = new JButton("small");
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 1;
    c.gridy = 1;
    add(small, c);

    dis = new JButton("disapear");
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 3;
    c.gridy = 1;
    add(dis, c);

    poof = new JLabel("  poof!");
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 3;
    c.gridy = 1;
    poof.setVisible(false);
    add(poof, c);

    big.setSize(300,300); // same story

    event a = new event();
    big.addActionListener(a);
    small.addActionListener(a);
    dis.addActionListener(a);
}

public class event implements ActionListener{
    public void actionPerformed(ActionEvent a){

        String op = a.getActionCommand();

        if(op.equals("BIG")){
            big.setSize(50,50); // finaly!
        } else if(op.equals("small")){
            small.setSize(10,10);
        } else if(op.equals("disapear")){
            dis.setVisible(false);
            poof.setVisible(true);
        }

    }
}

public static void main(String args[]){
    ButtonChanger gui = new ButtonChanger();
    gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    gui.setVisible(true);
    gui.setSize(250,250);
    gui.setTitle("");
}
}
</code>```

But when I tried to use same solution here - nothing happened.

```<code>import java.util.Random;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Board extends JPanel
               implements ActionListener{
private Integer pixelWidth;
private Integer pixelHeight;
public Field[][] board;

private Random generator = new Random();

public Board(int width,int height){ // width - x axis scaled with "button" unit
    // height -  y axis scaled with "button" unit

    setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    board = new Field[width][height];

    pixelWidth = width * Field.fieldW;
    pixelHeight = height * Field.fieldH;

    for(int i = 0;i < height;i++)
        for(int j = 0;j < width;j++){
            board[i][j] = new Field(generator.nextBoolean());
        }

    for(int i = 0;i < height;i++){
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridy = i;
        for(int j = 0;j < width;j++){
            c.gridx = j;
            add(board[i][j].getFieldButton(),c);
            add(board[i][j].getFieldLabel(),c);
        }
    }

/*  for(int i = 0;i < height;i++)
        for(int j = 0;j < width;j++){
            board[i][j].setField();
        }*/

}
public void actionPerformed(ActionEvent e){
    String co = e.getActionCommand();
    if(co.equals(" ")){ // button is single space sign
        for(int i = 0;i < 10;i++)
            for(int j = 0;j < 10;j++){
                board[i][j].setField(); //inside this method is call for setSize() for fieldButton
                }
    }
}
}
</code>```

Previously I changed Board class to make it inhetitate after JFrame  (set up as main GUI frame in whole code) but that gave me same output as original.

Did I mess up something?

答:
```<code>big =  new JButton("BIG");
big.setSize(30, 30); // no reaction for this call
c.fill = GridBagConstraints.HORIZONTAL;
</code>```

There is no reaction for big.setSize... because then in GridBagConstraints you set fill to horizontal, so button will be "stretched" to fill horizontally.

Instead use c.fill = GridBagConstraints.NONE

fill

Used when the component's display area is larger than the component's requested size to determine whether and how to resize the component. Valid values (defined as GridBagConstraints constants) include NONE (the default), HORIZONTAL (make the component wide enough to fill its display area horizontally, but do not change its height), VERTICAL (make the component tall enough to fill its display area vertically, but do not change its width), and BOTH (make the component fill its display area entirely).

You can read more here: https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html

Title: Issue with changing JButton size

Body:
I'm trying to make a mine sweeper game with Swing library (just for training).
I spotted a problem when I tried to change size of a button with setSize() method (part of Container class). One of my previous program was able to handle that (with ActionListener)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonChanger extends JFrame {

JButton big, small, dis;
JLabel message, poof;

public ButtonChanger(){
    setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    message = new JLabel("Click to make it");
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 0;
    add(message, c);

    big =  new JButton("BIG");
    big.setSize(30, 30); // no reaction for this call
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 1;
    add(big, c);

    small = new JButton("small");
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 1;
    c.gridy = 1;
    add(small, c);

    dis = new JButton("disapear");
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 3;
    c.gridy = 1;
    add(dis, c);

    poof = new JLabel("  poof!");
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 3;
    c.gridy = 1;
    poof.setVisible(false);
    add(poof, c);

    big.setSize(300,300); // same story

    event a = new event();
    big.addActionListener(a);
    small.addActionListener(a);
    dis.addActionListener(a);
}

public class event implements ActionListener{
    public void actionPerformed(ActionEvent a){

        String op = a.getActionCommand();

        if(op.equals("BIG")){
            big.setSize(50,50); // finaly!
        } else if(op.equals("small")){
            small.setSize(10,10);
        } else if(op.equals("disapear")){
            dis.setVisible(false);
            poof.setVisible(true);
        }

    }
}

public static void main(String args[]){
    ButtonChanger gui = new ButtonChanger();
    gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    gui.setVisible(true);
    gui.setSize(250,250);
    gui.setTitle("");
}
}

But when I tried to use same solution here - nothing happened.

import java.util.Random;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Board extends JPanel
               implements ActionListener{
private Integer pixelWidth;
private Integer pixelHeight;
public Field[][] board;

private Random generator = new Random();

public Board(int width,int height){ // width - x axis scaled with "button" unit
    // height -  y axis scaled with "button" unit

    setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    board = new Field[width][height];

    pixelWidth = width * Field.fieldW;
    pixelHeight = height * Field.fieldH;

    for(int i = 0;i < height;i++)
        for(int j = 0;j < width;j++){
            board[i][j] = new Field(generator.nextBoolean());
        }

    for(int i = 0;i < height;i++){
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridy = i;
        for(int j = 0;j < width;j++){
            c.gridx = j;
            add(board[i][j].getFieldButton(),c);
            add(board[i][j].getFieldLabel(),c);
        }
    }

/*  for(int i = 0;i < height;i++)
        for(int j = 0;j < width;j++){
            board[i][j].setField();
        }*/

}
public void actionPerformed(ActionEvent e){
    String co = e.getActionCommand();
    if(co.equals(" ")){ // button is single space sign
        for(int i = 0;i < 10;i++)
            for(int j = 0;j < 10;j++){
                board[i][j].setField(); //inside this method is call for setSize() for fieldButton
                }
    }
}
}

Previously I changed Board class to make it inhetitate after JFrame  (set up as main GUI frame in whole code) but that gave me same output as original.

Did I mess up something?

Body:
big =  new JButton("BIG");
big.setSize(30, 30); // no reaction for this call
c.fill = GridBagConstraints.HORIZONTAL;

There is no reaction for big.setSize... because then in GridBagConstraints you set fill to horizontal, so button will be "stretched" to fill horizontally.

Instead use c.fill = GridBagConstraints.NONE

fill

Used when the component's display area is larger than the component's requested size to determine whether and how to resize the component. Valid values (defined as GridBagConstraints constants) include NONE (the default), HORIZONTAL (make the component wide enough to fill its display area horizontally, but do not change its height), VERTICAL (make the component tall enough to fill its display area vertically, but do not change its width), and BOTH (make the component fill its display area entirely).

You can read more here: https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html


问:
How to mock external module method?
I have this module with a function in it:

```<code>const utils = {
  redirectTo(url) {
    if (url) {
      window.location = url;
    }
  },
};

export default utils;
</code>```

It is used somewhere in a React component like this:

```<code>import utils from '../../lib/utils';

componentWillUpdate() {
  this.redirectTo('foo')
}
</code>```

Now I want to check that the value that redirectTo is called with equals foo.

```<code>  it('should redirect if no rights', () => {
    const mockRedirectFn = jest.fn();
    utils.redirectTo = mockRedirectFn;

    mount(
      <SomeComponent />,
    );

    expect(mockRedirectFn).toBeCalled();
    expect(mockRedirectFn).toBeCalledWith('foo');
    console.log(mockRedirectFn.mock);
    // { calls: [], instances: [] }
  });
</code>```

Thats what I've got and it does not work. How do I do this?

答:
This is what I ended up using:</p>

```<code> it('should redirect if no rights', () => {

    // this way we mock only one method: redirectTo
    jest.mock('lib/utils', () => {
      const original = require.requireActual('lib/utils');
      original.default.redirectTo = jest.fn();
      return original;
    });

    const redirectTo = require.requireMock('lib/utils').default.redirectTo;

    mount(
      <SomeComponent />,
    );

    expect(redirectTo).toHaveBeenCalled();
  });
</code>```

Title: How to mock external module method?

Body:
I have this module with a function in it:

const utils = {
  redirectTo(url) {
    if (url) {
      window.location = url;
    }
  },
};

export default utils;

It is used somewhere in a React component like this:

import utils from '../../lib/utils';

componentWillUpdate() {
  this.redirectTo('foo')
}

Now I want to check that the value that redirectTo is called with equals foo.

  it('should redirect if no rights', () => {
    const mockRedirectFn = jest.fn();
    utils.redirectTo = mockRedirectFn;

    mount(
      <SomeComponent />,
    );

    expect(mockRedirectFn).toBeCalled();
    expect(mockRedirectFn).toBeCalledWith('foo');
    console.log(mockRedirectFn.mock);
    // { calls: [], instances: [] }
  });

Thats what I've got and it does not work. How do I do this?

Body:
This is what I ended up using:

 it('should redirect if no rights', () => {

    // this way we mock only one method: redirectTo
    jest.mock('lib/utils', () => {
      const original = require.requireActual('lib/utils');
      original.default.redirectTo = jest.fn();
      return original;
    });

    const redirectTo = require.requireMock('lib/utils').default.redirectTo;

    mount(
      <SomeComponent />,
    );

    expect(redirectTo).toHaveBeenCalled();
  });


问:
Remove sql table after x days
I am looking for a way for my system made in C ++ to remove old sqls tables after 90 days, I searched but did not find anything related.

The names of my tables are generated according to the days, for example 20170323

Now the way to remove I can not think of anything that can be done

答:
If you want to do the logic in C++ and are willing to use Howard Hinnant's free, open-source, header-only date library, you could write a function something like this:

```<code>#include "date.h"
#include <sstream>

void
maybe_remove_table(const std::string& tablename)
{
    using namespace std;
    using namespace std::chrono;
    using namespace date;
    istringstream in{tablename};
    sys_days table_date;
    in >> parse("%Y%m%d", table_date);
    sys_days today = floor<days>(system_clock::now());
    if (table_date < today - days{90})
        remove_table(tablename);
}
</code>```

This function converts the name of the table into a date::sys_days, which is a type alias for std::chrono::time_point<system_clock, days>.  This is just a coarse time_point.  Then it gets the current day (as defined by UTC), and compares the date of the table to 90 days prior to the current day.

Title: Remove sql table after x days

Body:
If you want to do the logic in C++ and are willing to use Howard Hinnant's free, open-source, header-only date library, you could write a function something like this:

#include "date.h"
#include <sstream>

void
maybe_remove_table(const std::string& tablename)
{
    using namespace std;
    using namespace std::chrono;
    using namespace date;
    istringstream in{tablename};
    sys_days table_date;
    in >> parse("%Y%m%d", table_date);
    sys_days today = floor<days>(system_clock::now());
    if (table_date < today - days{90})
        remove_table(tablename);
}

This function converts the name of the table into a date::sys_days, which is a type alias for std::chrono::time_point<system_clock, days>.  This is just a coarse time_point.  Then it gets the current day (as defined by UTC), and compares the date of the table to 90 days prior to the current day.


问:
instantiate model object in jsp web project
Im writing an web application using the MVC design pattern.. the application should connect to a RMI server providing the business part (Model)

my problem is, I dont know where i should instantiate the model class and connect to the RMI, providing access to all servlets.. i added a ServletContextListener and shared the reference on the servlet context, but i dont think that is the right way to do it

thanks in advance

答:
You can instantiate your Model/Business classes from your Controller. Better still make a single instance (Just Create One) of each in the start of the application. You can also go lazy-loading about it.

Instantiating Model/Business classes from your JSPs means, instantiating them from View. That, of course, violates the MVC pattern.

Either you can make your Model/Business classes as Singleton, or keep the reference in Servlet Context. Both are fine and the latter is more test friendly. The former can be made test friendly too, if you don't specify the constructor as private but just have a common understanding that it's not there for instantiating it everywhere.


问:
how to read from file and add to object data?
```<code>17  5
12  8
15  22
17  11
33  21
43  15
15  4
44  35
23  19
10  23
55  39
8   6
21  9
20  28
20  13
45  29
18  16
21  19
68  55
10  16
33  54
3   1
5   9
</code>```

I am trying to read in input.txt file that looks like input above but the problem is that the program only reads in the last line from the text file.

Here is my code:

```<code>import java.io.FileNotFoundException;
import java.io.*;
import java.io.IOException;
import java.util.*;
import java.util.Scanner;

/**
 *
 */
public class ReadIn {

public static void main(String[] args) throws IOException {

    //List<Integer> value = new ArrayList<Integer>();
    //List<Integer> weight = new ArrayList<Integer>();
    FileReader readFile = new FileReader ("C:\\Users\\owner\\IdeaProjects\\knapsack\\src\\input");
    BufferedReader br = new BufferedReader(readFile);
    Scanner input = new Scanner(br);
    Scanner keyboard = new Scanner(System.in);
    //List<Items> items = new ArrayList<Items>();

    Items[] items= new Items[23];//this only creates references that are set to their default value null which throws a null exception
    for(int i =0 ; i <items.length; i++) {//fixes null exception

        items[i] = new Items();//fully creates the objects

        while (input.hasNext()) {//read in file input to object data
            items[i].setValue(input.nextInt());
            items[i].setWeight(input.nextInt());
            items[i].setId(i);
        }
    }
    input.close();
    input.reset();
    System.out.println("What is the max capacity for the knapsack? ");
    Integer maxCapacity = keyboard.nextInt();
    System.out.println(maxCapacity);
    int[] maxWeight = new int[maxCapacity];//creates int array so we can use the index as the maxWeight as the number of fields
    printArray(items);

}
    public static void printArray(Items[] x) {

        for (int i = 0; i < x.length; i++) {
            x[i] = new Items();
            System.out.println(x[i].getValue() + " " + x[i].getWeight() + " " + x[i].getId() + " ");
        }
    }

}
</code>```

Thanks for the help I am stuck!!
I have also attached the Items class that i am trying to use

```<code>    public class Items {
        private Integer value ;
        private Integer weight;
        private Integer Id;

        public Items(){
            this.value = 0;
            this.weight = 0;
            this.Id =0;
        }

        public Items(Integer v, Integer w, Integer ID){
            this.value = v;
            this.weight = w;
            this.Id = ID;
        }

        public Integer getValue() {
            return value;
        }

        public void setValue(Integer value) {
            this.value = value;
        }

        public Integer getWeight() {
            return weight;
        }

        public void setWeight(Integer weight) {
            this.weight = weight;
        }

        public Integer getId() {
            return Id;
        }

        public void setId(Integer id) {//sets id
            Id = id;
        }
    }
</code>```

This is the end of the code

答:
Maybe this will be useful:

UPDATE:

You should declare and initialize the j variable and within the while loop the variable j increases by 1 in each loop:

```<code>int j=0; // ----> initialize j variable
while (input.hasNext()) {
    items[j].setValue(input.nextInt());
    items[j].setWeight(input.nextInt());
    items[j].setId(j);
    j++; // ----> increment 1 y each loop
}
</code>```

In the printArray (Items[] x) method inside the for loop you should not define this:

```<code>x[i] = new Items();
</code>```

because in each iteration create a new object and when print it will be 0 0 0

Here the example:

```<code>public class MyTree {
    public static void main(String[] args) throws IOException {

        FileReader readFile = new FileReader("C:\\Users\\owner\\IdeaProjects\\knapsack\\src\\input");
        BufferedReader br = new BufferedReader(readFile);
        Scanner input = new Scanner(br);
        Scanner keyboard = new Scanner(System.in);

        Items[] items = new Items[23];//this only creates references that are set to their default value null which throws a null exception
        for (int i = 0; i < items.length; i++) {//fixes null exception
            items[i] = new Items();//fully creates the objects
        }

        int j=0; // ----> initialize j variable
        while (input.hasNext()) {
            items[j].setValue(input.nextInt());
            items[j].setWeight(input.nextInt());
            items[j].setId(j);
            j++; // ----> increment 1 y each loop
        }

        input.close();
        input.reset();
        System.out.println("What is the max capacity for the knapsack? ");
        Integer maxCapacity = keyboard.nextInt();
        System.out.println(maxCapacity);
        int[] maxWeight = new int[maxCapacity];//creates int array so we can use the index as the maxWeight as the number of fields
        printArray(items);

    }

    public static void printArray(Items[] x) {

        for (int i = 0; i < x.length; i++) {
            //x[i] = new Items();  //It shouldn't be here, because in each iteration create a new object
            System.out.println(x[i].getValue() + " " + x[i].getWeight() + " " + x[i].getId() + " ");
        }
    }
}
</code>```

Body:
17  5
12  8
15  22
17  11
33  21
43  15
15  4
44  35
23  19
10  23
55  39
8   6
21  9
20  28
20  13
45  29
18  16
21  19
68  55
10  16
33  54
3   1
5   9

I am trying to read in input.txt file that looks like input above but the problem is that the program only reads in the last line from the text file.

Here is my code:

import java.io.FileNotFoundException;
import java.io.*;
import java.io.IOException;
import java.util.*;
import java.util.Scanner;

/**
 *
 */
public class ReadIn {

public static void main(String[] args) throws IOException {

    //List<Integer> value = new ArrayList<Integer>();
    //List<Integer> weight = new ArrayList<Integer>();
    FileReader readFile = new FileReader ("C:\\Users\\owner\\IdeaProjects\\knapsack\\src\\input");
    BufferedReader br = new BufferedReader(readFile);
    Scanner input = new Scanner(br);
    Scanner keyboard = new Scanner(System.in);
    //List<Items> items = new ArrayList<Items>();

    Items[] items= new Items[23];//this only creates references that are set to their default value null which throws a null exception
    for(int i =0 ; i <items.length; i++) {//fixes null exception

        items[i] = new Items();//fully creates the objects

        while (input.hasNext()) {//read in file input to object data
            items[i].setValue(input.nextInt());
            items[i].setWeight(input.nextInt());
            items[i].setId(i);
        }
    }
    input.close();
    input.reset();
    System.out.println("What is the max capacity for the knapsack? ");
    Integer maxCapacity = keyboard.nextInt();
    System.out.println(maxCapacity);
    int[] maxWeight = new int[maxCapacity];//creates int array so we can use the index as the maxWeight as the number of fields
    printArray(items);

}
    public static void printArray(Items[] x) {

        for (int i = 0; i < x.length; i++) {
            x[i] = new Items();
            System.out.println(x[i].getValue() + " " + x[i].getWeight() + " " + x[i].getId() + " ");
        }
    }

}

Thanks for the help I am stuck!!
I have also attached the Items class that i am trying to use

    public class Items {
        private Integer value ;
        private Integer weight;
        private Integer Id;

        public Items(){
            this.value = 0;
            this.weight = 0;
            this.Id =0;
        }

        public Items(Integer v, Integer w, Integer ID){
            this.value = v;
            this.weight = w;
            this.Id = ID;
        }

        public Integer getValue() {
            return value;
        }

        public void setValue(Integer value) {
            this.value = value;
        }

        public Integer getWeight() {
            return weight;
        }

        public void setWeight(Integer weight) {
            this.weight = weight;
        }

        public Integer getId() {
            return Id;
        }

        public void setId(Integer id) {//sets id
            Id = id;
        }
    }

This is the end of the code

Body:
Maybe this will be useful:

UPDATE:

You should declare and initialize the j variable and within the while loop the variable j increases by 1 in each loop:

int j=0; // ----> initialize j variable
while (input.hasNext()) {
    items[j].setValue(input.nextInt());
    items[j].setWeight(input.nextInt());
    items[j].setId(j);
    j++; // ----> increment 1 y each loop
}

In the printArray (Items[] x) method inside the for loop you should not define this:

x[i] = new Items();

because in each iteration create a new object and when print it will be 0 0 0

Here the example:

public class MyTree {
    public static void main(String[] args) throws IOException {

        FileReader readFile = new FileReader("C:\\Users\\owner\\IdeaProjects\\knapsack\\src\\input");
        BufferedReader br = new BufferedReader(readFile);
        Scanner input = new Scanner(br);
        Scanner keyboard = new Scanner(System.in);

        Items[] items = new Items[23];//this only creates references that are set to their default value null which throws a null exception
        for (int i = 0; i < items.length; i++) {//fixes null exception
            items[i] = new Items();//fully creates the objects
        }

        int j=0; // ----> initialize j variable
        while (input.hasNext()) {
            items[j].setValue(input.nextInt());
            items[j].setWeight(input.nextInt());
            items[j].setId(j);
            j++; // ----> increment 1 y each loop
        }

        input.close();
        input.reset();
        System.out.println("What is the max capacity for the knapsack? ");
        Integer maxCapacity = keyboard.nextInt();
        System.out.println(maxCapacity);
        int[] maxWeight = new int[maxCapacity];//creates int array so we can use the index as the maxWeight as the number of fields
        printArray(items);

    }

    public static void printArray(Items[] x) {

        for (int i = 0; i < x.length; i++) {
            //x[i] = new Items();  //It shouldn't be here, because in each iteration create a new object
            System.out.println(x[i].getValue() + " " + x[i].getWeight() + " " + x[i].getId() + " ");
        }
    }
}


问:
How to get more than 100 results from Google Custom Search API
I am trying to use Google Custom Search API for research purposes in Java. As a result I'm gonna need a big result set for each query. However it seems that I'm limited with first 100 results which is much less than what I need. I use the list method like this:

```<code>list.setStart(90L);
</code>```

And when I set it to start from index 100 I get this error:

```<code>com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request

{   "code" : 400,
    "errors" : [ {
    "domain" : "global",
    "message" : "Invalid Value",
    "reason" : "invalid"
  } ],
    "message" : "Invalid Value"
}
</code>```

Is there any way to remove this limitation?

答: You can use lowRange and highRange to solve this problem. See: https://productforums.google.com/forum/#!topic/customsearch/2qilVDaCz0A</p>

Body:
I am trying to use Google Custom Search API for research purposes in Java. As a result I'm gonna need a big result set for each query. However it seems that I'm limited with first 100 results which is much less than what I need. I use the list method like this:

list.setStart(90L);

And when I set it to start from index 100 I get this error:

com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request

{   "code" : 400,
    "errors" : [ {
    "domain" : "global",
    "message" : "Invalid Value",
    "reason" : "invalid"
  } ],
    "message" : "Invalid Value"
}

Is there any way to remove this limitation?