问:
What are alternatives to this typelist-based class hierarchy generation code?
I'm working with a simple object model in which objects can implement interfaces to provide optional functionality. At it's heart, an object has to implement a getInterface method which is given a (unique) interface ID. The method then returns a pointer to an interface - or null, in case the object doesn't implement the requested interface. Here's a code sketch to illustrate this:

```<code>struct Interface { };
struct FooInterface : public Interface { enum { Id = 1 }; virtual void doFoo() = 0; };
struct BarInterface : public Interface { enum { Id = 2 }; virtual void doBar() = 0; };
struct YoyoInterface : public Interface { enum { Id = 3 }; virtual void doYoyo() = 0; };

struct Object {
    virtual Interface *getInterface( int id ) { return 0; }
};
</code>```

To make things easier for clients who work in this framework, I'm using a little template which automatically generates the 'getInterface' implementation so that clients just have to implement the actual functions required by the interfaces. The idea is to derive a concrete type from Object as well as all the interfaces and then let getInterface just return pointers to this (casted to the right type). Here's the template and a demo usage:

```<code>struct NullType { };
template <class T, class U>
struct TypeList {
    typedef T Head;
    typedef U Tail;
};

template <class Base, class IfaceList>
class ObjectWithIface :
    public ObjectWithIface<Base, typename IfaceList::Tail>,
    public IfaceList::Head
{
public:
    virtual Interface *getInterface( int id ) {
        if ( id == IfaceList::Head::Id ) {
            return static_cast<IfaceList::Head *>( this );
        }
        return ObjectWithIface<Base, IfaceList::Tail>::getInterface( id );
    }
};

template <class Base>
class ObjectWithIface<Base, NullType> : public Base
{
public:
    virtual Interface *getInterface( int id ) {
        return Base::getInterface( id );
    }
};

class MyObjectWithFooAndBar : public ObjectWithIface< Object, TypeList<FooInterface, TypeList<BarInterface, NullType> > >
{
public:
    // We get the getInterface() implementation for free from ObjectWithIface
    virtual void doFoo() { }
    virtual void doBar() { }
};
</code>```

This works quite well, but there are two problems which are ugly:

A blocker for me is that this doesn't work with MSVC6 (which has poor support for templates, but unfortunately I need to support it). MSVC6 yields a C1202 error when compiling this.

A whole range of classes (a linear hierarchy) is generated by the recursive ObjectWithIface template. This is not a problem for me per se, but unfortunately I can't just do a single switch statement to map an interface ID to a pointer in getInterface. Instead, each step in the hierarchy checks for a single interface and then forwards the request to the base class.

Does anybody have suggestions how to improve this situation? Either by fixing the above two problems with the ObjectWithIface template, or by suggesting alternatives which would make the Object/Interface framework easier to use.

答:
dynamic_cast exists within the language to solve this exact problem.

Example usage:

```<code>class Interface {
    virtual ~Interface() {}
}; // Must have at least one virtual function
class X : public Interface {};
class Y : public Interface {};

void func(Interface* ptr) {
    if (Y* yptr = dynamic_cast<Y*>(ptr)) {
        // Returns a valid Y* if ptr is a Y, null otherwise
    }
    if (X* xptr = dynamic_cast<X*>(ptr)) {
        // same for X
    }
}
</code>```

dynamic_cast will also seamlessly handle things like multiple and virtual inheritance, which you may well struggle with.

Edit:

You could check COM's QueryInterface for this- they use a similar design with a compiler extension. I've never seen COM code implemented, only used the headers, but you could search for it.

Body:
I'm working with a simple object model in which objects can implement interfaces to provide optional functionality. At it's heart, an object has to implement a getInterface method which is given a (unique) interface ID. The method then returns a pointer to an interface - or null, in case the object doesn't implement the requested interface. Here's a code sketch to illustrate this:

struct Interface { };
struct FooInterface : public Interface { enum { Id = 1 }; virtual void doFoo() = 0; };
struct BarInterface : public Interface { enum { Id = 2 }; virtual void doBar() = 0; };
struct YoyoInterface : public Interface { enum { Id = 3 }; virtual void doYoyo() = 0; };

struct Object {
    virtual Interface *getInterface( int id ) { return 0; }
};

To make things easier for clients who work in this framework, I'm using a little template which automatically generates the 'getInterface' implementation so that clients just have to implement the actual functions required by the interfaces. The idea is to derive a concrete type from Object as well as all the interfaces and then let getInterface just return pointers to this (casted to the right type). Here's the template and a demo usage:

struct NullType { };
template <class T, class U>
struct TypeList {
    typedef T Head;
    typedef U Tail;
};

template <class Base, class IfaceList>
class ObjectWithIface :
    public ObjectWithIface<Base, typename IfaceList::Tail>,
    public IfaceList::Head
{
public:
    virtual Interface *getInterface( int id ) {
        if ( id == IfaceList::Head::Id ) {
            return static_cast<IfaceList::Head *>( this );
        }
        return ObjectWithIface<Base, IfaceList::Tail>::getInterface( id );
    }
};

template <class Base>
class ObjectWithIface<Base, NullType> : public Base
{
public:
    virtual Interface *getInterface( int id ) {
        return Base::getInterface( id );
    }
};

class MyObjectWithFooAndBar : public ObjectWithIface< Object, TypeList<FooInterface, TypeList<BarInterface, NullType> > >
{
public:
    // We get the getInterface() implementation for free from ObjectWithIface
    virtual void doFoo() { }
    virtual void doBar() { }
};

This works quite well, but there are two problems which are ugly:

A blocker for me is that this doesn't work with MSVC6 (which has poor support for templates, but unfortunately I need to support it). MSVC6 yields a C1202 error when compiling this.

A whole range of classes (a linear hierarchy) is generated by the recursive ObjectWithIface template. This is not a problem for me per se, but unfortunately I can't just do a single switch statement to map an interface ID to a pointer in getInterface. Instead, each step in the hierarchy checks for a single interface and then forwards the request to the base class.

Does anybody have suggestions how to improve this situation? Either by fixing the above two problems with the ObjectWithIface template, or by suggesting alternatives which would make the Object/Interface framework easier to use.

Body:
dynamic_cast exists within the language to solve this exact problem.

Example usage:

class Interface {
    virtual ~Interface() {}
}; // Must have at least one virtual function
class X : public Interface {};
class Y : public Interface {};

void func(Interface* ptr) {
    if (Y* yptr = dynamic_cast<Y*>(ptr)) {
        // Returns a valid Y* if ptr is a Y, null otherwise
    }
    if (X* xptr = dynamic_cast<X*>(ptr)) {
        // same for X
    }
}

dynamic_cast will also seamlessly handle things like multiple and virtual inheritance, which you may well struggle with.

Edit:

You could check COM's QueryInterface for this- they use a similar design with a compiler extension. I've never seen COM code implemented, only used the headers, but you could search for it.


来源: stackexchange

问:
HTML input type="number" still returning a string when accessed from javascript
I'm new to javascript , I'm trying learning how functions etc in JS and trying to add 2 numbers

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>JS ADD</title>

Funcitons is JS

  <input type="number" id="num1">
  <input type="number" id="num2">

  <button type="button" onclick="addNumAction()">
    Add
  </button>

```

If I remove the parseInt() the value is treated as a string only , then what is the point of using <input type="number"> ?please explain to me.
what field to use for getting input as a number?

答:
You can use valueAsNumber (described on that page) to get the actual number value. So your code would then be:

```<code>function addNum(n1, n2) {
  return n1 + n2;
}

function addNumAction() {
  var n1 = document.getElementById("num1").valueAsNumber;
  var n2 = document.getElementById("num2").valueAsNumber;

  var sum = addNum(n1, n2);
  window.alert("" + sum);

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm new to javascript , I'm trying learning how functions etc in JS and trying to add 2 numbers

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>JS ADD</title>

Funcitons is JS

  <input type="number" id="num1">
  <input type="number" id="num2">

  <button type="button" onclick="addNumAction()">
    Add
  </button>

If I remove the parseInt() the value is treated as a string only , then what is the point of using <input type="number"> ?please explain to me.
what field to use for getting input as a number?

Body:
You can use valueAsNumber (described on that page) to get the actual number value. So your code would then be:

function addNum(n1, n2) {
  return n1 + n2;
}

function addNumAction() {
  var n1 = document.getElementById("num1").valueAsNumber;
  var n2 = document.getElementById("num2").valueAsNumber;

  var sum = addNum(n1, n2);
  window.alert("" + sum);

}

ContentLicense: CC BY-SA 4.0


问:
Pointer in for loop in c program
I have the following structure:

```<code>struct Matrix
{
    int     numOfRows;
    int     numOfColumns;
    double* values;
    int*    permutationVector;
}
</code>```

Also I have the following function:

```<code>void SetRowToZero(Matrix* m, int row)
{
    int rowBegin = row*(m->numOfColumns);
    for (int c = 0; c < (m->numOfColumns); c++)
    {
        m->values[rowBegin + c] = 0;
    }
}
</code>```

I wonder is there any performance slowdown during operation c < (m->numOfColumns)?
Is there any difference if i write function like this:

```<code>void SetRowToZero(Matrix* m, int row)
{
    // Unpacking structure
    int numOfColumns = m->numOfColumns;
    double* values = m->values;

    int rowBegin = row*(m->numOfColumns);

    for (int c = 0; c < numOfColumns; c++)
    {
        values[rowBegin + c] = 0;
    }
}
</code>```

And in general, should i even care about performace on such a small scale?

答:
There should be no performance issues to speak about: optimizing compilers should be able to turn your first code fragment into a second code fragment, store the pointer in a register, optimize out the index c, or use an addressing mode that computes offset+index in hardware.

Note: If you prefer pointer arithmetic, you could rewrite your loop without using indexes. Performance of this code would be similar to that of your original two blocks of code, but it translates almost directly to a simple block of assembly code with pointers stored in registers:

```<code>void SetRowToZero(Matrix* m, int row) {
    double *rowPtr = m->values + (row*(m->numOfColumns));
    double *pastEndPtr = rowPtr + m->numOfColumns;
    while (rowPtr != pastEndPtr) {
        *rowPtr++ = 0;
    }
}
</code>```

Also note that all three implementations are not thread-safe: if the value of m->numOfColumns or m->values is changed in the middle of the loop by another thread, you would end up with behavior that is very likely to be undefined, and definitely unexpected.

Title: Pointer in for loop in c program

Body:
I have the following structure:

struct Matrix
{
    int     numOfRows;
    int     numOfColumns;
    double* values;
    int*    permutationVector;
}

Also I have the following function:

void SetRowToZero(Matrix* m, int row)
{
    int rowBegin = row*(m->numOfColumns);
    for (int c = 0; c < (m->numOfColumns); c++)
    {
        m->values[rowBegin + c] = 0;
    }
}

I wonder is there any performance slowdown during operation c < (m->numOfColumns)?
Is there any difference if i write function like this:

void SetRowToZero(Matrix* m, int row)
{
    // Unpacking structure
    int numOfColumns = m->numOfColumns;
    double* values = m->values;

    int rowBegin = row*(m->numOfColumns);

    for (int c = 0; c < numOfColumns; c++)
    {
        values[rowBegin + c] = 0;
    }
}

And in general, should i even care about performace on such a small scale?

Body:
There should be no performance issues to speak about: optimizing compilers should be able to turn your first code fragment into a second code fragment, store the pointer in a register, optimize out the index c, or use an addressing mode that computes offset+index in hardware.

Note: If you prefer pointer arithmetic, you could rewrite your loop without using indexes. Performance of this code would be similar to that of your original two blocks of code, but it translates almost directly to a simple block of assembly code with pointers stored in registers:

void SetRowToZero(Matrix* m, int row) {
    double *rowPtr = m->values + (row*(m->numOfColumns));
    double *pastEndPtr = rowPtr + m->numOfColumns;
    while (rowPtr != pastEndPtr) {
        *rowPtr++ = 0;
    }
}

Also note that all three implementations are not thread-safe: if the value of m->numOfColumns or m->values is changed in the middle of the loop by another thread, you would end up with behavior that is very likely to be undefined, and definitely unexpected.


问:
TypeError: hr.employee(26,) is not JSON serializable
I tried to apply domain for many2one field. But I got the following Error:

  @api.mutli
  def open_other_view(self):
      ......
      ......
      ......
      tree_id = self.env.ref('module_name.tree_xml_id').id
      return {
         'type': 'ir.actions.act_window',
         'name': 'title',
         'views': [(tree_id, 'tree'), (False, 'form')],
         'domain' : [('employee_id','=',self.employee_id)],
         ....
         ....
      }```

答:
you could try to obtain the employee id like:

```<code>'domain' : [('employee_id','=',self.employee_id.id)]
</code>```

I hope this help you.

Body:
you could try to obtain the employee id like:

'domain' : [('employee_id','=',self.employee_id.id)]

I hope this help you.


问:
iOS | Simulating/Catching AdMob's adViewDidReceiveAd in UITests
My project has a AdMob Banner Ad which should be globally visible when it gets an ad successfully. A controller has bannerView and a container view which contains an UINavigationController.

BannerView is initially outside the controller. When adViewDidReceiveAd called, bannerView goes up inside the controller view, and container view shrinks.

Here is a simple explanation:

Now, I want to create UITests for this but I don't know how to simulate/catch adViewDidReceiveAd and didFailToReceiveAdWithError delegate methods.

Thank you.

答:
Hmm. I don't know of a way to do this without network traffic that doesn't involve creating your own protocols and objects that wrap the GADAdView and its delegate (MockableAdView, maybe), so you can make a second mocked implementation that just fires off the events the way you like.

If you don't mind involving network requests, you can request banners using our test ad unit ID (see the test ads guide) when you want them to pass, and a fake, garbage ad unit ID when you want them to fail and send didFailToReceiveAdWithError. The test ad unit ID should perform reliably enough to avoid making your test flaky.


问:
Javascript - move/drag icons to table
I am trying to like 10x10 table where I can drag images to each another.

Does anybody have an idea how this can be accomplished using JavaScript? I have already tried something with Dragula but it didn't work well.

This is what I want to work in real time:

答:
You can add the

```<code>draggable="true"
</code>```

attribute to the html elements.
If that doesn't help then try checking out W3Schools.
You can also check out Mozilla
Hope this helps.

Title: Javascript - move/drag icons to table

Body:
You can add the

draggable="true"

attribute to the html elements.
If that doesn't help then try checking out W3Schools.
You can also check out Mozilla
Hope this helps.


问:
How to simplify an account code?
I am making an account code in python and it works but it is really long and I want to know if there is a way to shorten it. Here is my code:

```<code>user1 = "Jeff"
user2 = "Bob"

password1 = "Password"
password2 = "Lol"

username = input("Login: >> ")
password = input("Password: >> ")

if username == user1:
    if password == password1:
        print ("Access granted")
        print ("Welcome to the system!")
        home()

    else:
        print ("Access denied")
        print ("Try again!")
        print ("\n")
        time.sleep(2)
        login()

elif username == user2:
    if password == password2:
        print ("Access granted")
        print ("Welcome to the system!")
        home()
    else:
        print ("Access denied")
        print ("Try again!")
        print ("\n")
        time.sleep(2)
        login()

else:
    print ("Access denied")
    print ("Try again!")
    print ("\n")
    time.sleep(2)
    login()
</code>```

The more accounts I create the longer longer it will get. Is there a way to shorten or simplify this?

答:
I'd separate the user and password checks:</p>

```<code>users = {
    "Jeff": "Password",
    "Bob": "Lol"}

def login(user=None):

    # User
    if not user:
        user = input("Login: >> ").title()
        if not users.get(user):
            print ("No such user")
            return None

    # Password
    password = input("Password: >> ")
    if password == users[user]:
        print ("Access granted")
        print ("Welcome to the system!")
        return user
    else:
        print("Access denied")
        print("Try again!")
        return login(user=user)

while True:
    logged_in_user = login()
    if logged_in_user:
        print("Welcome {}".format(logged_in_user))
        break
</code>```

Title: How to simplify an account code?

Body:
I am making an account code in python and it works but it is really long and I want to know if there is a way to shorten it. Here is my code:

user1 = "Jeff"
user2 = "Bob"

password1 = "Password"
password2 = "Lol"

username = input("Login: >> ")
password = input("Password: >> ")

if username == user1:
    if password == password1:
        print ("Access granted")
        print ("Welcome to the system!")
        home()

    else:
        print ("Access denied")
        print ("Try again!")
        print ("\n")
        time.sleep(2)
        login()

elif username == user2:
    if password == password2:
        print ("Access granted")
        print ("Welcome to the system!")
        home()
    else:
        print ("Access denied")
        print ("Try again!")
        print ("\n")
        time.sleep(2)
        login()

else:
    print ("Access denied")
    print ("Try again!")
    print ("\n")
    time.sleep(2)
    login()

The more accounts I create the longer longer it will get. Is there a way to shorten or simplify this?

Body:
I'd separate the user and password checks:

users = {
    "Jeff": "Password",
    "Bob": "Lol"}

def login(user=None):

    # User
    if not user:
        user = input("Login: >> ").title()
        if not users.get(user):
            print ("No such user")
            return None

    # Password
    password = input("Password: >> ")
    if password == users[user]:
        print ("Access granted")
        print ("Welcome to the system!")
        return user
    else:
        print("Access denied")
        print("Try again!")
        return login(user=user)

while True:
    logged_in_user = login()
    if logged_in_user:
        print("Welcome {}".format(logged_in_user))
        break


问:
Oracle SQL - Eliminate values that are not equal on a join
Here's how my tables look: Both tables have a composite primary key on all 3 columns. And the SecondaryId will not repeat from these two tables. This is obviously not enforced by a DB constraint but by business rules on the front-end.

```<code>Table1:
PrimaryID|SecondaryID|Email
1   9999    ABC@GMAIL.COM
1   9999    DEF@GMAIL.COM
2   8888    CCC@GMAIL.COM
3   7777    CBA@GMAIL.COM

Table2:
PrimaryID|SecondaryID|Email
1   1111    ABC@GMAIL.COM
2   2222    XYZ@GMAIL.COM
3   3333    CBA@GMAIL.COM
</code>```

I want the secondaryid in both tables returned, joining on the same primaryid where the emails are different on all occurrences of the primary id.

For PrimaryID = 1:
Table1 has two rows, table 2 has one row. But that one email from table2 matches with the one on table1 so I don't want that back. Here's my query but that doesn't eliminate the above duplicate which is what I need.

```<code> SELECT DISTINCT T1.SECONDARYID, T2.SECONDARYID
    FROM TABLE1 T1 INNER JOIN TABLE2 T2 ON T1.PRIMARYID = T2.PRIMARYID
    AND T1.EMAIL <> T2.EMAIL;
</code>```

Returns

```<code>9999    1111
8888    2222
</code>```

答:
You need to identify the id's for which there is at least one email in common in the two tables. One way to do that is to join on primaryid and email in a subquery. The solution below may not be the most efficient, but it will do the job.</p>

```<code>select t1.primaryid,
       t1.secondaryid as secondaryid_in_t1,
       t2.secondaryid as secondaryid_in_t2
from   table1 t1 join table2 t2
                 on t1.primaryid = t2.primaryid
where  t1.primaryid not in (
         select a.primaryid
         from   table1 a join table2 b
                          on a.primaryid = b.primaryid and a.email = b.email
       )
;
</code>```

Body:
Here's how my tables look: Both tables have a composite primary key on all 3 columns. And the SecondaryId will not repeat from these two tables. This is obviously not enforced by a DB constraint but by business rules on the front-end.

Table1:
PrimaryID|SecondaryID|Email
1   9999    ABC@GMAIL.COM
1   9999    DEF@GMAIL.COM
2   8888    CCC@GMAIL.COM
3   7777    CBA@GMAIL.COM

Table2:
PrimaryID|SecondaryID|Email
1   1111    ABC@GMAIL.COM
2   2222    XYZ@GMAIL.COM
3   3333    CBA@GMAIL.COM

I want the secondaryid in both tables returned, joining on the same primaryid where the emails are different on all occurrences of the primary id.

For PrimaryID = 1:
Table1 has two rows, table 2 has one row. But that one email from table2 matches with the one on table1 so I don't want that back. Here's my query but that doesn't eliminate the above duplicate which is what I need.

 SELECT DISTINCT T1.SECONDARYID, T2.SECONDARYID
    FROM TABLE1 T1 INNER JOIN TABLE2 T2 ON T1.PRIMARYID = T2.PRIMARYID
    AND T1.EMAIL <> T2.EMAIL;

Returns

9999    1111
8888    2222

Body:
You need to identify the id's for which there is at least one email in common in the two tables. One way to do that is to join on primaryid and email in a subquery. The solution below may not be the most efficient, but it will do the job.

select t1.primaryid,
       t1.secondaryid as secondaryid_in_t1,
       t2.secondaryid as secondaryid_in_t2
from   table1 t1 join table2 t2
                 on t1.primaryid = t2.primaryid
where  t1.primaryid not in (
         select a.primaryid
         from   table1 a join table2 b
                          on a.primaryid = b.primaryid and a.email = b.email
       )
;


问:
Match and extract zipcode in javascript
I have a string like  HONOLULU HI 96814-2317 USA and sometimes HONOLULU HI 96814 USA . I want to extract only the zipcode i.e., 96814-2317 and 96814 from the string in javascript . How can i achieve this ?</p>

答:
Here is the Running code.</p>

```<code><html>
<body onload="myFunction()">

<script>
function myFunction() {
var str1 = 'HONOLULU HI 96814 USA';
var str2= 'HONOLULU HI 96814-2317 USA';
var pattern=/\d{5}(?:[-\s]\d{4})?/;
var result1 = pattern.exec(str1);
var result2 = pattern.exec(str2);
document.getElementById("result1").innerHTML = result1;
document.getElementById("result2").innerHTML = result2;
}
</script>
<p id="result1"></p>
<p id="result2"></p>
</html>
</code>```

Title: Match and extract zipcode in javascript

Body:
Here is the Running code.

<html>
<body onload="myFunction()">

<script>
function myFunction() {
var str1 = 'HONOLULU HI 96814 USA';
var str2= 'HONOLULU HI 96814-2317 USA';
var pattern=/\d{5}(?:[-\s]\d{4})?/;
var result1 = pattern.exec(str1);
var result2 = pattern.exec(str2);
document.getElementById("result1").innerHTML = result1;
document.getElementById("result2").innerHTML = result2;
}
</script>
<p id="result1"></p>
<p id="result2"></p>
</html>


问:
Javascript function to convert color names to hex codes
Is there a built-in function that would convert a color by name into its hex representation?
Like I want to pass 'white' and receive '#FFFFFF'. I really want to avoid coding all hundred if's myself :)</p>

答:
@dlauzon suggested I convert my comment into an answer. Thanks for suggesting! Here it is :)

```<code>function standardize_color(str){
    var ctx = document.createElement('canvas').getContext('2d');
    ctx.fillStyle = str;
    return ctx.fillStyle;
}
</code>```

function standardize_color(str){
    var ctx = document.createElement("canvas").getContext("2d");
    ctx.fillStyle = str;
    return ctx.fillStyle;
}

document.getElementById("myspan1").innerHTML = standardize_color("red");
document.getElementById("myspan2").innerHTML = standardize_color("PeachPuff");
document.getElementById("myspan3").innerHTML = standardize_color("PaleGoldenRod");
document.getElementById("myspan4").innerHTML = standardize_color("RGB(123,234,142)");
document.getElementById("myspan5").innerHTML = standardize_color("HSL(284,6%,49%)");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>span { font-weight:800; }</code>```

The color named "Red" has a code of: (requires js).

 ...and color "PeachPuff"'s code is: (requires js).

 ...and "PaleGoldenRod" is: (requires js).

It works with "RGB(123,234,142)" too: (needs js)
and therefore with: "HSL(284,6%,49%)", which is: (requires js)
.  Handy!```

Body:
@dlauzon suggested I convert my comment into an answer. Thanks for suggesting! Here it is :)

function standardize_color(str){
    var ctx = document.createElement('canvas').getContext('2d');
    ctx.fillStyle = str;
    return ctx.fillStyle;
}

function standardize_color(str){
    var ctx = document.createElement("canvas").getContext("2d");
    ctx.fillStyle = str;
    return ctx.fillStyle;
}

document.getElementById("myspan1").innerHTML = standardize_color("red");
document.getElementById("myspan2").innerHTML = standardize_color("PeachPuff");
document.getElementById("myspan3").innerHTML = standardize_color("PaleGoldenRod");
document.getElementById("myspan4").innerHTML = standardize_color("RGB(123,234,142)");
document.getElementById("myspan5").innerHTML = standardize_color("HSL(284,6%,49%)");

span { font-weight:800; }

The color named "Red" has a code of: <span id="myspan1">(requires js)</span>.<br>
 ...and color "PeachPuff"'s code is: <span id="myspan2">(requires js)</span>.<br>
 ...and "PaleGoldenRod" is: <span id="myspan3">(requires js)</span>.<br><br>

It works with "RGB(123,234,142)" too: <span id="myspan4">(needs js)</span>
and therefore with: "HSL(284,6%,49%)", which is: <span id="myspan5">(requires js)
</span>.  Handy!


问:
Spark Dataframe GroupBy & complex case statement derivation
I need to implement the following scenarios on dataframes using Spark Scala :

```<code>Scenarios-1: If the "KEY" exist one time, take the "TYPE_VAL" as is .
             Eg: KEY=66 exist once so take the TYPE_VAL=100
Scenarios-2: If the "KEY" exist more than one time, Check for the same TYPE_VAL, if it is same, then take TYPE_VAL once .
             Eg: for KEY=68,so TYPE_VAL=23
Scenarios-3: If the "KEY" exist more than one time, Check for the same TYPE_VAL and subtract the other TYPE_VAL.
             Eg: for KEY=67 , TYPE_VAL=10 exists twice,so subtract 2 & 4 from 10, finally TYPE_VAL=4
</code>```

I have tried using group by for the same key, but unable to derive all the scenarios

```<code>   //Sample Input Values
    val values = List(List("66","100") ,
    List("67","10") , List("67","10"),List("67","2"),List("67","4")
    List("68","23"),List("68","23")).map(x =>(x(0), x(1)))

    import spark.implicits._
    //created a dataframe
    val df1 = values.toDF("KEY","TYPE_VAL")

    df1.show(false)
    ------------------------
    KEY |TYPE_VAL  |
    ------------------------
    66  |100       |
    67  |10        |
    67  |10        |
    67  |2         |
    67  |4         |
    68  |23        |
    68  |23        |
    -------------------------
</code>```

Expected Output :

```<code>df2.show(false)
    ------------------------
    KEY |TYPE_VAL  |
    ------------------------
    66  |100       | -------> [single row ,so 100]
    67  |4         | -------> [four rows,out of which two are same & rest are diffrent, so (10 - 2 - 4) = 4 ]
    68  |23        | -------> [two rows with same values, so 23]
    -------------------------
</code>```

答:
If you can assume the number of records per key cannot be too large (i.e. up to ~thousands?), you can use collect_list after grouping to get all matches into an array, and then use a UDF to compute your result based on that array:

```<code>import org.apache.spark.sql.functions._
import spark.implicits._

// create the sample data:
val df1 = List(
  (66, 100),
  (67, 10),
  (67, 10),
  (67, 2),
  (67, 4),
  (68, 23),
  (68, 23)
).toDF("KEY", "TYPE_VAL")

// define a UDF that computes the result per scenario for a given Seq[Int].
// This is just one possible implementation, simpler ones probably exist...
val computeTypeVal = udf { (vals: Seq[Int]) =>
  vals.groupBy(identity).values.toList.sortBy(-_.size).flatten match {
    case a :: Nil => a
    case a :: b :: tail if a == b => a - tail.filterNot(_ == a).sum
    case _ => 0 // or whatever else should be done for other cases
  }
}

// group by key, use functions.collect_list to collect all value per key and apply UDF
df1.groupBy($"KEY")
  .agg(collect_list($"TYPE_VAL") as "VALS")
  .select($"KEY", computeTypeVal($"VALS") as "TYPE_VAL")
  .sort($"KEY")
  .show()
</code>```

Body:
I need to implement the following scenarios on dataframes using Spark Scala :

Scenarios-1: If the "KEY" exist one time, take the "TYPE_VAL" as is .
             Eg: KEY=66 exist once so take the TYPE_VAL=100
Scenarios-2: If the "KEY" exist more than one time, Check for the same TYPE_VAL, if it is same, then take TYPE_VAL once .
             Eg: for KEY=68,so TYPE_VAL=23
Scenarios-3: If the "KEY" exist more than one time, Check for the same TYPE_VAL and subtract the other TYPE_VAL.
             Eg: for KEY=67 , TYPE_VAL=10 exists twice,so subtract 2 & 4 from 10, finally TYPE_VAL=4

I have tried using group by for the same key, but unable to derive all the scenarios

   //Sample Input Values
    val values = List(List("66","100") ,
    List("67","10") , List("67","10"),List("67","2"),List("67","4")
    List("68","23"),List("68","23")).map(x =>(x(0), x(1)))

    import spark.implicits._
    //created a dataframe
    val df1 = values.toDF("KEY","TYPE_VAL")

    df1.show(false)
    ------------------------
    KEY |TYPE_VAL  |
    ------------------------
    66  |100       |
    67  |10        |
    67  |10        |
    67  |2         |
    67  |4         |
    68  |23        |
    68  |23        |
    -------------------------

Expected Output :

df2.show(false)
    ------------------------
    KEY |TYPE_VAL  |
    ------------------------
    66  |100       | -------> [single row ,so 100]
    67  |4         | -------> [four rows,out of which two are same & rest are diffrent, so (10 - 2 - 4) = 4 ]
    68  |23        | -------> [two rows with same values, so 23]
    -------------------------

Body:
If you can assume the number of records per key cannot be too large (i.e. up to ~thousands?), you can use collect_list after grouping to get all matches into an array, and then use a UDF to compute your result based on that array:

import org.apache.spark.sql.functions._
import spark.implicits._

// create the sample data:
val df1 = List(
  (66, 100),
  (67, 10),
  (67, 10),
  (67, 2),
  (67, 4),
  (68, 23),
  (68, 23)
).toDF("KEY", "TYPE_VAL")

// define a UDF that computes the result per scenario for a given Seq[Int].
// This is just one possible implementation, simpler ones probably exist...
val computeTypeVal = udf { (vals: Seq[Int]) =>
  vals.groupBy(identity).values.toList.sortBy(-_.size).flatten match {
    case a :: Nil => a
    case a :: b :: tail if a == b => a - tail.filterNot(_ == a).sum
    case _ => 0 // or whatever else should be done for other cases
  }
}

// group by key, use functions.collect_list to collect all value per key and apply UDF
df1.groupBy($"KEY")
  .agg(collect_list($"TYPE_VAL") as "VALS")
  .select($"KEY", computeTypeVal($"VALS") as "TYPE_VAL")
  .sort($"KEY")
  .show()


问:
How to cancel a scroll event after N pixels have been scrolled
inputs :

1 scroll down event scrolls 100 pixels.

An HTML element is 5 pixels below the bottom of the page. It is not on screen.

A Javascript function detects when at least 1 pixel of the HTML element is on screen, and :

automatically scrolls the page so that the element is fully on screen.

prevent other scroll events during the animation

events :

the user does 1 scroll-down event (refered below as "the scroll event").

expected result :

After 6 pixels scrolled - when 1px of the element is visible - the scroll event is CANCELLED and the javascript function initiates the automatic scroll.

actual result :

The other scroll events are correctly prevented, but it looks like the first scroll event and the automatic scroll are in conflict as long as the scroll event hasn't finished its 100px scroll (it looks choppy).

I did try to do "overflow:hidden" on the "body" during the animation, but this does not cancel the scroll event, which still continues to scroll the page after the animation of the automatic scroll is completed (specifically using a laptop trackpad).

Any ideas ? Thx !

P.S.: I would appreciate native javascript answers please.

答:
You could use window.pageYOffset

Here is an example: The code within the if statement only runs within the first 100px from top of the page

```<code>window.addEventListener("scroll", function(){
    if(window.pageYOffset < 100) {
        console.log("hi there");
    }
});
</code>```

Body:
You could use window.pageYOffset

Here is an example: The code within the if statement only runs within the first 100px from top of the page

window.addEventListener("scroll", function(){
    if(window.pageYOffset < 100) {
        console.log("hi there");
    }
});


问:
Dynamic SQL Procedure with Pivot displaying counts based on Date Range

I have a table which contains multiple user entries.
I want to pull counts of user entries based on date range passed to a stored procedure.

start date: 11/9/2017
end date: 11/11/2017

However the response needs to be dynamic based on amount of days in the date range.

Here is a desired format:

答:
Now that you have provided examples, I have updated my answer which provides you with a solution based on the data you have provided.

Note that you are able to change the date range and the query will update accordingly.

Bare in mind that this SQL query is for SQL Server:

```<code>create table #tbl1 (
    [UserId] int
    ,[UserName] nvarchar(max)
    ,[EntryDateTime] datetime
);

insert into #tbl1 ([UserId],[UserName],[EntryDateTime])
values
    (1,'John Doe','20171109')
    ,(1,'John Doe','20171109')
    ,(1,'John Doe','20171110')
    ,(1,'John Doe','20171111')
    ,(2,'Mike Smith','20171109')
    ,(2,'Mike Smith','20171110')
    ,(2,'Mike Smith','20171110')
    ,(2,'Mike Smith','20171110')
;

-- declare variables
declare
    @p1 date
    ,@p2 date
    ,@diff int
    ,@counter1 int
    ,@counter2 int
    ,@dynamicSQL nvarchar(max)
;

-- set variables
set @p1 = '20171109';   -- ENTER THE START DATE IN THE FORMAT YYYYMMDD
set @p2 = '20171111';   -- ENTER THE END DATE IN THE FORMAT YYYYMMDD
set @diff = datediff(dd,@p1,@p2); -- used to calculate the difference in days
set @counter1 = 0;  -- first counter to be used in while loop
set @counter2 = 0;  -- second counter to be used in while loop
set @dynamicSQL = 'select pivotTable.[UserId] ,pivotTable.[UserName] as [Name] '; -- start of the dynamic SQL statement

-- to get the dates into the query in a dynamic way, you need to do a while loop (or use a cursor)
while (@counter1 < @diff)
begin
    set @dynamicSQL += ',pivotTable.[' + convert(nvarchar(10),dateadd(dd,@counter1,@p1),120) + '] '

    set @counter1 = (@counter1 +1)
end

-- continuation of the dynamic SQL statement
set @dynamicSQL += ' from (
    select
        t.[UserId]
        ,t.[UserName]
        ,cast(t.[EntryDateTime] as date) as [EntryDate]
        ,count(t.[UserId]) as [UserCount]
    from #tbl1 as t
    where
        t.[EntryDateTime] >= ''' + convert(nvarchar(10),@p1,120) + ''' ' +
        ' and t.[EntryDateTime] <= ''' + convert(nvarchar(10),@p2,120) + ''' ' +
    'group by
        t.[UserId]
        ,t.[UserName]
        ,t.[EntryDateTime]
    ) as mainQuery

    pivot (
        sum(mainQuery.[UserCount]) for mainQuery.[EntryDate]
            in ('
;

-- the second while loop which is used to create the columns in the pivot table
while (@counter2 < @diff)
begin
    set @dynamicSQL += ',[' + convert(nvarchar(10),dateadd(dd,@counter2,@p1),120) + ']'

    set @counter2 = (@counter2 +1)
end

-- continuation of the SQL statement
set @dynamicSQL += ')
    ) as pivotTable'
;

-- this is the easiet way I could think of to get rid of the leading comma in the query
set @dynamicSQL = replace(@dynamicSQL,'in (,','in (');

print @dynamicSQL   -- included this so that you can see the SQL statement that is generated

exec sp_executesql @dynamicSQL; -- this will run the generate dynamic SQL statement

drop table #tbl1;
</code>```

Let me know if that's what you were looking for.

Body:
Now that you have provided examples, I have updated my answer which provides you with a solution based on the data you have provided.

Note that you are able to change the date range and the query will update accordingly.

Bare in mind that this SQL query is for SQL Server:

create table #tbl1 (
    [UserId] int
    ,[UserName] nvarchar(max)
    ,[EntryDateTime] datetime
);

insert into #tbl1 ([UserId],[UserName],[EntryDateTime])
values
    (1,'John Doe','20171109')
    ,(1,'John Doe','20171109')
    ,(1,'John Doe','20171110')
    ,(1,'John Doe','20171111')
    ,(2,'Mike Smith','20171109')
    ,(2,'Mike Smith','20171110')
    ,(2,'Mike Smith','20171110')
    ,(2,'Mike Smith','20171110')
;

-- declare variables
declare
    @p1 date
    ,@p2 date
    ,@diff int
    ,@counter1 int
    ,@counter2 int
    ,@dynamicSQL nvarchar(max)
;

-- set variables
set @p1 = '20171109';   -- ENTER THE START DATE IN THE FORMAT YYYYMMDD
set @p2 = '20171111';   -- ENTER THE END DATE IN THE FORMAT YYYYMMDD
set @diff = datediff(dd,@p1,@p2); -- used to calculate the difference in days
set @counter1 = 0;  -- first counter to be used in while loop
set @counter2 = 0;  -- second counter to be used in while loop
set @dynamicSQL = 'select pivotTable.[UserId] ,pivotTable.[UserName] as [Name] '; -- start of the dynamic SQL statement

-- to get the dates into the query in a dynamic way, you need to do a while loop (or use a cursor)
while (@counter1 < @diff)
begin
    set @dynamicSQL += ',pivotTable.[' + convert(nvarchar(10),dateadd(dd,@counter1,@p1),120) + '] '

    set @counter1 = (@counter1 +1)
end

-- continuation of the dynamic SQL statement
set @dynamicSQL += ' from (
    select
        t.[UserId]
        ,t.[UserName]
        ,cast(t.[EntryDateTime] as date) as [EntryDate]
        ,count(t.[UserId]) as [UserCount]
    from #tbl1 as t
    where
        t.[EntryDateTime] >= ''' + convert(nvarchar(10),@p1,120) + ''' ' +
        ' and t.[EntryDateTime] <= ''' + convert(nvarchar(10),@p2,120) + ''' ' +
    'group by
        t.[UserId]
        ,t.[UserName]
        ,t.[EntryDateTime]
    ) as mainQuery

    pivot (
        sum(mainQuery.[UserCount]) for mainQuery.[EntryDate]
            in ('
;

-- the second while loop which is used to create the columns in the pivot table
while (@counter2 < @diff)
begin
    set @dynamicSQL += ',[' + convert(nvarchar(10),dateadd(dd,@counter2,@p1),120) + ']'

    set @counter2 = (@counter2 +1)
end

-- continuation of the SQL statement
set @dynamicSQL += ')
    ) as pivotTable'
;

-- this is the easiet way I could think of to get rid of the leading comma in the query
set @dynamicSQL = replace(@dynamicSQL,'in (,','in (');

print @dynamicSQL   -- included this so that you can see the SQL statement that is generated

exec sp_executesql @dynamicSQL; -- this will run the generate dynamic SQL statement

drop table #tbl1;

Let me know if that's what you were looking for.


问:
Drawing Truth Tables? A && (B || D)
I'm having trouble starting this truth table and drawing it out in my AP Computer Science class. A && (B || D) is what I have to draw.</p>

Title: Drawing Truth Tables? A && (B || D)

Body:
Display all posibilities in first, and it will be easy ;)

+-----------+-----+
| A | B | C | Out |
|---|---|---|-----|
| 0 | 0 | 0 |  0  |
| 0 | 0 | 1 |  0  |
| 0 | 1 | 0 |  ?  |
| 0 | 1 | 1 |  ?  |
....
....
| 1 | 1 | 1 |  1  |
+-----------+-----+

I did the begin and the last for you ;)


问:
Launch Dataflow template from Google App Engine
I want to launch a dataflow template using Google App Engine. I've written the code but I get a runtime error 'NoClassDefFoundError'.

My App Engine Code:-

```<code>     doGet(HttpServletRequest request, HttpServletResponse response){

        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
            JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
            Dataflow dataflowService = new Dataflow.Builder(httpTransport, jsonFactory, credential).build();
            System.out.println(dataflowService.getApplicationName());

com.google.api.services.dataflow.Dataflow.Projects.Locations.Templates.Launch request1 = dataflowService.projects().locations()
                        .templates().launch(projectId,"us-central1",null);

                request1.setGcsPath("gs://bucket/MyTemplate");
                request1.setLocation("us-central1");
                request1.setValidateOnly(false);

                LaunchTemplateResponse response1 = request1.execute();
</code>```

The error that I'm getting:-

```<code>2017-10-27 17:16:14.177:WARN:oejs.ServletHandler:qtp1811044090-14: Error for /hello
java.lang.NoClassDefFoundError: com/google/api/services/dataflow/Dataflow$Builder
    at com.testing.HelloAppEngine.doGet(HelloAppEngine.java:53)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:848)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1772)
    at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:134)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
    at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
    at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
    at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:48)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
    at com.google.appengine.tools.development.jetty9.StaticFileFilter.doFilter(StaticFileFilter.java:123)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectRequest(DevAppServerModulesFilter.java:366)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectModuleRequest(DevAppServerModulesFilter.java:349)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doFilter(DevAppServerModulesFilter.java:116)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1751)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:582)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:524)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1180)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:512)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112)
    at com.google.appengine.tools.development.jetty9.DevAppEngineWebAppContext.doScope(DevAppEngineWebAppContext.java:94)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
    at com.google.appengine.tools.development.jetty9.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:597)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
    at org.eclipse.jetty.server.Server.handle(Server.java:534)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)
    at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:283)
    at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:108)
    at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
    at java.lang.Thread.run(Unknown Source)
Caused by:
java.lang.ClassNotFoundException: com.google.api.services.dataflow.Dataflow$Builder
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at com.google.appengine.tools.development.IsolatedAppClassLoader.loadClass(IsolatedAppClassLoader.java:196)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at com.testing.HelloAppEngine.doGet(HelloAppEngine.java:53)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:848)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1772)
    at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:134)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
    at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
    at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
    at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:48)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
    at com.google.appengine.tools.development.jetty9.StaticFileFilter.doFilter(StaticFileFilter.java:123)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectRequest(DevAppServerModulesFilter.java:366)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectModuleRequest(DevAppServerModulesFilter.java:349)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doFilter(DevAppServerModulesFilter.java:116)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1751)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:582)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:524)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1180)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:512)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112)
    at com.google.appengine.tools.development.jetty9.DevAppEngineWebAppContext.doScope(DevAppEngineWebAppContext.java:94)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
    at com.google.appengine.tools.development.jetty9.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:597)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
    at org.eclipse.jetty.server.Server.handle(Server.java:534)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)
    at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:283)
    at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:108)
    at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
    at java.lang.Thread.run(Unknown Source)
2017-10-27 17:16:35.782:INFO:oejs.AbstractConnector:pool-1-thread-1: Stopped NetworkTrafficSelectChannelConnector@741a8937{HTTP/1.1,[http/1.1]}{localhost:8080}
2017-10-27 17:16:35.786:INFO:oejsh.ContextHandler:pool-1-thread-1: Stopped c.g.a.t.d.j.DevAppEngineWebAppContext@6283d8b8{/,file:///C:/Users/kishank/KishanTester/.metadata/.plugins/org.eclipse.wst.server.core/tmp4/FinalTesting/,UNAVAILABLE}{C:\Users\kishank\KishanTester\.metadata\.plugins\org.eclipse.wst.server.core\tmp4\FinalTesting}
Oct 27, 2017 5:16:35 PM com.google.appengine.tools.development.AbstractModule shutdown
Shutting down.
INFO: Shutting down module instance default
</code>```

The same code to launch the template works fine within Dataflow. Am I missing anything here? Does anything need to done differently within App Engine?

Thanks.

答:
The Problem OCcured Due To Dependency in Dataflow API So I Updated To latest Version and Problem Resolved
Dataflow API Latest Version Must Be Used </p>

Body:
I want to launch a dataflow template using Google App Engine. I've written the code but I get a runtime error 'NoClassDefFoundError'.

My App Engine Code:-

     doGet(HttpServletRequest request, HttpServletResponse response){

        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
            JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
            Dataflow dataflowService = new Dataflow.Builder(httpTransport, jsonFactory, credential).build();
            System.out.println(dataflowService.getApplicationName());

com.google.api.services.dataflow.Dataflow.Projects.Locations.Templates.Launch request1 = dataflowService.projects().locations()
                        .templates().launch(projectId,"us-central1",null);

                request1.setGcsPath("gs://bucket/MyTemplate");
                request1.setLocation("us-central1");
                request1.setValidateOnly(false);

                LaunchTemplateResponse response1 = request1.execute();

The error that I'm getting:-

2017-10-27 17:16:14.177:WARN:oejs.ServletHandler:qtp1811044090-14: Error for /hello
java.lang.NoClassDefFoundError: com/google/api/services/dataflow/Dataflow$Builder
    at com.testing.HelloAppEngine.doGet(HelloAppEngine.java:53)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:848)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1772)
    at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:134)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
    at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
    at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
    at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:48)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
    at com.google.appengine.tools.development.jetty9.StaticFileFilter.doFilter(StaticFileFilter.java:123)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectRequest(DevAppServerModulesFilter.java:366)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectModuleRequest(DevAppServerModulesFilter.java:349)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doFilter(DevAppServerModulesFilter.java:116)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1751)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:582)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:524)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1180)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:512)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112)
    at com.google.appengine.tools.development.jetty9.DevAppEngineWebAppContext.doScope(DevAppEngineWebAppContext.java:94)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
    at com.google.appengine.tools.development.jetty9.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:597)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
    at org.eclipse.jetty.server.Server.handle(Server.java:534)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)
    at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:283)
    at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:108)
    at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
    at java.lang.Thread.run(Unknown Source)
Caused by:
java.lang.ClassNotFoundException: com.google.api.services.dataflow.Dataflow$Builder
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at com.google.appengine.tools.development.IsolatedAppClassLoader.loadClass(IsolatedAppClassLoader.java:196)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at com.testing.HelloAppEngine.doGet(HelloAppEngine.java:53)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:848)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1772)
    at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:134)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
    at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
    at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
    at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:48)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
    at com.google.appengine.tools.development.jetty9.StaticFileFilter.doFilter(StaticFileFilter.java:123)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectRequest(DevAppServerModulesFilter.java:366)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectModuleRequest(DevAppServerModulesFilter.java:349)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doFilter(DevAppServerModulesFilter.java:116)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1751)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:582)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:524)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1180)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:512)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112)
    at com.google.appengine.tools.development.jetty9.DevAppEngineWebAppContext.doScope(DevAppEngineWebAppContext.java:94)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
    at com.google.appengine.tools.development.jetty9.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:597)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
    at org.eclipse.jetty.server.Server.handle(Server.java:534)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)
    at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:283)
    at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:108)
    at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
    at java.lang.Thread.run(Unknown Source)
2017-10-27 17:16:35.782:INFO:oejs.AbstractConnector:pool-1-thread-1: Stopped NetworkTrafficSelectChannelConnector@741a8937{HTTP/1.1,[http/1.1]}{localhost:8080}
2017-10-27 17:16:35.786:INFO:oejsh.ContextHandler:pool-1-thread-1: Stopped c.g.a.t.d.j.DevAppEngineWebAppContext@6283d8b8{/,file:///C:/Users/kishank/KishanTester/.metadata/.plugins/org.eclipse.wst.server.core/tmp4/FinalTesting/,UNAVAILABLE}{C:\Users\kishank\KishanTester\.metadata\.plugins\org.eclipse.wst.server.core\tmp4\FinalTesting}
Oct 27, 2017 5:16:35 PM com.google.appengine.tools.development.AbstractModule shutdown
Shutting down.
INFO: Shutting down module instance default

The same code to launch the template works fine within Dataflow. Am I missing anything here? Does anything need to done differently within App Engine?

Thanks.


答:
Have a column for each individual value (A, B, D) and a row for every combination of values 2^3 = 8. Then, have additional columns for each intermediate calculation. In the end have another column for the complete expression. Now you can do the calculations step by step.

You should end up with the following template:

```<code> A | B | D | (B || D) | A && (B || D)
---+---+---+----------+--------------
 F | F | F |          |
 F | F | T |          |
 F | T | F |          |
 F | T | T |          |
 T | F | F |          |
 T | F | T |          |
 T | T | F |          |
 T | T | T |          |
</code>```

From here on, you should be able to solve your task.

Title: Drawing Truth Tables? A && (B || D)

Body: I'm having trouble starting this truth table and drawing it out in my AP Computer Science class. A && (B || D) is what I have to draw.

Body:
Have a column for each individual value (A, B, D) and a row for every combination of values 2^3 = 8. Then, have additional columns for each intermediate calculation. In the end have another column for the complete expression. Now you can do the calculations step by step.

You should end up with the following template:

 A | B | D | (B || D) | A && (B || D)
---+---+---+----------+--------------
 F | F | F |          |
 F | F | T |          |
 F | T | F |          |
 F | T | T |          |
 T | F | F |          |
 T | F | T |          |
 T | T | F |          |
 T | T | T |          |

From here on, you should be able to solve your task.


问:
Difference LP/MIP and CP
what is the difference between Constraint Programming (CP) and Linear Programming (LP) or Mixed Integer Programming (MIP) ? I know what LP and MIP is but dont understand the difference to CP - or is CP just the same as MIP and LP ? I am a but confused on this ...</p>

答:
This may be a little exhaustive, but I will try to provide all the information to cover a good scope of this topic.
I'll start with an example and the corresponding information will make more sense.

**Example**: Say we need to sequence a set of tasks on a machine. Each task i has a specific fixed processing time pi. Each task can be started after its release date ri , and must be completed before its deadline di. Tasks cannot overlap in time. Time is represented as a discrete set of time points, say {1, 2,…, H} (H stands for horizon)

MIP Model:

Variables: Binary variable xij represents whether task i starts at time period j

Constraints:

Each task starts on exactly one time point

* ∑j xij = 1 for all tasks i

Respect release date and deadline

j*xij = 0 for all tasks i and (j < ri ) or (j > di - pi )

Tasks cannot overlap

Variant 1:
∑i xij ≤ 1 for all time points j we also need to take processing times into account; this becomes messy

Variant 2:
introduce binary variable bi representing whether task i comes before task k must be linked to xij; this becomes messy
MIP models thus consists of linear/quadratic optimization functions, linear/ quadratic optimization constraints and binary/integer variables.

CP model:

Variables:

Let starti represent the starting time of task i takes a value from domain {1,2,…, H} - this immediately ensures that each task starts at exactly one time point

Constraints:

Respect release date and deadline

ri ≤ starti ≤ di - pi

Tasks cannot overlap:
for all tasks i and j (starti + pi < startj) OR (starti + pi < starti)

and that is it!

You could probably say that the structure of the CP models and MIP models are the same: using decision variables, objective function and a set of constraints. Both MIP and CP problems are non-convex  and make use of some systematic and exhaustive search algorithms.

However, we see the major difference in modeling capacity.  With CP we have n variables and one constraint.  In MIP we have nm variables and n+m constraints.  This way to map global constraints to MIP constraints using binary variables is quite generic

CP and MIP solves problems in a different way.  Both use a divide and conquer approach, where the problem to be solved is recursively split into sub problems by fixing values of one variable at a time.  The main difference lies in what happens at each node of the resulting problem tree.  In MIP one usually solves a linear relaxation of the problem and uses the result to guide search.  This is a branch and bound search.  In CP, logical inferences based on the combinatorial nature of each global constraint are performed.  This is an implicit enumeration search.

Optimization differences:

A constraint programming engine makes decisions on variables and values and, after each decision, performs a set of logical inferences to reduce the available options for the remaining variables' domains. In contrast, an mathematical programming engine, in the context of discrete optimization, uses a combination of relaxations (strengthened by cutting-planes) and "branch and bound."

A constraint programming engine proves optimality by showing that no better solution than the current one can be found, while an mathematical programming engine uses a lower bound proof provided by cuts and linear relaxation.

A constraint programming engine doesn't make assumptions on the mathematical properties of the solution space (convexity, linearity etc.), while an mathematical programming engine requires that the model falls in a well-defined mathematical category (for instance Mixed Integer Quadratic Programming (MIQP).

In deciding how you should define your problem - as MIP or CP, Google Optimization tools guide suggests: -

If all the constraints for the problem must hold for a solution to be feasible (constraints connected by "and" statements), then MIP is generally faster.

If many of the constraints have the property that just one of them needs to hold for a solution to be feasible (constraints connected by "or" statements), then CP is generally faster.

My 2 cents:

CP and MIP solves problems in a different way.  Both use a divide and conquer approach, where the problem to be solved is recursively split into sub problems by fixing values of one variable at a time.  The main difference lies in what happens at each node of the resulting problem tree.  In MIP one usually solves a linear relaxation of the problem and uses the result to guide search.  This is a branch and bound search.  In CP, logical inferences based on the combinatorial nature of each global constraint are performed.

There is no one specific answer to which approach would you use to formulate your model and solve the problem. CP would probably work better when the number of variables increase by a lot and the problem is difficult to formulate the constraints using linear equalities. If the MIP relaxation is tight, it can give better results - If you lower bound doesn't move enough while traversing your MIP problem, you might want to take higher degrees of MIP or CP into consideration. CP works well when the problem can be represented by Global constraints.

Some more reading on MIP and CP:

Mixed-Integer Programming problems has some of the decision variables constrained to integers (-n … 0 … n) at the optimal solution. This makes it easier to define the problems in terms of a mathematical program. MP focuses on special class of problems and is useful for solving relaxations or subproblems (vertical structure).

Example of a mathematical model:

Objective:  minimize cT x
   Constraints: A x = b (linear constraints)
l ≤ x ≤ u (bound constraints)
some or all xj must take integer values (integrality constraints)

Or the model could be define by Quadratic functions or constraints, (MIQP/ MIQCP problems)

 Objective:   minimize xT Q x + qT x
   Constraints: A x = b (linear constraints)
l ≤ x ≤ u (bound constraints)
xT Qi x + qiT x ≤ bi (quadratic constraints)
some or all x must take integer values (integrality constraints)

The most common algorithm used to converge MIP problems is the Branch and Bound approach.

CP:
CP stems from a problems in AI, Operations Research and Computer Science, thus it is closely affiliated to Computer Programming.
- Problems in this area assign symbolic values to variables that need to satisfy certain constraints.
- These symbolic values have a finite domain and can be labelled with integers.
- CP modelling language is more flexible and closer to natural language.

Quoted from one of the IBM docs, constraint Programming is a technology where:

business problems are modeled using a richer modeling language than what is traditionally found in mathematical optimization

problems are solved with a combination of tree search, artificial intelligence and graph theory techniques

The most common constraint(global) is the "alldifferent" constraint, which ensures that the decision variables assume some permutation (non-repeating ordering) of integer values. Ex. If the domain of the problem is 5 decision variables viz. 1,2,3,4,5, they can be ordered in any non-repetitive way.

Title: Difference LP/MIP and CP


问:
What C++17 standard say about calling delete on nullptr?
C++03 Standard say's:

5.3.5 Delete

[...] In either alternative, if the value of the operand of delete is the null pointer the operation has no effect.[...]

```<code>char *p = nullptr;
delete p; //no effect
</code>```

It means, it is valid to delete null pointer in c++.

What C++17 standard say about calling delete on nullptr pointer?

答:
For destructors, [expr.delete]/6:

If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted.

This technically doesn't say that if the operand is a null pointer value, the destructor isn't invoked. Probably a minor wording issue?

For deallocation, [expr.delete]/7:

If the value of the operand of the delete-expression is a null pointer value, it is unspecified whether a deallocation function will be called as described above.

Unspecified deallocation, but likely no destruction.

Note also, from [basic.stc.dynamic.deallocation]/3, which clarifies that even if the standard library deallocation function is called in this situation, there is no effect:

The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect.

Body:
C++03 Standard say's:

5.3.5 Delete

[...] In either alternative, if the value of the operand of delete is the null pointer the operation has no effect.[...]

char *p = nullptr;
delete p; //no effect

It means, it is valid to delete null pointer in c++.

What C++17 standard say about calling delete on nullptr pointer?


问:
Is it possible to add a string with spaces or special characters to an enum?
Is it possible to add a string with spaces or special characters to an enum?

For example, I have a string Insurance KR Users (Name), I have tried to include this string into an enum:

```<code>    public enum MemberGroup
    {
        Insurance KR Users (Name)
    }
</code>```

but it throws an error.

How can I include these types of strings into enum?

答:
The enum itself can't contain spaces, and as Peter says, it can only contain a certain set of characters.

You could use the enum's Description attribute however to store some extra information, but this would have to be retrieved using reflection. There are quite a few examples over the internet how to do it, but just as an example, here is one.

Body:
Is it possible to add a string with spaces or special characters to an enum?

For example, I have a string Insurance KR Users (Name), I have tried to include this string into an enum:

    public enum MemberGroup
    {
        Insurance KR Users (Name)
    }

but it throws an error.

How can I include these types of strings into enum?

ContentLicense: CC BY-SA 2.5


问:
YouTube Upload Error - Upload failed: Can't process file
I am using this sample application for uploading a video on to YouTube. Initially I can able to upload the videos successfully without any issue, but after few days suddenly I have been facing the below error.

https://github.com/youtube/api-samples/tree/master/java

After completing upload, when I check the video in the Videos list of my channel, there it is showing an error(Upload failed: Can't process file) like below

The class I am using is

https://github.com/youtube/api-samples/blob/master/java/src/main/java/com/google/api/services/samples/youtube/cmdline/data/UploadVideo.java

And while executing, the messages in the console are as in the below.

```<code>Jul 15, 2017 2:02:59 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for everybody: C:\Users\Krishna\.oauth-credentials
Jul 15, 2017 2:02:59 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for owner: C:\Users\Krishna\.oauth-credentials

is is not empty
Initiation Started
Initiation Completed
Upload in progress
Upload percentage: 10485760
Upload Completed!

================== Returned Video ==================

  - Id: wYB8OfEe9jU
  - Title: ex
  - Tags: [video, file]
  - Privacy Status: public
  - Video Count: 0
</code>```

答: Your upload limit might have hit with your sample account on YouTube. I remember when I first started using YouTube, and used the Sample Account, and sooner or later I couldn't upload anymore videos. I had to create a full account with YouTube. I would try to login with a Google account you've, or even making a Google account and signing in with that Google account and see if that works for you!</p>

Body:
I am using this sample application for uploading a video on to YouTube. Initially I can able to upload the videos successfully without any issue, but after few days suddenly I have been facing the below error.

https://github.com/youtube/api-samples/tree/master/java

After completing upload, when I check the video in the Videos list of my channel, there it is showing an error(Upload failed: Can't process file) like below

The class I am using is

https://github.com/youtube/api-samples/blob/master/java/src/main/java/com/google/api/services/samples/youtube/cmdline/data/UploadVideo.java

And while executing, the messages in the console are as in the below.

Jul 15, 2017 2:02:59 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for everybody: C:\Users\Krishna\.oauth-credentials
Jul 15, 2017 2:02:59 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for owner: C:\Users\Krishna\.oauth-credentials

is is not empty
Initiation Started
Initiation Completed
Upload in progress
Upload percentage: 10485760
Upload Completed!

================== Returned Video ==================

  - Id: wYB8OfEe9jU
  - Title: ex
  - Tags: [video, file]
  - Privacy Status: public
  - Video Count: 0


问:
Angular2 Hashtag routing to Anchor doesnt move page
So I used the following post to figure out how to add a fragment to the url.

Angular2 Routing with Hashtag to page anchor

And the fragment gets added fine, however the page doesn't move to the resulting anchor. I have tried using both the name and id attribute on the destination div, but neither seem to work.

I'm using Angular Version 2.0.0-rc.3, and router version 3.0.0-alpha.6.

Thanks!

```<code><a [routerLink]="[]" fragment="destination">Go TO DIV</a>

<div id='destination'>
    <h2>Destination</h2>
</div>
</code>```

There is enough space between the 2 elements to tell if the page actually moves.

And as said before, the url correctly adds #destination to itself.

答:
After seeing all the solutions here, I decided to go with a small and simple directive. Here's what I ended up with:

```<code>import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({ selector: '[appAnchorTo]' })
export class AnchorToDirective {
  @Input() target: string;

  constructor(el: ElementRef) { el.nativeElement.style.cursor = 'pointer'; }

  @HostListener('click', ['$event'])
  onClick() { document.querySelector(this.target).scrollIntoView(); }
}
</code>```

The idea was to create something flexible, that could be attached to any element on the page.

Usage:

```<code><a appAnchorTo target="#my-link">My Insights</a>
<div appAnchorTo target="#my-other-link">My Customers</div>
</code>```

And don't forget to declare the directive on one of your Modules:

```<code>@NgModule({
    ...,
    declarations: [
        ...,
        AnchorToDirective,
    ]
})
</code>```

Body:
So I used the following post to figure out how to add a fragment to the url.

Angular2 Routing with Hashtag to page anchor

And the fragment gets added fine, however the page doesn't move to the resulting anchor. I have tried using both the name and id attribute on the destination div, but neither seem to work.

I'm using Angular Version 2.0.0-rc.3, and router version 3.0.0-alpha.6.

Thanks!

Go TO DIV

Destination

There is enough space between the 2 elements to tell if the page actually moves.

And as said before, the url correctly adds #destination to itself.

Body:
After seeing all the solutions here, I decided to go with a small and simple directive. Here's what I ended up with:

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({ selector: '[appAnchorTo]' })
export class AnchorToDirective {
  @Input() target: string;

  constructor(el: ElementRef) { el.nativeElement.style.cursor = 'pointer'; }

  @HostListener('click', ['$event'])
  onClick() { document.querySelector(this.target).scrollIntoView(); }
}

The idea was to create something flexible, that could be attached to any element on the page.

Usage:

<a appAnchorTo target="#my-link">My Insights</a>
<div appAnchorTo target="#my-other-link">My Customers</div>

And don't forget to declare the directive on one of your Modules:

@NgModule({
    ...,
    declarations: [
        ...,
        AnchorToDirective,
    ]
})


问:
HttpListenerResponse adding a 2nd cookie makes all cookies disappear
I have the following code:

```<code>    void WriteConnectionId(HttpListenerContext context, string id)
    {
        var cookie = context.Response.Cookies[CookieConnectionId];
        if (cookie == null)
        {
            cookie = new Cookie(CookieConnectionId, id)
            {
                HttpOnly = true,
                Secure = true,
                Path = "/"
            };
            context.Response.Cookies.Add(cookie);
        }
        else
        {
            cookie.Value = id;
        }
        //context.Response.SetCookie(new Cookie("lalala", "lololo"));
    }
</code>```

This code stores correctly the cookie for "connection Id" in the client. In Chrome's console I can see the cookie in the list of cookies.

However, if I uncomment the last line that adds an extra cookie, then neither the session cookie or the dummy cookie make it to the client. They do not appear in Chrome's console.

Edit: removing the "/" path on the first cookie makes the first cookie appear, though with both values from the 1st and 2nd cookie concatenated with a comma.

答:
Try</p>

```<code>context.Response.AppendCookie(new Cookie("lalala", "lololo"));
</code>```

Body:
I have the following code:

    void WriteConnectionId(HttpListenerContext context, string id)
    {
        var cookie = context.Response.Cookies[CookieConnectionId];
        if (cookie == null)
        {
            cookie = new Cookie(CookieConnectionId, id)
            {
                HttpOnly = true,
                Secure = true,
                Path = "/"
            };
            context.Response.Cookies.Add(cookie);
        }
        else
        {
            cookie.Value = id;
        }
        //context.Response.SetCookie(new Cookie("lalala", "lololo"));
    }

This code stores correctly the cookie for "connection Id" in the client. In Chrome's console I can see the cookie in the list of cookies.

However, if I uncomment the last line that adds an extra cookie, then neither the session cookie or the dummy cookie make it to the client. They do not appear in Chrome's console.

Edit: removing the "/" path on the first cookie makes the first cookie appear, though with both values from the 1st and 2nd cookie concatenated with a comma.

Body:
Try

context.Response.AppendCookie(new Cookie("lalala", "lololo"));


问:
Filter array of dates
I know that there is .filter () in it that filters an array to return it just the way I want, and using a lot to search, when we pass what we want to search in that array.

However I'm having trouble filtering an array of dates like this:

```<code>["08:00" "09:00" "10:10" "10:30" "10:50" "11:30" "11:50" "12:00"];
</code>```

I need to filter it by past date I have start date and end date, for example step to it " 09:00 " and " 11:30 " it should return to me:

```<code>["10:10" "10:30" "10:50"]
</code>```

Trying to do this I did so in my typescript:

```<code>1. this.schedules = this.navigation.lineSelected.schedules;
2. this.schedules.filter (item => {
3. item> this.hourNow && item <this.hourFinish
4.});
</code>```

On line 1 I get all the times I have, so on line 2.4 I filter this array, but it returns everything to me.

How can I do this?

Translating what I need:

I'm going to have two strings of hours like "12:00" and "15:00" I need to make comparisons in my array, because I need the hours that are between interval as in the above example.

When I say time I'm talking about a string, so I need to compare string if it's bigger or not than the other type string that are below "12:00" will not appear in my final array, and strings larger than "15:00" will also do not.

This is the best way I can explain what I need, I do not see any other option to explain. Simply filter an array

答:
You could just filter the values with a trimmed min and max value.

var array = ["08:00", "09:00", "10:10", "10:30", "10:50", "11:30", "11:50", "12:00"],
    min = "09:00",
    max = "11:30",
    result = array.filter(a => a > min && a < max);

console.log(result);```

Title: Filter array of dates

Body:
I know that there is .filter () in it that filters an array to return it just the way I want, and using a lot to search, when we pass what we want to search in that array.

However I'm having trouble filtering an array of dates like this:

["08:00" "09:00" "10:10" "10:30" "10:50" "11:30" "11:50" "12:00"];

I need to filter it by past date I have start date and end date, for example step to it " 09:00 " and " 11:30 " it should return to me:

["10:10" "10:30" "10:50"]

Trying to do this I did so in my typescript:

1. this.schedules = this.navigation.lineSelected.schedules;
2. this.schedules.filter (item => {
3. item> this.hourNow && item <this.hourFinish
4.});

On line 1 I get all the times I have, so on line 2.4 I filter this array, but it returns everything to me.

How can I do this?

Translating what I need:

I'm going to have two strings of hours like "12:00" and "15:00" I need to make comparisons in my array, because I need the hours that are between interval as in the above example.

When I say time I'm talking about a string, so I need to compare string if it's bigger or not than the other type string that are below "12:00" will not appear in my final array, and strings larger than "15:00" will also do not.

This is the best way I can explain what I need, I do not see any other option to explain. Simply filter an array


问:
Access C array of type const char * from Go
I have a C file with an array of type const char *, lets call it myStringArray[], something like:

```<code>const char *myStringArray[] = {
  "NAME_OF_FIRST_THING",
  "NAME_OF_SECOND_THING",
  "NAME_OF_THIRD_THING"}
</code>```

I need Go to index into that C array, using cgo, and convert an array entry into a Go string.  The following code compiles but does not work correctly; you can see from the output that follows, it is indexing along the strings rather than up the array:

myGoString := C.GoString((*C.char) (unsafe.Pointer(uintptr(unsafe.Pointer(C.myStringArray)) + uintptr(index) * unsafe.Sizeof(C.myStringArray))))

...result being this:

NAME_OF_FIRST_THING

FIRST_THING

ING

FYI, the purpose of this is to decode on a server a log file that was created on an embedded platform running C, hence the need to re-use the same logging index files.

I've been stabbing at this randomly for a few hours now without success. Can anyone correct my construction, or provide an alternative?

答:
While you could do the pointer arithmetic yourself, it's safer and more convenient to convert the C array into a Go slice first.

```<code>arraySize := 3
cStrings := (*[1 << 30]*C.char)(unsafe.Pointer(&C.myStringArray))[:arraySize:arraySize]

for _, cString := range cStrings {
    fmt.Println(C.GoString(cString))
}

// prints:
// NAME_OF_FIRST_THING
// NAME_OF_SECOND_THING
// NAME_OF_THIRD_THING
</code>```

Relevant cgo wiki entry: https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices

Body:
I have a C file with an array of type const char *, lets call it myStringArray[], something like:

const char *myStringArray[] = {
  "NAME_OF_FIRST_THING",
  "NAME_OF_SECOND_THING",
  "NAME_OF_THIRD_THING"}

I need Go to index into that C array, using cgo, and convert an array entry into a Go string.  The following code compiles but does not work correctly; you can see from the output that follows, it is indexing along the strings rather than up the array:

myGoString := C.GoString((*C.char) (unsafe.Pointer(uintptr(unsafe.Pointer(C.myStringArray)) + uintptr(index) * unsafe.Sizeof(C.myStringArray))))

...result being this:

NAME_OF_FIRST_THING

FIRST_THING

ING

FYI, the purpose of this is to decode on a server a log file that was created on an embedded platform running C, hence the need to re-use the same logging index files.

I've been stabbing at this randomly for a few hours now without success. Can anyone correct my construction, or provide an alternative?

Body:
While you could do the pointer arithmetic yourself, it's safer and more convenient to convert the C array into a Go slice first.

arraySize := 3
cStrings := (*[1 << 30]*C.char)(unsafe.Pointer(&C.myStringArray))[:arraySize:arraySize]

for _, cString := range cStrings {
    fmt.Println(C.GoString(cString))
}

// prints:
// NAME_OF_FIRST_THING
// NAME_OF_SECOND_THING
// NAME_OF_THIRD_THING

Relevant cgo wiki entry: https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices


问:
how to create a self-defined ciphersuite and use it by setEnabledCipherSuites(_)?
I am trying to write a self-defined ciphersuite and use it for tls connection, how can this be implemented?

thx!

答:
This question is really general, you may want to rephrase it after reading How to ask.

We need more context on what you're trying to accomplish. SSLSocket.setEnabledCipherSuites() uses the built in implementation cipher suites, so you would have to modify the javax.net.ssl.SSLSocket class to support your custom suite, which may be more than you want to do.


问:
Table added through ckeditor doesn't retains the style attribute
I have integrated ckeditor in a web page which uses table plugin to allow users to create tables in the editor window. When the user exits the editor window and the result is shown on the page the table width sometimes gets much wider than the web page.

I have made changes so that the editor allows style tags like:

```<code>CKEDITOR.replace('editor', {
    extraAllowedContent: 'table{*}'
});
</code>```

Also made this change to ckeditor's config.js for making default width of table as 100%:

```<code>CKEDITOR.on('dialogDefinition', function (ev) {
    var dialogName = ev.data.name;
    var dialogDefinition = ev.data.definition;
    if (dialogName == 'table') {
        var info = dialogDefinition.getContents('info');
        info.get('txtWidth')['default'] = '100%';
    }
});
</code>```

But I'm not able to set table-layout as fixed so that when the table is shown on web page the table is fixed in its 100% width on the web page.

答:
If the table has width:100% when data is extracted from CKEditor (you can verify it via editor.getData method), its width depends on the parent element width in which it is placed on the website. If the parent (direct or not) element has fixed width, the table should not expand beyond it.

See this codepen: https://codepen.io/f1ames/pen/ZaaRPy

Maybe you can share you html code or prepare some snippet showing the issue if above answer is not enough?

Body:
I have integrated ckeditor in a web page which uses table plugin to allow users to create tables in the editor window. When the user exits the editor window and the result is shown on the page the table width sometimes gets much wider than the web page.

I have made changes so that the editor allows style tags like:

CKEDITOR.replace('editor', {
    extraAllowedContent: 'table{*}'
});

Also made this change to ckeditor's config.js for making default width of table as 100%:

CKEDITOR.on('dialogDefinition', function (ev) {
    var dialogName = ev.data.name;
    var dialogDefinition = ev.data.definition;
    if (dialogName == 'table') {
        var info = dialogDefinition.getContents('info');
        info.get('txtWidth')['default'] = '100%';
    }
});

But I'm not able to set table-layout as fixed so that when the table is shown on web page the table is fixed in its 100% width on the web page.


问:
Cannot update state from render method React
I have a NavLink component like this:

```<code><NavLink  isActive={(match, location) => this.isActiveFunc(match, location)}  className={classes.subLink} to={{ pathname: "/admin/users" }}>
    <ListItem button className={classes.nested}>
       <ListItemText disableTypography={this.state.activePath === "/admin/users"} inset primary="Users" />
    </ListItem>
</NavLink>
</code>```

and try to set my state every time the NavLink is active as follows:

```<code> updateActivePath = (match) => {
    if (match && this.state.activePath !== match.path) {
      this.setState({activePath: match.path})
    }
  };

  isActiveFunc = (match, location) => {
    this.updateActivePath(match);
  };
</code>```

This however gives me the following error:

Warning: Cannot update during an existing state transition (such as
  within render or another component's constructor). Render methods
  should be a pure function of props and state; constructor side-effects
  are an anti-pattern, but can be moved to componentWillMount.

Any ideas how I can fix this?

答:
If the "state" you're after is already in React Router, then copying it to your own state is unnecessary duplication, and the cause of your error (trying to update the state during render. You're better off just grabbing the state from the React Router. You can use a Route without a path for that

```<code><Route render={({ location }) => (
   // this will render whenever the location changes
   <YourNavigationBar location={location} />
  )}
/>
</code>```

Body:
I have a NavLink component like this:

<NavLink  isActive={(match, location) => this.isActiveFunc(match, location)}  className={classes.subLink} to={{ pathname: "/admin/users" }}>
    <ListItem button className={classes.nested}>
       <ListItemText disableTypography={this.state.activePath === "/admin/users"} inset primary="Users" />
    </ListItem>
</NavLink>

and try to set my state every time the NavLink is active as follows:

 updateActivePath = (match) => {
    if (match && this.state.activePath !== match.path) {
      this.setState({activePath: match.path})
    }
  };

  isActiveFunc = (match, location) => {
    this.updateActivePath(match);
  };

This however gives me the following error:

Warning: Cannot update during an existing state transition (such as
  within render or another component's constructor). Render methods
  should be a pure function of props and state; constructor side-effects
  are an anti-pattern, but can be moved to componentWillMount.

Any ideas how I can fix this?

Body:
If the "state" you're after is already in React Router, then copying it to your own state is unnecessary duplication, and the cause of your error (trying to update the state during render. You're better off just grabbing the state from the React Router. You can use a Route without a path for that

<Route render={({ location }) => (
   // this will render whenever the location changes
   <YourNavigationBar location={location} />
  )}
/>