问:
Memcpy a str[ ] to str*
I'm trying to create a xoring function ( I want to XOR 2 strings and return the result).

For that, I need to copy the content a an array (str[ ]) to a string (str* ).

```<code>char* xor(char* str1, char* str2)
{
    char temp[strlen(str1)];
    char* result = NULL;
    int i;

    for(i=0; i<=strlen(str1); i++)
    {
        temp[i] = str1[i] ^ str2[i];
    }
    memcpy(result,temp,sizeof(temp)+1);
    return result;
}
</code>```

I'm getting a seg fault for my memcpy.

Am I missing something ? Can you help me ?

答:
You didn't allocate memory for result and you passed NULL to memcpy(); that is undefined behavior.

```<code>#include <stdlib.h>
#include <string.h>

char *xor(char const *a, char const *b) {
  size_t const size = strlen(a);
  if (size != strlen(b)) {
    return NULL;
  }

  char *result = malloc(size + 1);
  if (!result) {
    return NULL;
  }

  for (size_t i = 0; i < size; i++) {
    result[i] = a[i] ^ b[i];
  }
  result[size] = '\0';

  return result;
}
</code>```

Title: Memcpy a str[ ] to str*

Body:
I'm trying to create a xoring function ( I want to XOR 2 strings and return the result).

For that, I need to copy the content a an array (str[ ]) to a string (str* ).

char* xor(char* str1, char* str2)
{
    char temp[strlen(str1)];
    char* result = NULL;
    int i;

    for(i=0; i<=strlen(str1); i++)
    {
        temp[i] = str1[i] ^ str2[i];
    }
    memcpy(result,temp,sizeof(temp)+1);
    return result;
}

I'm getting a seg fault for my memcpy.

Am I missing something ? Can you help me ?

Body:
You didn't allocate memory for result and you passed NULL to memcpy(); that is undefined behavior.

#include <stdlib.h>
#include <string.h>

char *xor(char const *a, char const *b) {
  size_t const size = strlen(a);
  if (size != strlen(b)) {
    return NULL;
  }

  char *result = malloc(size + 1);
  if (!result) {
    return NULL;
  }

  for (size_t i = 0; i < size; i++) {
    result[i] = a[i] ^ b[i];
  }
  result[size] = '\0';

  return result;
}


来源: stackexchange

问:
Show div's based on a randomly shuffled array using javascript/jquery
Essentially I'm trying to write a Javascript/Jquery script which will show/hide a number of div's one at a time in an order determined by a randomly shuffled series of numbers.

I've managed to get the scripts to shuffle the numbers and cycle through the divs working but I'm not sure how to combine the two.

The script so far looks like this

```<code>$(document).ready(function() {

    function shuffle(arra1) {
        var ctr = arra1.length, temp, index;

        // While there are elements in the array
        while (ctr > 0) {
            // Pick a random index
            index = Math.floor(Math.random() * ctr);
            // Decrease ctr by 1
            ctr--;
            // And swap the last element with it
            temp = arra1[ctr];
            arra1[ctr] = arra1[index];
            arra1[index] = temp;
        }

        return arra1;
    }

    var myArray = [0, 1, 2, 3, 4, 5];
    console.log(shuffle(myArray));

    var divs = $('div[id^="random"]').hide(),
        i = 0;

    (function cycle() {
        divs.eq(i).fadeIn(400)
                  .delay(1000)
                  .fadeOut(400, cycle);

        i = ++i % divs.length;
    })();
});
</code>```

The div's that I'm trying to cycle through in the HTML look Like this

```<code><div id="random-divs">
    <div id="random0">Div 0</div>
    <div id="random1">Div 1</div>
    <div id="random2">Div 2</div>
    <div id="random3">Div 3</div>
    <div id="random4">Div 4</div>
    <div id="random5">Div 5</div>
</div>
</code>```

If anyone could point me in the right direction I'd greatly appreciate it.

答:
The easiest change would be to replace divs.eq(i) with divs.eq(myArray[i]), taking into account the shuffled positions.

However, instead of shuffling an array with indices, it would in general be easier to understand if you just would shuffle an array with the elements themselves:

```<code>var divs = $('div[id^="random"]').hide().toArray()
    i = 0;
shuffle(divs);

(function cycle() {
    $(divs[i]).fadeIn(400)
              .delay(1000)
              .fadeOut(400, cycle);

    i = ++i % divs.length;
})();
</code>```

You might not even need the toArray and $(divs[i]), your shuffle function is generic enough to work on jQuery collections as well.

ContentLicense: CC BY-SA 3.0

Body:
Essentially I'm trying to write a Javascript/Jquery script which will show/hide a number of div's one at a time in an order determined by a randomly shuffled series of numbers.

I've managed to get the scripts to shuffle the numbers and cycle through the divs working but I'm not sure how to combine the two.

The script so far looks like this

$(document).ready(function() {

    function shuffle(arra1) {
        var ctr = arra1.length, temp, index;

        // While there are elements in the array
        while (ctr > 0) {
            // Pick a random index
            index = Math.floor(Math.random() * ctr);
            // Decrease ctr by 1
            ctr--;
            // And swap the last element with it
            temp = arra1[ctr];
            arra1[ctr] = arra1[index];
            arra1[index] = temp;
        }

        return arra1;
    }

    var myArray = [0, 1, 2, 3, 4, 5];
    console.log(shuffle(myArray));

    var divs = $('div[id^="random"]').hide(),
        i = 0;

    (function cycle() {
        divs.eq(i).fadeIn(400)
                  .delay(1000)
                  .fadeOut(400, cycle);

        i = ++i % divs.length;
    })();
});

The div's that I'm trying to cycle through in the HTML look Like this

Div 0

Div 1

Div 2

Div 3

Div 4

Div 5

If anyone could point me in the right direction I'd greatly appreciate it.

Body:
The easiest change would be to replace divs.eq(i) with divs.eq(myArray[i]), taking into account the shuffled positions.

However, instead of shuffling an array with indices, it would in general be easier to understand if you just would shuffle an array with the elements themselves:

var divs = $('div[id^="random"]').hide().toArray()
    i = 0;
shuffle(divs);

(function cycle() {
    $(divs[i]).fadeIn(400)
              .delay(1000)
              .fadeOut(400, cycle);

    i = ++i % divs.length;
})();

You might not even need the toArray and $(divs[i]), your shuffle function is generic enough to work on jQuery collections as well.


问:
how to get the whole tweet instead of a part of tweet with links
I am using Twython library for tweets acquisition. but most of the tweets are not complete and end with a short URL where the whole tweet is present. Is there any way that I can get through it.
here is the sample code:

```<code>results=twitter.search(q="python")
all_tweets=results['statuses']
for tweet in all_tweets:
    print(tweet['text'])
</code>```

答:
In order to see the extended tweet you just need to supply this parameter to your search query: tweet_mode=extended.

Then, you will find the extended tweet in the full_text field of the returned tweet. I don't work in Python, but based on the documentation I think you should do something like:

```<code>results = twitter.search(q='pizza', tweet_mode='extended')
for result in results['statuses']:
    print(result['full_text'])
</code>```

Body:
I am using Twython library for tweets acquisition. but most of the tweets are not complete and end with a short URL where the whole tweet is present. Is there any way that I can get through it.
here is the sample code:

results=twitter.search(q="python")
all_tweets=results['statuses']
for tweet in all_tweets:
    print(tweet['text'])

Body:
In order to see the extended tweet you just need to supply this parameter to your search query: tweet_mode=extended.

Then, you will find the extended tweet in the full_text field of the returned tweet. I don't work in Python, but based on the documentation I think you should do something like:

results = twitter.search(q='pizza', tweet_mode='extended')
for result in results['statuses']:
    print(result['full_text'])


问:
Check if a user is authenticated in controller
There are many code snippets how to check if authenticated user is authorized to request a resource. But i cannot find a example to check if the user is authenticated at all.

I've got a kernel request listener, in which i'm trying to check if a user is authenticated, using this code:

```<code>if (TRUE === $this->get('security.authorization_checker')->isGranted('ROLE_USER'))
{
    //doing stuff
}
</code>```

I get the following error message:

```<code>AuthenticationCredentialsNotFoundException in classes.php line 5307:
The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL.
</code>```

I guess, this is because the user is not logged in at all, and therefore doesn't have any authentication token.

So my question is: how do i, in a symfony controller, check if a user is authenticated before i check if he is authorized?

答:
Referring to the official documentation, you can use IS_AUTHENTICATED_FULLY or IS_AUTHENTICATED_REMEMBERED:

```<code>if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
    throw $this->createAccessDeniedException();
}

// do stuff
</code>```

Body:
There are many code snippets how to check if authenticated user is authorized to request a resource. But i cannot find a example to check if the user is authenticated at all.

I've got a kernel request listener, in which i'm trying to check if a user is authenticated, using this code:

if (TRUE === $this->get('security.authorization_checker')->isGranted('ROLE_USER'))
{
    //doing stuff
}

I get the following error message:

AuthenticationCredentialsNotFoundException in classes.php line 5307:
The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL.

I guess, this is because the user is not logged in at all, and therefore doesn't have any authentication token.

So my question is: how do i, in a symfony controller, check if a user is authenticated before i check if he is authorized?

Body:
Referring to the official documentation, you can use IS_AUTHENTICATED_FULLY or IS_AUTHENTICATED_REMEMBERED:

if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
    throw $this->createAccessDeniedException();
}

// do stuff


问:
Problem with RDD bash script variable
I have the folowing bash script i'm trying to implement, but it fails awfully, can anyone help me with some advice...

```<code>#!/bin/bash
FILE='/var/www/router.rrd'
OUTPUT='/var/www/router.png'
RRDTOOL='rrdtool graph'
$RRDTOOL $OUTPUT \
        -t "192.168.10.1" -v "Time in ms" \
        --start="now-1d" \
        --end="now" \
        --height="120" \
        --width="440" \
        "DEF:ping_time=$FILE:ping:AVERAGE" \
        "CDEF:shading2=ping_time,0.98,*" "AREA:shading2#F90000:router" \
        "GPRINT:ping_time:LAST:Last\: %5.2lf ms" \
        "GPRINT:ping_time:MIN:Min\: %5.2lf ms" \
        "GPRINT:ping_time:MAX:Max\: %5.2lf ms" \
        "GPRINT:ping_time:AVERAGE:Avg\: %5.2lf ms" >/dev/null
</code>```

The error mesages are like the folowing

```<code>
hostname:/# sh -v /var/www/router.sh
FILE='/var/www/router.rrd'
OUTPUT='/var/www/router.png'
RRDTOOL='rrdtool graph'
HOST='hello'
: command not foundre_retea/ping/router.sh: line 6:
"$RRDTOOL" $OUTPUT \
: command not foundre_retea/ping/router.sh: line 7: rrdtool graph
        -t "192.168.10.1" -v "Time in ms" \
/var/www/router.sh: line 8: -t: command not found
        --start="now-1d" \
/var/www/router.sh: line 9: --start=now-1d: command not found
        --end="now" \
/var/www/router.sh: line 10: --end=now: command not found
        --height="120" \
/var/www/router.sh: line 11: --height=120: command not found
        --width="440" \
/var/www/router.sh: line 12: --width=440: command not found
        "DEF:ping_time=$FILE:ping:AVERAGE" \
/var/www/router.sh: line 13: DEF:ping_time=/var/www/router.:ping:AVERAGE: No such file or directory
        "CDEF:shading2=ping_time,0.98,*" "AREA:shading2#F90000:router" \
/var/www/monitorizare_retea/ping/100.100.100.6_graph.sh: line 14: CDEF:shading2=ping_time,0.98,*: command not found
        "GPRINT:ping_time:LAST:Last\: %5.2lf ms" \
.... and so on
```

答:
My first guess is that it gives you an error that says "command not found". If that's the case it's because you're putting a command and an argument in a variable. Don't do that. Please see BashFAQ/050.

Additionally, it looks like your script file may have Windows line endings. If that's the case then running dos2unix on it will fix that.

```<code>dos2unix scriptname
</code>```

Another possibility is that you may have white space after your line-continuation backslashes. Removing the white space characters may help:

```<code>sed 's/\\[[:blank:]]\+$/\\/' scriptname
</code>```

ContentLicense: CC BY-SA 2.5

Title: Problem with RDD bash script variable

Body:
I have the folowing bash script i'm trying to implement, but it fails awfully, can anyone help me with some advice...

#!/bin/bash
FILE='/var/www/router.rrd'
OUTPUT='/var/www/router.png'
RRDTOOL='rrdtool graph'
$RRDTOOL $OUTPUT \
        -t "192.168.10.1" -v "Time in ms" \
        --start="now-1d" \
        --end="now" \
        --height="120" \
        --width="440" \
        "DEF:ping_time=$FILE:ping:AVERAGE" \
        "CDEF:shading2=ping_time,0.98,*" "AREA:shading2#F90000:router" \
        "GPRINT:ping_time:LAST:Last\: %5.2lf ms" \
        "GPRINT:ping_time:MIN:Min\: %5.2lf ms" \
        "GPRINT:ping_time:MAX:Max\: %5.2lf ms" \
        "GPRINT:ping_time:AVERAGE:Avg\: %5.2lf ms" >/dev/null

The error mesages are like the folowing

hostname:/# sh -v /var/www/router.sh
FILE='/var/www/router.rrd'
OUTPUT='/var/www/router.png'
RRDTOOL='rrdtool graph'
HOST='hello'
: command not foundre_retea/ping/router.sh: line 6:
"$RRDTOOL" $OUTPUT \
: command not foundre_retea/ping/router.sh: line 7: rrdtool graph
        -t "192.168.10.1" -v "Time in ms" \
/var/www/router.sh: line 8: -t: command not found
        --start="now-1d" \
/var/www/router.sh: line 9: --start=now-1d: command not found
        --end="now" \
/var/www/router.sh: line 10: --end=now: command not found
        --height="120" \
/var/www/router.sh: line 11: --height=120: command not found
        --width="440" \
/var/www/router.sh: line 12: --width=440: command not found
        "DEF:ping_time=$FILE:ping:AVERAGE" \
/var/www/router.sh: line 13: DEF:ping_time=/var/www/router.:ping:AVERAGE: No such file or directory
        "CDEF:shading2=ping_time,0.98,*" "AREA:shading2#F90000:router" \
/var/www/monitorizare_retea/ping/100.100.100.6_graph.sh: line 14: CDEF:shading2=ping_time,0.98,*: command not found
        "GPRINT:ping_time:LAST:Last\: %5.2lf ms" \
.... and so on

Body:
My first guess is that it gives you an error that says "command not found". If that's the case it's because you're putting a command and an argument in a variable. Don't do that. Please see BashFAQ/050.

Additionally, it looks like your script file may have Windows line endings. If that's the case then running dos2unix on it will fix that.

dos2unix scriptname

Another possibility is that you may have white space after your line-continuation backslashes. Removing the white space characters may help:

sed 's/\\[[:blank:]]\+$/\\/' scriptname


问:
Espresso- lines in the text view
I am trying to get a number of lines, in Espresso, of the TextView from one of the elements from recycler view. This is my macher for it:

```<code> public static TypeSafeMatcher<RecyclerView.ViewHolder> isTextInLines(final int lines) {
    return new TypeSafeMatcher<RecyclerView.ViewHolder>() {
        @Override
        protected boolean matchesSafely(RecyclerView.ViewHolder item) {
            Log.e("Lines", ((TextView) item.itemView.findViewById(R.id.textTextView)).getLineCount() + "");
            return ((TextView) item.itemView.findViewById(R.id.textTextView)).getLineCount() == lines;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("isTextInLines");
        }
    };
}
</code>```

The problem is that it prints that all of them has 0 lines. As I understand the problem might be that it is still in drawing phase according to this:

https://stackoverflow.com/a/24035591/6470918

Any idea how to solve it?

PS. This is the code which uses this matcher:

```<code>onView(withId(R.id.recyclerView))
            .perform(scrollToHolder(isTextInLines(12)));
</code>```

答:
Any RecyclerViewAction::scrollTo...  binds all adapter items to the in memory ViewHolders and loops over those to find the adapter position of the item that you are interested in and then scrolls to that position. And because of this, these ViewHolders are never laid out.

Unfortunately, to get the number of lines of the TextView it has to be laid out first.

You can work your problem around with normal ViewAssertion like so onView(matcher).check(matches(isTextInLines(12)) or even onView(isTextInLines(12)).check(matches(isDisplayed())

You might need to scroll to the ViewHolder using other matchers that don't require layout pass first, in case the ViewHolder is off the screen.

Title: Espresso- lines in the text view

Body:
I am trying to get a number of lines, in Espresso, of the TextView from one of the elements from recycler view. This is my macher for it:

 public static TypeSafeMatcher<RecyclerView.ViewHolder> isTextInLines(final int lines) {
    return new TypeSafeMatcher<RecyclerView.ViewHolder>() {
        @Override
        protected boolean matchesSafely(RecyclerView.ViewHolder item) {
            Log.e("Lines", ((TextView) item.itemView.findViewById(R.id.textTextView)).getLineCount() + "");
            return ((TextView) item.itemView.findViewById(R.id.textTextView)).getLineCount() == lines;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("isTextInLines");
        }
    };
}

The problem is that it prints that all of them has 0 lines. As I understand the problem might be that it is still in drawing phase according to this:

https://stackoverflow.com/a/24035591/6470918

Any idea how to solve it?

PS. This is the code which uses this matcher:

onView(withId(R.id.recyclerView))
            .perform(scrollToHolder(isTextInLines(12)));


问:
How do you track database changes in source control?
We use SQL Server 2000/2005 and Vault or SVN on most of our projects. I haven't found a decent solution for capturing database schema/proc changes in either source control system.

Our current solution is quite cumbersome and difficult to enforce (script out the object you change and commit it to the database).

We have a lot of ideas of how to tackle this problem with some custom development, but I'd rather install an existing tool (paid tools are fine).

So: how do you track your database code changes? Do you have any recommended tools?

Edit:

Thanks for all the suggestions. Due to time constraints, I'd rather not roll my own here. And most of the suggestions have the flaw that they require the dev to follow some procedure.

Instead, an ideal solution would monitor the SQL Database for changes and commit any detected changes to SCM. For example, if SQL Server had an add-on that could record any DML change with the user that made the change, then commit the script of that object to SCM, I'd be thrilled.

We talked internally about two systems:
  1. In SQL 2005, use object permissions to restrict you from altering an object until you did a "checkout". Then, the checkin procedure would script it into the SCM.
  2. Run a scheduled job to detect any changes and commit them (anonymously) to SCM.

It'd be nice if I could skip the user-action part and have the system handle all this automatically.

答:
Tracking database changes directly from SSMS is possible using various 3rd party tools. ApexSQL Source Control automatically scripts any database object that is included in versioning. Commits cannot be automatically performed by the tool. Instead, the user needs to choose which changes will be committed.

When getting changes from a repository, ApexSQL Source Control is aware of a SQL database referential integrity. Thus, it will create a synchronization scripts including all dependent objects that will be wrapped in a transactions so, either all changes will be applied in case no error is encountered, or none of the selected changes is applied. In any case, database integrity remains unaffected.

OwnerDisplayName: Michael Haren

LastEditorDisplayName: Michael Haren


问:
Sequence does not reset after truncating the table
I use SELECT lastval() to get wrong serial id  after truncated  the table.

when I truncate the table, I use SELECT lastval(), I got the wrong ID/

答:
The best way to reset a sequence to start back with number 1 is to execute the following after you have successfully truncate it:

```<code>ALTER SEQUENCE <tablename>_<id>_seq RESTART WITH 1
</code>```

So, for example for the users table it would be:

```<code>ALTER SEQUENCE users_id_seq RESTART WITH 1
</code>```

Body:
The best way to reset a sequence to start back with number 1 is to execute the following after you have successfully truncate it:

ALTER SEQUENCE <tablename>_<id>_seq RESTART WITH 1

So, for example for the users table it would be:

ALTER SEQUENCE users_id_seq RESTART WITH 1


问:
Google Smart Home integration with my IoT device (clarification needed)
I am looking for some clarification to how Google Smart Home works.
I am looking to integrate my current end device which control lights with Google Smart Home.

My end device is running a very small microcontroller utilizing an RTOS (Linux is not available)

Here is how I see it (Please correct or comment)

To my understanding this requires me to host my own cloud service
which will talk to my current end device?

My cloud service will then talk to Google cloud service.

My cloud service defines the protocol to talk to multiple end devices

Google Smart Home define the protocol to talk to my cloud service

Questions

Is there any method of doing this without having my own cloud Service?

答:
That is a pretty basic summary of things - yes.

The crucial point there is that issuing a command to the Google Home does not have it send out a message on your local network. Google issues any commands from their network - not from your device.

This might seem like a minor detail, but it doesn't need to be a "cloud service" that you control that Google talks to. It does need to be a publicly accessible HTTPS endpoint. This could be a cloud service (and it would be in most cases), a public non-cloud server, or even just a public URL that has a tunnel to your private network (such as with ngrok).

The last is really how you'd get around having your own cloud service - you can setup the control on a local machine, and have a tunnel using ngrok.


问:
ViewModel cannot be instantiated in an Activity
I am trying to instantiate one ViewModel to use across all of my Activity(s).

```<code>public class LaunchActivity extends Activity {
    private Controller control;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_launch);
         control = ViewModelProviders.of(this).get(Controller.class);
    }
}
</code>```

but I got an error at control = ViewModelProviders.of(this) <-- stating that it cannot resolve of(this), but based on the example here by Android Developer on Implementing ViewModel; a class that extends ViewModel should be able to be instantiated on Activity, am I right?

If what I am doing is wrong, how should I instantiate a ViewModel object for my Activity(s)? Do I have to create n number of Activity(s) with Fragment(s) since ViewModelProviders.of() only works with Fragment?

答:
You need to use the support library activity.

AppCompatActivity or FragmentActivity

Body:
I am trying to instantiate one ViewModel to use across all of my Activity(s).

public class LaunchActivity extends Activity {
    private Controller control;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_launch);
         control = ViewModelProviders.of(this).get(Controller.class);
    }
}

but I got an error at control = ViewModelProviders.of(this) <-- stating that it cannot resolve of(this), but based on the example here by Android Developer on Implementing ViewModel; a class that extends ViewModel should be able to be instantiated on Activity, am I right?

If what I am doing is wrong, how should I instantiate a ViewModel object for my Activity(s)? Do I have to create n number of Activity(s) with Fragment(s) since ViewModelProviders.of() only works with Fragment?


问:
Drupal 6: in hook_cron, how do I specify the path to a module file?
In my .module file, I have an basic implementation of hook_cron:

```<code>function foobar_cron()
{
    $file = fopen('my_file', 'a');
    // stuff
    fclose($file);
}
</code>```

The problem is that this method is called by (http://www.example.com/)cron.php, so the path my_file is incorrect. How do I specify the correct path for my_file which is located in the foobar module directory?

答:
```<code><?php
   // something like the following. Might need to tweak the pathing.
   $path = drupal_get_path('module', $module_name) . '/my_file'; // $module_name = foobar in your case
?>
</code>```

Body:
In my .module file, I have an basic implementation of hook_cron:

function foobar_cron()
{
    $file = fopen('my_file', 'a');
    // stuff
    fclose($file);
}

The problem is that this method is called by (http://www.example.com/)cron.php, so the path my_file is incorrect. How do I specify the correct path for my_file which is located in the foobar module directory?


问:
How to setStyleSheet for QLabel in a specific class in Qt
I have a testing sample like this:
In class B, which only has a QVector to store some QLabel like this:

```<code>class B : public QWidget
{
public:
    B(QWidget *parent = 0);

    QVector<QLabel*> mLbls;
};
</code>```

And in class A, I have the following code:

```<code>A::A(QWidget *parent)
    : QMainWindow(parent)
{
    QWidget *mWidget = new QWidget(this);
    QHBoxLayout *hLayout = new QHBoxLayout(mWidget);

    B testingB;
    testingB.mLbls.resize(5);
    for(int i = 0; i < 5; i++) {
        testingB.mLbls[i] = new QLabel(mWidget);
        testingB.mLbls[i]->setText(QString::number(i));
        hLayout->addWidget(testingB.mLbls[i]);
    }
    setStyleSheet("QLabel {background-color: red;}"); //I want to set the QLabel bg color to red

    mWidget->setLayout(hLayout);
    setCentralWidget(mWidget);
}
</code>```

So what I am trying to do is set all QLabel that ONLY in Class B to red color. But the problem is, if I use setStyleSheet("QLabel {background-color: red;}");, all the QLabel(even the QLabel in Class A) will be set to red background color.

I do not know how to set all the stylesheet only for CLass B object. And I know I could use this way to implement what I am trying to do:

```<code>for(int i = 0; i < 5; i++) {
    testingB.mLbls[i] = new QLabel(mWidget);
    testingB.mLbls[i]->setText(QString::number(i));
    testingB.mLbls[i]->setStyleSheet("QLabel {background-color: red;}"); //new added
    hLayout->addWidget(testingB.mLbls[i]);
}
</code>```

By using that way, I think that so troublesome to set stylesheet for them one by one individually, besides sometimes I may need to set some QLabel stylesheet differently and the rest of them just have the same stylesheet. If I have more objects and set each of them one by one, that may cost a lot of time.
So I assume there is a way to set stylesheet for some objects in a class once for all. Hope that I explain my question clearly. To solve that problem, what can I do?
 Thanks.

答:
Qt CSS syntax allows you to select children for the CSS rules (Qt doc), but it is based on the parentship of QObjects not in which class contains pointers to the QLabel.

This CSS will only apply to QLabel objects which are children or grand children of a YourContainerClassWidget object.

```<code>// C++
auto container = new YourContainerClassWidget;
auto label = QLabel(container); // The label is now a child of container

// CSS
YourContainerClassWidget QLabel { // Descendant selector
    background-color: red;
}

// You can also apply only to direct children with this syntax
YourContainerClassWidget > QLabel { // Child selector
    background-color: red;
}
</code>```

Body:
I have a testing sample like this:
In class B, which only has a QVector to store some QLabel like this:

class B : public QWidget
{
public:
    B(QWidget *parent = 0);

    QVector<QLabel*> mLbls;
};

And in class A, I have the following code:

A::A(QWidget *parent)
    : QMainWindow(parent)
{
    QWidget *mWidget = new QWidget(this);
    QHBoxLayout *hLayout = new QHBoxLayout(mWidget);

    B testingB;
    testingB.mLbls.resize(5);
    for(int i = 0; i < 5; i++) {
        testingB.mLbls[i] = new QLabel(mWidget);
        testingB.mLbls[i]->setText(QString::number(i));
        hLayout->addWidget(testingB.mLbls[i]);
    }
    setStyleSheet("QLabel {background-color: red;}"); //I want to set the QLabel bg color to red

    mWidget->setLayout(hLayout);
    setCentralWidget(mWidget);
}

So what I am trying to do is set all QLabel that ONLY in Class B to red color. But the problem is, if I use setStyleSheet("QLabel {background-color: red;}");, all the QLabel(even the QLabel in Class A) will be set to red background color.

I do not know how to set all the stylesheet only for CLass B object. And I know I could use this way to implement what I am trying to do:

for(int i = 0; i < 5; i++) {
    testingB.mLbls[i] = new QLabel(mWidget);
    testingB.mLbls[i]->setText(QString::number(i));
    testingB.mLbls[i]->setStyleSheet("QLabel {background-color: red;}"); //new added
    hLayout->addWidget(testingB.mLbls[i]);
}

By using that way, I think that so troublesome to set stylesheet for them one by one individually, besides sometimes I may need to set some QLabel stylesheet differently and the rest of them just have the same stylesheet. If I have more objects and set each of them one by one, that may cost a lot of time.
So I assume there is a way to set stylesheet for some objects in a class once for all. Hope that I explain my question clearly. To solve that problem, what can I do?
 Thanks.

Body:
Qt CSS syntax allows you to select children for the CSS rules (Qt doc), but it is based on the parentship of QObjects not in which class contains pointers to the QLabel.

This CSS will only apply to QLabel objects which are children or grand children of a YourContainerClassWidget object.

// C++
auto container = new YourContainerClassWidget;
auto label = QLabel(container); // The label is now a child of container

// CSS
YourContainerClassWidget QLabel { // Descendant selector
    background-color: red;
}

// You can also apply only to direct children with this syntax
YourContainerClassWidget > QLabel { // Child selector
    background-color: red;
}


问:
stale element references in loop after redirection to another page
i am trying to choose a certain element of similar objects on a website, in my e2e tests, and to click it then to change to another site, related to that element. The Problem is that the loop is still going on after the page is changed because the promise resolves asynchronous (i'm new to all this stuff)

Here the code:

```<code>    goToCartridge(name){
    let done = false;
    element(by.id('dashboard')).all(by.className('card z-depth-1')).then( elems => {
      for(let i = 0; i < elems.length ; i++ ){
        if(done) break;
          elems[i].element(by.tagName('h2')).getText().then( text => {
            if(name === text) {
              element(by.id('cartridge-' + i)).click();
              done = true;
            }
          return;
        });
      }
    });
  }
</code>```

How can i wait for the async part inside the loop before the next iteration starts? i searched alot for a solution, but couldnt find one yet.

答:
Maybe this works, I changed the for loops to array.map and filter. Not sure if Array.from is going to work on elms:</p>

```<code>goToCartridge(name){
  element(by.id('dashboard')).all(by.className('card z-depth-1'))
  .then(
    elems => {
      Promise.all(
        Array.from(elems).map(
          element =>
            element.element(by.tagName('h2')).getText()
            .then( text => [text,element] )
        )
      ).then(
        result=> {
          let [_,index] = result.map(
            ([text,element],index)=>[name === text,index]
          ).filter(
            ([hasText,index])=>hasText
          )[0];
          if(index !== undefined){
            return element(by.id('cartridge-' + index)).click();
          }
          else{
            return Promise.reject("could not find element");
          }
        }
      )
    }
  });
}
</code>```

Body:
i am trying to choose a certain element of similar objects on a website, in my e2e tests, and to click it then to change to another site, related to that element. The Problem is that the loop is still going on after the page is changed because the promise resolves asynchronous (i'm new to all this stuff)

Here the code:

    goToCartridge(name){
    let done = false;
    element(by.id('dashboard')).all(by.className('card z-depth-1')).then( elems => {
      for(let i = 0; i < elems.length ; i++ ){
        if(done) break;
          elems[i].element(by.tagName('h2')).getText().then( text => {
            if(name === text) {
              element(by.id('cartridge-' + i)).click();
              done = true;
            }
          return;
        });
      }
    });
  }

How can i wait for the async part inside the loop before the next iteration starts? i searched alot for a solution, but couldnt find one yet.

Body:
Maybe this works, I changed the for loops to array.map and filter. Not sure if Array.from is going to work on elms:

goToCartridge(name){
  element(by.id('dashboard')).all(by.className('card z-depth-1'))
  .then(
    elems => {
      Promise.all(
        Array.from(elems).map(
          element =>
            element.element(by.tagName('h2')).getText()
            .then( text => [text,element] )
        )
      ).then(
        result=> {
          let [_,index] = result.map(
            ([text,element],index)=>[name === text,index]
          ).filter(
            ([hasText,index])=>hasText
          )[0];
          if(index !== undefined){
            return element(by.id('cartridge-' + index)).click();
          }
          else{
            return Promise.reject("could not find element");
          }
        }
      )
    }
  });
}


问:
Macro to loop through all sheets in the workbook, test if a cell has a certain value. If yes, copy the sheet and exit the loop
```<code>Dim j As Double
For j = 1 To Worksheets.Count
        If Sheets(j).Range("E4").Value Like "Filters" Then
            ActiveSheet.Copy before:=Worksheets(1)
              ActiveSheet.Name = "data"
        End If
 Next j
</code>```

This is my code... when i run the code worksheet is created as "Data" but it is not exiting the loop... it is creating duplication of "data" worksheet and getting debug.. im missing very small thing  and i dont know what it is.. can anybody help.. thanks

答:
If your issue is to stop the loop once the sheet has been copied, change your code to this:</p>

```<code>Dim j As Double
For j = 1 To Worksheets.Count
        If Sheets(j).Range("E4").Value Like "Filters" Then
            ActiveSheet.Copy before:=Worksheets(1)
              ActiveSheet.Name = "data"
              Exit For 'Or could be Exit Sub?
        End If
 Next j
</code>```

Body:
Dim j As Double
For j = 1 To Worksheets.Count
        If Sheets(j).Range("E4").Value Like "Filters" Then
            ActiveSheet.Copy before:=Worksheets(1)
              ActiveSheet.Name = "data"
        End If
 Next j

This is my code... when i run the code worksheet is created as "Data" but it is not exiting the loop... it is creating duplication of "data" worksheet and getting debug.. im missing very small thing  and i dont know what it is.. can anybody help.. thanks

Body:
If your issue is to stop the loop once the sheet has been copied, change your code to this:

Dim j As Double
For j = 1 To Worksheets.Count
        If Sheets(j).Range("E4").Value Like "Filters" Then
            ActiveSheet.Copy before:=Worksheets(1)
              ActiveSheet.Name = "data"
              Exit For 'Or could be Exit Sub?
        End If
 Next j


问:
Utilizing AWS javascript SDK when connecting to API Gateway
I've enabled CORS on my Lambda function and have downloaded the SDK. I want to test utilizing the API Gateway to trigger the Lambda function with a local file. This is an html file that calls a javascript function when a button is pushed. It's running Apache locally to run this test webpage.

Currently, the code for this looks as follows:

```<code><button onclick="doFunction()">Download</button>
<script type="text/javascript" src="lib/axios/dist/axios.standalone.js"></script>
<script type="text/javascript" src="lib/CryptoJS/rollups/hmac-sha256.js"></script>
<script type="text/javascript" src="lib/CryptoJS/rollups/sha256.js"></script>
<script type="text/javascript" src="lib/CryptoJS/components/hmac.js"></script>
<script type="text/javascript" src="lib/CryptoJS/components/enc-base64.js"></script>
<script type="text/javascript" src="lib/url-template/url-template.js"></script>
<script type="text/javascript" src="lib/apiGatewayCore/sigV4Client.js"></script>
<script type="text/javascript" src="lib/apiGatewayCore/apiGatewayClient.js"></script>
<script type="text/javascript" src="lib/apiGatewayCore/simpleHttpClient.js"></script>
<script type="text/javascript" src="lib/apiGatewayCore/utils.js"></script>
<script type="text/javascript" src="apigClient.js"></script>
<script>
    function doFunction()
    {
        var apigClient = apigClientFactory.newClient();
        // etc...
</code>```

This snippet follows the tutorial documented here. However, all of these references fail, and as a result, the code can't recognize apigClientFactory. I've attempted adding the downloaded SDK files to the same folder that the file that's running the code is in. I'm really lost as to where I should be pointing and why it's not working. I can't tell if it's an issue with how I've set up CORS, if I need to have some S3 bucket properly referenced, or if I have the SDK files set up incorrectly in the directory. My question is how do I properly import these files from the AWS SDK.

Most of the questions regarding this part of accessing the API Gateway with Javascript use Nodejs or a different setup, which unfortunately is not apart of this process. This question just wants to utilize basic javascript.

答: I realized what I was doing wrong. The files various files were not located in the correct directory. Basically, the lib folder was not in the same spot as the html file and the apigClient.js. As soon as that happened, all was good!</p>

Body:
I've enabled CORS on my Lambda function and have downloaded the SDK. I want to test utilizing the API Gateway to trigger the Lambda function with a local file. This is an html file that calls a javascript function when a button is pushed. It's running Apache locally to run this test webpage.

Currently, the code for this looks as follows:

<button onclick="doFunction()">Download</button>


问:
React onClick and preventDefault() link refresh/redirect?
I'm rendering a link with react:

```<code>render: ->
  `<a className="upvotes" onClick={this.upvote}>upvote</a>`
</code>```

Then, above I have the upvote function:

```<code>upvote: ->
  // do stuff (ajax)
</code>```

Before link I had span in that place but I need to switch to link and here's the trouble - every time I click on .upvotes the page gets refreshed, what I've tried so far:

event.preventDefault() - not working.

```<code>upvote: (e) ->
  e.preventDefault()
  // do stuff (ajax)
</code>```

event.stopPropagation() - not working.

```<code>upvote: (e) ->
  e.stopPropagation()
  // do stuff (ajax)
</code>```

return false - not working.

```<code>upvote: (e) ->
  // do stuff (ajax)
  return false
</code>```

I've also tried all of the above using jQuery in my index.html, but nothing seems to work. What should I do here and what I'm doing wrong? I've checked event.type and it's click so I guess I should be able to avoid redirect somehow?

Excuse me, I'm a rookie when it comes to React.

Thank you!

答:
If you use checkbox

```<code><input
    type='checkbox'
    onChange={this.checkboxHandler}
/>
</code>```

stopPropagation and stopImmediatePropagation won't be working.

Because you must using onClick={this.checkboxHandler}

Body:
I'm rendering a link with react:

render: ->
  `<a className="upvotes" onClick={this.upvote}>upvote</a>`

Then, above I have the upvote function:

upvote: ->
  // do stuff (ajax)

Before link I had span in that place but I need to switch to link and here's the trouble - every time I click on .upvotes the page gets refreshed, what I've tried so far:

event.preventDefault() - not working.

upvote: (e) ->
  e.preventDefault()
  // do stuff (ajax)

event.stopPropagation() - not working.

upvote: (e) ->
  e.stopPropagation()
  // do stuff (ajax)

return false - not working.

upvote: (e) ->
  // do stuff (ajax)
  return false

I've also tried all of the above using jQuery in my index.html, but nothing seems to work. What should I do here and what I'm doing wrong? I've checked event.type and it's click so I guess I should be able to avoid redirect somehow?

Excuse me, I'm a rookie when it comes to React.

Thank you!

Body:
If you use checkbox

<input
    type='checkbox'
    onChange={this.checkboxHandler}
/>

stopPropagation and stopImmediatePropagation won't be working.

Because you must using onClick={this.checkboxHandler}


问:
what is the main differences between web service and wcf?
i know that web service can be host only in IIS but wcf can be host in IIS and both in win service too. but where is the actual main power lies in wcf for which developer choose wcf rather web service. please explain in detail. thanks</p>

答:
WCF offers:

unified programming model

new features

more protocols

support for the older ASMX/XML webservices

In .NET, use WCF unless you have very specific legacy requirements.


问:
Spirit X3 composed attributes
I am trying to compose spirit rules but I cannot figure out what the attribute of this new rule would be.

The following code is working as I would expect it.

```<code>#include <iostream>
#include <boost/spirit/home/x3.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>
#include <boost/fusion/tuple.hpp>
namespace ast{
    struct Record{
       int id;
       std::string name;
    };
    struct Document{
        Record rec;
        Record rec2;
        //std::vector<Record> rec;
        std::string name;
    };
    using boost::fusion::operator<<;
}
BOOST_FUSION_ADAPT_STRUCT(ast::Record,
    name, id
)
BOOST_FUSION_ADAPT_STRUCT(ast::Document,
    rec, rec2,
    //rec,
    name
)
namespace parser{
    namespace x3 = boost::spirit::x3;
    namespace ascii = boost::spirit::x3::ascii;
    using x3::lit;
    using x3::int_;
    using ascii::char_;

    const auto identifier = +char_("a-z");
    const x3::rule<class record, ast::Record> record = "record";
    const auto record_def = lit("record") >> identifier >> lit("{") >> int_ >> lit("}");
    const x3::rule<class document, ast::Document> document = "document";
    const auto document_def =
         record >> record
         //+record // This should generate a sequence
         >> identifier
         ;
    BOOST_SPIRIT_DEFINE(document, record);
}

namespace{
    constexpr char g_input[] = R"input(
                record foo{42}
                record bar{73}
                foobar
                )input";
}

int main(){
    using boost::spirit::x3::ascii::space;
    std::string str = g_input;
    ast::Document unit;
    bool r = phrase_parse(str.begin(), str.end(), parser::document, space, unit);
    std::cout << "Got: " << unit << "\n";
    return 0;
}
</code>```

But when I change the rule to parse multiple records(instead of exactly 2) I would expect it to have a std::vector<Record> as an attribute. But all I get is a long compiler error that does not help me very much.
Can someone point me to what I am doing wrong in order to compose the attributes correctly?

答:
I think the whole reason it didn't compile is because you tried to print the result... and std::vector<Record> doesn't know how to be streamed:

```<code>namespace ast {
    using boost::fusion::operator<<;
    static inline std::ostream& operator<<(std::ostream& os, std::vector<Record> const& rs) {
        os << "{ ";
        for (auto& r : rs) os << r << " ";
        return os << "}";
    }
}
</code>```

Some more notes:

adding lexemes where absolutely required (!)

simplifying (no need to BOOST_SPIRIT_DEFINE unless recursive rules/separate TUs)

dropping redundant lit

I arrived at

Live On Coliru

```<code>#include <iostream>
#include <boost/spirit/home/x3.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>

namespace ast {
    struct Record{
       int id;
       std::string name;
    };
    struct Document{
        std::vector<Record> rec;
        std::string name;
    };
}

BOOST_FUSION_ADAPT_STRUCT(ast::Record, name, id)
BOOST_FUSION_ADAPT_STRUCT(ast::Document, rec, name)

namespace ast {
    using boost::fusion::operator<<;
    static inline std::ostream& operator<<(std::ostream& os, std::vector<Record> const& rs) {
        os << "{ ";
        for (auto& r : rs) os << r << " ";
        return os << "}";
    }
}

namespace parser {
    namespace x3    = boost::spirit::x3;
    namespace ascii = x3::ascii;

    const auto identifier = x3::lexeme[+x3::char_("a-z")];
    const auto record     = x3::rule<class record, ast::Record> {"record"}
                          = x3::lexeme["record"] >> identifier >> "{" >> x3::int_ >> "}";
    const auto document   = x3::rule<class document, ast::Document> {"document"}
                          = +record
                          >> identifier
                          ;
}

int main(){
    std::string const str =  "record foo{42} record bar{73} foobar";
    auto f = str.begin(), l = str.end();

    ast::Document unit;
    if (phrase_parse(f, l, parser::document, parser::ascii::space, unit)) {
        std::cout << "Got: " << unit << "\n";
    } else {
        std::cout << "Parse failed\n";
    }

    if (f != l) {
        std::cout << "Remaining unparsed input: '" << std::string(f,l) << "'\n";
    }
}
</code>```

Prints

```<code>Got: ({ (foo 42) (bar 73) } foobar)
</code>```

Title: Spirit X3 composed attributes

Body:
I am trying to compose spirit rules but I cannot figure out what the attribute of this new rule would be.

The following code is working as I would expect it.

#include <iostream>
#include <boost/spirit/home/x3.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>
#include <boost/fusion/tuple.hpp>
namespace ast{
    struct Record{
       int id;
       std::string name;
    };
    struct Document{
        Record rec;
        Record rec2;
        //std::vector<Record> rec;
        std::string name;
    };
    using boost::fusion::operator<<;
}
BOOST_FUSION_ADAPT_STRUCT(ast::Record,
    name, id
)
BOOST_FUSION_ADAPT_STRUCT(ast::Document,
    rec, rec2,
    //rec,
    name
)
namespace parser{
    namespace x3 = boost::spirit::x3;
    namespace ascii = boost::spirit::x3::ascii;
    using x3::lit;
    using x3::int_;
    using ascii::char_;

    const auto identifier = +char_("a-z");
    const x3::rule<class record, ast::Record> record = "record";
    const auto record_def = lit("record") >> identifier >> lit("{") >> int_ >> lit("}");
    const x3::rule<class document, ast::Document> document = "document";
    const auto document_def =
         record >> record
         //+record // This should generate a sequence
         >> identifier
         ;
    BOOST_SPIRIT_DEFINE(document, record);
}

namespace{
    constexpr char g_input[] = R"input(
                record foo{42}
                record bar{73}
                foobar
                )input";
}

int main(){
    using boost::spirit::x3::ascii::space;
    std::string str = g_input;
    ast::Document unit;
    bool r = phrase_parse(str.begin(), str.end(), parser::document, space, unit);
    std::cout << "Got: " << unit << "\n";
    return 0;
}

But when I change the rule to parse multiple records(instead of exactly 2) I would expect it to have a std::vector<Record> as an attribute. But all I get is a long compiler error that does not help me very much.
Can someone point me to what I am doing wrong in order to compose the attributes correctly?

Body:
I think the whole reason it didn't compile is because you tried to print the result... and std::vector<Record> doesn't know how to be streamed:

namespace ast {
    using boost::fusion::operator<<;
    static inline std::ostream& operator<<(std::ostream& os, std::vector<Record> const& rs) {
        os << "{ ";
        for (auto& r : rs) os << r << " ";
        return os << "}";
    }
}

Some more notes:

adding lexemes where absolutely required (!)

simplifying (no need to BOOST_SPIRIT_DEFINE unless recursive rules/separate TUs)

dropping redundant lit

I arrived at

Live On Coliru

#include <iostream>
#include <boost/spirit/home/x3.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>

namespace ast {
    struct Record{
       int id;
       std::string name;
    };
    struct Document{
        std::vector<Record> rec;
        std::string name;
    };
}

BOOST_FUSION_ADAPT_STRUCT(ast::Record, name, id)
BOOST_FUSION_ADAPT_STRUCT(ast::Document, rec, name)

namespace ast {
    using boost::fusion::operator<<;
    static inline std::ostream& operator<<(std::ostream& os, std::vector<Record> const& rs) {
        os << "{ ";
        for (auto& r : rs) os << r << " ";
        return os << "}";
    }
}

namespace parser {
    namespace x3    = boost::spirit::x3;
    namespace ascii = x3::ascii;

    const auto identifier = x3::lexeme[+x3::char_("a-z")];
    const auto record     = x3::rule<class record, ast::Record> {"record"}
                          = x3::lexeme["record"] >> identifier >> "{" >> x3::int_ >> "}";
    const auto document   = x3::rule<class document, ast::Document> {"document"}
                          = +record
                          >> identifier
                          ;
}

int main(){
    std::string const str =  "record foo{42} record bar{73} foobar";
    auto f = str.begin(), l = str.end();

    ast::Document unit;
    if (phrase_parse(f, l, parser::document, parser::ascii::space, unit)) {
        std::cout << "Got: " << unit << "\n";
    } else {
        std::cout << "Parse failed\n";
    }

    if (f != l) {
        std::cout << "Remaining unparsed input: '" << std::string(f,l) << "'\n";
    }
}

Prints

Got: ({ (foo 42) (bar 73) } foobar)


问:
Install libs Pycharm
I try to install numpy in pycharm 2017.2. But when I choose numpy in Settings -> Project Interpreter, I'm getting error:

Make sure that you use the correct version of 'pip' installed for your Python interpreter located at '/usr/bin/python3.5'

Error: Python packaging tool 'pip' not found

What should I do to avoid it?

答:
ok you should not need to install pip (check here)

python 3.4+ ships with pip.

you should firstly make sure your python is on your PATH if you are on windows.

secondly, in Pycharm you should do: File > Settings > Project > Project Interpreter, in the dropdown select your python installation path and click apply and ok.

once all of this are set up correctly, you should go on to your command line, and type pip3 install --upgrade numpy.

Title: Install libs Pycharm


问:
PHP MySQL insert with $_REQUEST
I am trying to insert this $_REQUEST data into my MySQL database. The code is shown below:

```<code>foreach ($_REQUEST as $value)
{

 $sql = "INSERT INTO beer (b_beer) VALUES ('$value');";

 if(mysqli_query($connection, $sql))
  {
  echo "Records added successfully.";
  }

   else
   {
   echo "ERROR: Could not able to execute $sql. " . mysqli_error($connection);
   }
}
</code>```

The MySQL successfully inserts into my 'beer' table, but also creates 2 empty records. Is there a reason why this is happening?

答:
Give this a run.  You'd still be vulnerable to possible SQL Injections but at least you'll trim your values and only try to write those that actually contain something, plus with addslashes() you'll help ensure that any characters that would possibly break SQL are escaped.

```<code>foreach ($_REQUEST as $key => $value) {

    if(trim($key) == 'beer') {
        if($beerid = trim($value)) {
            $sql = sprintf('INSERT INTO beer (b_beer) VALUES ("%s")',addslashes($beerid));

            if(mysqli_query($connection, $sql)){
                echo "Records added successfully.";
            } else {
                printf("ERROR: Could not able to execute %s -- %s\n",$sql,mysqli_error($connection));
            }
        }
    }
}
</code>```

OR

Since you are only processing one request, and you know the name of the field as  'beer'  you can simply this way:

```<code>if(isset($_REQUEST['beer']) {

   if($beerid = trim($_REQUEST['beer'])) {
        $sql = sprintf('INSERT INTO beer (b_beer) VALUES ("%s")',addslashes($beerid));

        if(mysqli_query($connection, $sql)){
            echo "Records added successfully.";
        } else {
            printf("ERROR: Could not able to execute %s -- %s\n",$sql,mysqli_error($connection));
        }
    }
}
</code>```

Title: PHP MySQL insert with $_REQUEST

Body:
I am trying to insert this $_REQUEST data into my MySQL database. The code is shown below:

foreach ($_REQUEST as $value)
{

 $sql = "INSERT INTO beer (b_beer) VALUES ('$value');";

 if(mysqli_query($connection, $sql))
  {
  echo "Records added successfully.";
  }

   else
   {
   echo "ERROR: Could not able to execute $sql. " . mysqli_error($connection);
   }
}

The MySQL successfully inserts into my 'beer' table, but also creates 2 empty records. Is there a reason why this is happening?

Body:
Give this a run.  You'd still be vulnerable to possible SQL Injections but at least you'll trim your values and only try to write those that actually contain something, plus with addslashes() you'll help ensure that any characters that would possibly break SQL are escaped.

foreach ($_REQUEST as $key => $value) {

    if(trim($key) == 'beer') {
        if($beerid = trim($value)) {
            $sql = sprintf('INSERT INTO beer (b_beer) VALUES ("%s")',addslashes($beerid));

            if(mysqli_query($connection, $sql)){
                echo "Records added successfully.";
            } else {
                printf("ERROR: Could not able to execute %s -- %s\n",$sql,mysqli_error($connection));
            }
        }
    }
}

OR

Since you are only processing one request, and you know the name of the field as  'beer'  you can simply this way:

if(isset($_REQUEST['beer']) {

   if($beerid = trim($_REQUEST['beer'])) {
        $sql = sprintf('INSERT INTO beer (b_beer) VALUES ("%s")',addslashes($beerid));

        if(mysqli_query($connection, $sql)){
            echo "Records added successfully.";
        } else {
            printf("ERROR: Could not able to execute %s -- %s\n",$sql,mysqli_error($connection));
        }
    }
}


问:
Creating WooCommerce product variation adds an empty attribute value
When adding variations to a WooCommerce product it is adding in a blank attribute. Meaning that when I try to add my own attribute it gets appended to an existing array.

Example code I am running:

```<code>$product_variation = wc_get_product( $variation_id );
$product_variation->set_attributes(array('attribute_pa_varinfo' => 'blue'));
$product_variation->save();
</code>```

Then when I var_dump($product_variation); I get the following:

```<code>["attributes"]=>
array(2) {
  [0]=>
  string(0) ""
  ["pa_varinfo"]=>
  string(4) "5034"
}
</code>```

So when I view the product in WooCommerce admin all my variations are there but the attribute is stuck at "any option" for all of them.

The weird thing is when I then "update" the product from wp-admin all of the variations then get the correct attribute selected.

Has anyone encountered this before or got any ideas of what I can do?

As another example, if I run the following:

```<code>$product_variation = wc_get_product( $variation_id );
$product_variation->set_attributes( array ( 'simon' => 'confused' ) );
$product_variation->save();
var_dump($product_variation->get_attributes());
</code>```

This returns:

```<code>array(2) {
 [0]=> string(0) ""
 ["simon"]=> string(8) "confused"
}
</code>```

Where does the first item come from? I can't seem to clear it.

答:
So it turns out the problem was with the actual setting up of the attribute against the main parent product, I was passing through an unnamed array, by adding wc_attribute_taxonomy_name('varinfo') => (line 2 below) this correctly saves the data and removes the blank array I had.

```<code>      $product_attributes = array(
      wc_attribute_taxonomy_name('varinfo') =>
      array (
        'name'         => wc_attribute_taxonomy_name( 'varinfo' ), // set attribute name
        'value'        => '', // set attribute values
        'position'     => 1,
        'is_visible'   => 1,
        'is_variation' => 1,
        'is_taxonomy'  => 1
      )
    );

    update_post_meta($post_id, '_product_attributes', $product_attributes);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When adding variations to a WooCommerce product it is adding in a blank attribute. Meaning that when I try to add my own attribute it gets appended to an existing array.

Example code I am running:

$product_variation = wc_get_product( $variation_id );
$product_variation->set_attributes(array('attribute_pa_varinfo' => 'blue'));
$product_variation->save();

Then when I var_dump($product_variation); I get the following:

["attributes"]=>
array(2) {
  [0]=>
  string(0) ""
  ["pa_varinfo"]=>
  string(4) "5034"
}

So when I view the product in WooCommerce admin all my variations are there but the attribute is stuck at "any option" for all of them.

The weird thing is when I then "update" the product from wp-admin all of the variations then get the correct attribute selected.

Has anyone encountered this before or got any ideas of what I can do?

As another example, if I run the following:

$product_variation = wc_get_product( $variation_id );
$product_variation->set_attributes( array ( 'simon' => 'confused' ) );
$product_variation->save();
var_dump($product_variation->get_attributes());

This returns:

array(2) {
 [0]=> string(0) ""
 ["simon"]=> string(8) "confused"
}

Where does the first item come from? I can't seem to clear it.

Body:
So it turns out the problem was with the actual setting up of the attribute against the main parent product, I was passing through an unnamed array, by adding wc_attribute_taxonomy_name('varinfo') => (line 2 below) this correctly saves the data and removes the blank array I had.

      $product_attributes = array(
      wc_attribute_taxonomy_name('varinfo') =>
      array (
        'name'         => wc_attribute_taxonomy_name( 'varinfo' ), // set attribute name
        'value'        => '', // set attribute values
        'position'     => 1,
        'is_visible'   => 1,
        'is_variation' => 1,
        'is_taxonomy'  => 1
      )
    );

    update_post_meta($post_id, '_product_attributes', $product_attributes);


问:
hive query with multiple where IN clause with AND type logical connection
I have a web application with hive db at back end from which users selects 4 different type of values and related data is displayed on UI.

Example the fields may be:

Project ID

Sub-portfolio

Project Status

Project Finance Status

User can select different values for the fields mentioned ( single or multiple) and request for data.

I have a single hive query with multiple where IN clause and combined with AND logical operator to generate the data.

All is good untill user is selecting atleast one value for each field. But if the user selects filters for 3 fields and leaves on blank then '' is passed to IN clause in where condition and no data is displayed. As none of the rows match the condition.

Where as if a field is not selected I have to pass something in IN clause to get all the data for that field or to remove IN clause for that field.

To check everytime if a value is selected before creating a query will involve a lot of cases.

If anyone can suggest a single query with multiple where IN, and pass some parameter to get all the rows for a fields where no value is selected.

Note: I am using hive JDBC queries.

答:
You can handle this issue with constructs like:

```<code>where ($subporfolio is null or subportfolio = $subportfolio) and
      ($status is null or status = $status) and
      . . .
</code>```

Of course the in null might be = '' depending on how you are passing the values.

Body:
You can handle this issue with constructs like:

where ($subporfolio is null or subportfolio = $subportfolio) and
      ($status is null or status = $status) and
      . . .

Of course the in null might be = '' depending on how you are passing the values.


问:
Why my rabbitMQ client can't connect?
I'm trying to create RabbitMQ connection with server using TLSv1.2, but I have java.net.SocketException: Connection reset or javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure (It looks like this exceptions are changing randomly).

It worked when I had TLSv1.0, but when server changed protocol it stopped working (even if I'm using the same cipher, port etc).

Is it possible to get this exceptions if vhost/other connection parameter is incorrect?

Before connection, I'm setting:

```<code>System.setProperty("https.protocols", "TLSv1.2");
</code>```

Here is my configuration:

```<code>public ConnectionFactory get() throws IOException, KeyStoreException, NoSuchAlgorithmException,
        CertificateException, UnrecoverableKeyException, KeyManagementException, URISyntaxException {
    final ConnectionFactory cf = new ConnectionFactory();

    final SSLContext sslContext = getSSLContext();

    cf.useSslProtocol(sslContext);

    final ConnectionSettings connectionSettings = getConnectionSettings(sslContext.getSocketFactory());

    cf.setHost(connectionSettings.getHost());
    cf.setPort(connectionSettings.getPort());
    cf.setVirtualHost(connectionSettings.getVirtualHost());
    //using cf.setUsername and cs.setPassword doesn't work

    cf.setSaslConfig(DefaultSaslConfig.EXTERNAL);
    cf.setAutomaticRecoveryEnabled(false);
    cf.setTopologyRecoveryEnabled(false);

    return cf;
}
</code>```

And getSSLContext() method:

```<code>private SSLContext getSSLContext(){
    //SECURE_PROTOCOLE = "TLSv1.2"
    final SSLContext sslContext = SSLContext.getInstance(SECURE_PROTOCOLE);

    KeyStore keystore = KeyStore.getInstance("Windows-MY");
    keystore.load(null, null);

    final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keystore, null);

    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            // Not implemented
        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            // Not implemented
        }
    } };

    sslContext.init(keyManagerWrapper(kmf),
            trustAllCerts, new SecureRandom());
    return sslContext;
    }
</code>```

Exception occurs when I'm trying to create new connection:

```<code>this.connectionFactory = new ConnectionFactoryProvider().get();
this.connection = this.connectionFactory.newConnection();
</code>```

答:
The RabbitMQ team monitors this mailing list and only sometimes answers questions on StackOverflow.

Diagnosing TLS errors such as these with limited information is very difficult. You do not provide the following information which would be helpful:

RabbitMQ version

Erlang version

Operating system platform and version for both RabbitMQ server and client

Java version and Java client version

This line of code hints that you are running your client application on Windows:

```<code>KeyStore.getInstance("Windows-MY")
</code>```

If you can provide the above information as well as a complete set of TLS/SSL certificates to reproduce the problem that would be ideal.

The RabbitMQ documentation also includes a comprehensive TLS/SSL troubleshooting guide.

Title: Why my rabbitMQ client can't connect?

Body:
I'm trying to create RabbitMQ connection with server using TLSv1.2, but I have java.net.SocketException: Connection reset or javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure (It looks like this exceptions are changing randomly).

It worked when I had TLSv1.0, but when server changed protocol it stopped working (even if I'm using the same cipher, port etc).

Is it possible to get this exceptions if vhost/other connection parameter is incorrect?

Before connection, I'm setting:

System.setProperty("https.protocols", "TLSv1.2");

Here is my configuration:

public ConnectionFactory get() throws IOException, KeyStoreException, NoSuchAlgorithmException,
        CertificateException, UnrecoverableKeyException, KeyManagementException, URISyntaxException {
    final ConnectionFactory cf = new ConnectionFactory();

    final SSLContext sslContext = getSSLContext();

    cf.useSslProtocol(sslContext);

    final ConnectionSettings connectionSettings = getConnectionSettings(sslContext.getSocketFactory());

    cf.setHost(connectionSettings.getHost());
    cf.setPort(connectionSettings.getPort());
    cf.setVirtualHost(connectionSettings.getVirtualHost());
    //using cf.setUsername and cs.setPassword doesn't work

    cf.setSaslConfig(DefaultSaslConfig.EXTERNAL);
    cf.setAutomaticRecoveryEnabled(false);
    cf.setTopologyRecoveryEnabled(false);

    return cf;
}

And getSSLContext() method:

private SSLContext getSSLContext(){
    //SECURE_PROTOCOLE = "TLSv1.2"
    final SSLContext sslContext = SSLContext.getInstance(SECURE_PROTOCOLE);

    KeyStore keystore = KeyStore.getInstance("Windows-MY");
    keystore.load(null, null);

    final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keystore, null);

    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            // Not implemented
        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            // Not implemented
        }
    } };

    sslContext.init(keyManagerWrapper(kmf),
            trustAllCerts, new SecureRandom());
    return sslContext;
    }

Exception occurs when I'm trying to create new connection:

this.connectionFactory = new ConnectionFactoryProvider().get();
this.connection = this.connectionFactory.newConnection();

Body:
The RabbitMQ team monitors this mailing list and only sometimes answers questions on StackOverflow.

Diagnosing TLS errors such as these with limited information is very difficult. You do not provide the following information which would be helpful:

RabbitMQ version

Erlang version

Operating system platform and version for both RabbitMQ server and client

Java version and Java client version

This line of code hints that you are running your client application on Windows:

KeyStore.getInstance("Windows-MY")

If you can provide the above information as well as a complete set of TLS/SSL certificates to reproduce the problem that would be ideal.

The RabbitMQ documentation also includes a comprehensive TLS/SSL troubleshooting guide.


问:
Kafka connect confluent elasticsearch sink (no class found error)
I am very new to Kafka connect. I want to push my messages from Kafka topic to elasticsearch. After following the available documentation.. I downloaded and compiled elastic search sink from release tar.zip (https://github.com/confluentinc/kafka-connect-elasticsearch/releases)

I added the elastic search properties file and included the above jar in classpath. When I run kafka connect in standalone mode I get this error

./usr/bin/connect-standalone etc/schema-registry/connect-avro-standalone.properties etc/kafka-connect-elasticsearch/quickstart-elasticsearch.properties

```<code>[2016-11-13 00:05:38,768] ERROR Task elasticsearch-sink-0 threw an uncaught and unrecoverable exception (org.apache.kafka.connect.runtime.WorkerTask:142) java.lang.NoClassDefFoundError:io/searchbox/client/JestClientFactory
at io.confluent.connect.elasticsearch.ElasticsearchSinkTask.start(ElasticsearchSinkTask.java:81)
at io.confluent.connect.elasticsearch.ElasticsearchSinkTask.start(ElasticsearchSinkTask.java:52)
at org.apache.kafka.connect.runtime.WorkerSinkTask.initializeAndStart(WorkerSinkTask.java:207)
at org.apache.kafka.connect.runtime.WorkerSinkTask.execute(WorkerSinkTask.java:139)
at org.apache.kafka.connect.runtime.WorkerTask.doRun(WorkerTask.java:140)
at o
</code>```

NoClassDefFoundError:io/searchbox/client/JestClientFactory

I checkedthe pom.xml and it has Jest client dependency defined correctly. Am I missing anything?

Any pointers would be really appreciated.

Thanks,
Rajesh

答:
You can also build fat jar. Add descriptorRefs

<build>
  <plugins>
  ....
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-assembly-plugin</artifactId>
      <configuration>
      ....
        <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
      </configuration>
      ....
    </plugin>
  </plugins>
  ....
</build>```

to pom, build and copy jar with dependencies to libs directory of Kafka.

Body:
I am very new to Kafka connect. I want to push my messages from Kafka topic to elasticsearch. After following the available documentation.. I downloaded and compiled elastic search sink from release tar.zip (https://github.com/confluentinc/kafka-connect-elasticsearch/releases)

I added the elastic search properties file and included the above jar in classpath. When I run kafka connect in standalone mode I get this error

./usr/bin/connect-standalone etc/schema-registry/connect-avro-standalone.properties etc/kafka-connect-elasticsearch/quickstart-elasticsearch.properties

[2016-11-13 00:05:38,768] ERROR Task elasticsearch-sink-0 threw an uncaught and unrecoverable exception (org.apache.kafka.connect.runtime.WorkerTask:142) java.lang.NoClassDefFoundError:io/searchbox/client/JestClientFactory
at io.confluent.connect.elasticsearch.ElasticsearchSinkTask.start(ElasticsearchSinkTask.java:81)
at io.confluent.connect.elasticsearch.ElasticsearchSinkTask.start(ElasticsearchSinkTask.java:52)
at org.apache.kafka.connect.runtime.WorkerSinkTask.initializeAndStart(WorkerSinkTask.java:207)
at org.apache.kafka.connect.runtime.WorkerSinkTask.execute(WorkerSinkTask.java:139)
at org.apache.kafka.connect.runtime.WorkerTask.doRun(WorkerTask.java:140)
at o

NoClassDefFoundError:io/searchbox/client/JestClientFactory

I checkedthe pom.xml and it has Jest client dependency defined correctly. Am I missing anything?

Any pointers would be really appreciated.

Thanks,
Rajesh

Body:
You can also build fat jar. Add descriptorRefs

<build>
  <plugins>
  ....
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-assembly-plugin</artifactId>
      <configuration>
      ....
        <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
      </configuration>
      ....
    </plugin>
  </plugins>
  ....
</build>

to pom, build and copy jar with dependencies to libs directory of Kafka.


问:
setUserVisibleHint called before onCreateView in Fragment
I am working on ViewPager and using Fragment there I found

setUserVisibleHint() called before onCreateView() in Fragment

I am using Fragment from support library android.support.v4.app.Fragment

Is this is a problem with Library ?

How can I get rid of it ?

EDIT

I Override setUserVisibleHint() and not calling super to get rid of it.

```<code>@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    //FIXED: setUserVisibleHint() called before onCreateView() in Fragment causes NullPointerException
    //super.setUserVisibleHint(isVisibleToUser);
}
</code>```

答:
This is the best solution i found.</p>

```<code>    @Override
    public void onCreateView() {
        super.onStart();
        if (getUserVisibilityHint()){
            //do stuff
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isResumed() && isVisibleToUser) {
            //do stuff
        }
    }
</code>```

Body:
I am working on ViewPager and using Fragment there I found

setUserVisibleHint() called before onCreateView() in Fragment

I am using Fragment from support library android.support.v4.app.Fragment

Is this is a problem with Library ?

How can I get rid of it ?

EDIT

I Override setUserVisibleHint() and not calling super to get rid of it.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    //FIXED: setUserVisibleHint() called before onCreateView() in Fragment causes NullPointerException
    //super.setUserVisibleHint(isVisibleToUser);
}

Body:
This is the best solution i found.

    @Override
    public void onCreateView() {
        super.onStart();
        if (getUserVisibilityHint()){
            //do stuff
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isResumed() && isVisibleToUser) {
            //do stuff
        }
    }


问:
NodeInvocationException: localStorage is not defined
I m using the asp.net core 2.0 AngularJS template and When I trying to use localStorage in AppComponent it’s says

NodeInvocationException: localStorage is not defined
ReferenceError: localStorage is not defined.

I waste much time to fixed this, unfortunately angular2-universal even not working with the asp.net core 2.0 to check the condition isBrowser. Event the localStorage does not working with HomeComponent also.

How can I fixed this. Please help me to fixed this. Thank you.

```<code>export class AppComponent {

constructor() {

    localStorage.setItem('count', 'not set');
    console.log('const');
}
</code>```

}

答:
It seems someone posted a similar question on Github (https://github.com/MarkPieszak/aspnetcore-angular2-universal/issues/238).

I think there is an Angular error somewhere but it's getting reported as something else because the VS Angular template uses Webpack to build the Angular app.  I think the Webpack app is failing to build and the underlying issue is not reporting by ASP.Net Core.

Body:
I m using the asp.net core 2.0 AngularJS template and When I trying to use localStorage in AppComponent it’s says

NodeInvocationException: localStorage is not defined
ReferenceError: localStorage is not defined.

I waste much time to fixed this, unfortunately angular2-universal even not working with the asp.net core 2.0 to check the condition isBrowser. Event the localStorage does not working with HomeComponent also.

How can I fixed this. Please help me to fixed this. Thank you.

export class AppComponent {

constructor() {

    localStorage.setItem('count', 'not set');
    console.log('const');
}

}


问:
loop flv inside flash
I'm new in Flash and I need to insert a flv into a new flash project and I want that video to play non-stop.

thanks

this is interesting, but if i use a smaller video, then the video is looping...

答: here's an example with a looped flv, you need almost only NetConnection, NetStream and Video there

Title: loop flv inside flash


问:
Configure JOGL with maven
I'm trying to configure JOGL with maven following the guide found here:
http://jogamp.org/wiki/index.php/Maven

As far as I understand should be enough to include these dependencies:

```<code><dependencies>
    <dependency>
      <groupId>org.jogamp.gluegen</groupId>
      <artifactId>gluegen-rt-main</artifactId>
      <version>2.3.1</version>
    </dependency>
    <dependency>
      <groupId>org.jogamp.jogl</groupId>
      <artifactId>jogl-all-main</artifactId>
      <version>2.3.1</version>
    </dependency>
  </dependencies>
</code>```

Because they say:

```<code>"So, when you add a dependency on jogl-all-main in your own project, the native jar files of jogl-all are brought in as transitive dependencies and everything works as expected."
</code>```

I have create a Maven project including those dependencies and now the project looks like this:

I wrote a simple HelloWorld class to test it:

```<code>import com.jogamp.opengl.GLCapabilities;

    public class HelloWorld {
        public static void main (String args[]) {
            try {

                System.loadLibrary("jogl");
                System.out.println("Hello World! (The native libraries are installed.)");
                GLCapabilities caps = new GLCapabilities(null);
                System.out.println("Hello JOGL! (The jar appears to be available.)");
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
</code>```

But running it I get this error:

```<code>Exception in thread "main" java.lang.UnsatisfiedLinkError: no jogl in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1886)
    at java.lang.Runtime.loadLibrary0(Runtime.java:849)
    at java.lang.System.loadLibrary(System.java:1088)
    at jogl.HelloWorld.main(HelloWorld.java:12)
</code>```

So it seems the native dll (I'm on windows) are not found.

What is wrong here?
Is the tutorial wrong, or did I miss something?

This is the pom.xml I'm using:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>jogl</groupId>
    <artifactId>jogl</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.jogamp.gluegen</groupId>
            <artifactId>gluegen-rt-main</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.jogamp.jogl</groupId>
            <artifactId>jogl-all-main</artifactId>
            <version>2.3.1</version>
        </dependency>
    </dependencies>
</project>
</code>```

答:
I found the problem:
I was following the new procedure but using the old code to load the libraries.
Indeed with the new libraries you don't need to use this line anymore:

```<code> System.loadLibrary("jogl");
</code>```

I have test it with this Line class and it works...

```<code>import javax.swing.JFrame;

import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.GLCapabilities;
import com.jogamp.opengl.GLEventListener;
import com.jogamp.opengl.GLProfile;
import com.jogamp.opengl.awt.GLCanvas;

public class Line implements GLEventListener{
   @Override
   public void display(GLAutoDrawable drawable) {
      final com.jogamp.opengl.GL2 gl = drawable.getGL().getGL2();
      gl.glBegin (GL2.GL_LINES);//static field
      gl.glVertex3f(0.50f,-0.50f,0);
      gl.glVertex3f(-0.50f,0.50f,0);
      gl.glEnd();
   }
   @Override
   public void dispose(GLAutoDrawable arg0) {
      //method body
   }

   @Override
   public void init(GLAutoDrawable arg0) {
      // method body
   }
   @Override
   public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4) {
      // method body
   }
   public static void main(String[] args) {
      //getting the capabilities object of GL2 profile
      final GLProfile profile = GLProfile.get(GLProfile.GL2);
      GLCapabilities capabilities = new GLCapabilities(profile);
      // The canvas
      final GLCanvas glcanvas = new GLCanvas(capabilities);
      Line l = new Line();
      glcanvas.addGLEventListener(l);
      glcanvas.setSize(400, 400);
      //creating frame
      final JFrame frame = new JFrame ("straight Line");
      //adding canvas to frame
      frame.getContentPane().add(glcanvas);
      frame.setSize(frame.getContentPane().getPreferredSize());
      frame.setVisible(true);
   }//end of main
}//end of classimport javax.media.opengl.GL2;
</code>```

Title: Configure JOGL with maven

Body:
I'm trying to configure JOGL with maven following the guide found here:
http://jogamp.org/wiki/index.php/Maven

As far as I understand should be enough to include these dependencies:

<dependencies>
    <dependency>
      <groupId>org.jogamp.gluegen</groupId>
      <artifactId>gluegen-rt-main</artifactId>
      <version>2.3.1</version>
    </dependency>
    <dependency>
      <groupId>org.jogamp.jogl</groupId>
      <artifactId>jogl-all-main</artifactId>
      <version>2.3.1</version>
    </dependency>
  </dependencies>

Because they say:

"So, when you add a dependency on jogl-all-main in your own project, the native jar files of jogl-all are brought in as transitive dependencies and everything works as expected."

I have create a Maven project including those dependencies and now the project looks like this:

I wrote a simple HelloWorld class to test it:

import com.jogamp.opengl.GLCapabilities;

    public class HelloWorld {
        public static void main (String args[]) {
            try {

                System.loadLibrary("jogl");
                System.out.println("Hello World! (The native libraries are installed.)");
                GLCapabilities caps = new GLCapabilities(null);
                System.out.println("Hello JOGL! (The jar appears to be available.)");
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }

But running it I get this error:

Exception in thread "main" java.lang.UnsatisfiedLinkError: no jogl in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1886)
    at java.lang.Runtime.loadLibrary0(Runtime.java:849)
    at java.lang.System.loadLibrary(System.java:1088)
    at jogl.HelloWorld.main(HelloWorld.java:12)

So it seems the native dll (I'm on windows) are not found.

What is wrong here?
Is the tutorial wrong, or did I miss something?

This is the pom.xml I'm using:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>jogl</groupId>
    <artifactId>jogl</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.jogamp.gluegen</groupId>
            <artifactId>gluegen-rt-main</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.jogamp.jogl</groupId>
            <artifactId>jogl-all-main</artifactId>
            <version>2.3.1</version>
        </dependency>
    </dependencies>
</project>

Body:
I found the problem:
I was following the new procedure but using the old code to load the libraries.
Indeed with the new libraries you don't need to use this line anymore:

 System.loadLibrary("jogl");

I have test it with this Line class and it works...

import javax.swing.JFrame;

import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.GLCapabilities;
import com.jogamp.opengl.GLEventListener;
import com.jogamp.opengl.GLProfile;
import com.jogamp.opengl.awt.GLCanvas;

public class Line implements GLEventListener{
   @Override
   public void display(GLAutoDrawable drawable) {
      final com.jogamp.opengl.GL2 gl = drawable.getGL().getGL2();
      gl.glBegin (GL2.GL_LINES);//static field
      gl.glVertex3f(0.50f,-0.50f,0);
      gl.glVertex3f(-0.50f,0.50f,0);
      gl.glEnd();
   }
   @Override
   public void dispose(GLAutoDrawable arg0) {
      //method body
   }

   @Override
   public void init(GLAutoDrawable arg0) {
      // method body
   }
   @Override
   public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4) {
      // method body
   }
   public static void main(String[] args) {
      //getting the capabilities object of GL2 profile
      final GLProfile profile = GLProfile.get(GLProfile.GL2);
      GLCapabilities capabilities = new GLCapabilities(profile);
      // The canvas
      final GLCanvas glcanvas = new GLCanvas(capabilities);
      Line l = new Line();
      glcanvas.addGLEventListener(l);
      glcanvas.setSize(400, 400);
      //creating frame
      final JFrame frame = new JFrame ("straight Line");
      //adding canvas to frame
      frame.getContentPane().add(glcanvas);
      frame.setSize(frame.getContentPane().getPreferredSize());
      frame.setVisible(true);
   }//end of main
}//end of classimport javax.media.opengl.GL2;


问:
Google Apps Script - Setting revision history
Has anyone worked with versioning on Google Sheets or Docs? I want a specific version of Google Sheets to be loaded when I or another user opens the sheet, this Id will be listed using the script below, but, I cannot find a way to set this as the version to load on opening the sheet. The opening of the sheet will be the trigger for this script to load.

See my script below

While I have reviewed https://developers.google.com/drive/v2/reference/revisions

I am unsure how to get it to set a specific version of the sheet on opening the sheet. I have attached my sample that is giving me an error: Invalid number of arguments provided. Expected 3-4 only (line 21, file "Code")

The methods available are:
delete
get
list
patch
update
There is no option to set a revision, so I am playing with the patch and update methods with little success. Any ideas?

Here's what I have so far:

```<code>function setRevisions() {
  listRevisions("1rMy631GhjrfaSlcRhUoICD4dYxNTBVJMwCzteGwl2wo")
}

function listRevisions(fileId) {
  var revisions = Drive.Revisions.list(fileId);
  if (revisions.items && revisions.items.length > 0) {
    for (var i = 0; i < revisions.items.length; i++) {
      var revision = revisions.items[i];
      Logger.log(revision.id);
    }
  } else {
    Logger.log('No revisions found.');
  }
  if(revision.id = '18') {
  Drive.Revisions.patch(revision.id);
} else {
  Logger.log("18 is not available");
  }

}
</code>```

Thanks in advance

答:
First obtain the revision Ids using Drive.Revisions.list(fileId). After obtaining the differevent revision Ids, use the regular Revision methods like Drive.Revisions.get and  Drive.Revisions.update through Advanced Drive Service.

A demo sample can be found in this post:

```<code>function listRevisions(fileId) {
  var fileId = '1yck2UQDJztdqD3Ji8UT3KcwTKiA0bgLd2-4xqwbU824';
  var revisions = Drive.Revisions.list(fileId);

  if (revisions.items && revisions.items.length > 0) {
    for (var i = 0; i < revisions.items.length; i++) {
      var revision = revisions.items[i];
      var date = new Date(revision.modifiedDate);
      Logger.log(revision.id);
    }
  } else {
   Logger.log('No revisions found.');
  }
}

function alterRevision(){
  var fileId = '1yck2UQDJztdqD3Ji8UT3KcwTKiA0bgLd2-4xqwbU824';
  var change = Drive.Revisions.get(fileId, 1306);
  var update = Drive.Revisions.update(change, fileId, 1306);
  Logger.log(update.id + update.modifiedDate);
}
</code>```

Body:
Has anyone worked with versioning on Google Sheets or Docs? I want a specific version of Google Sheets to be loaded when I or another user opens the sheet, this Id will be listed using the script below, but, I cannot find a way to set this as the version to load on opening the sheet. The opening of the sheet will be the trigger for this script to load.

See my script below

While I have reviewed https://developers.google.com/drive/v2/reference/revisions

I am unsure how to get it to set a specific version of the sheet on opening the sheet. I have attached my sample that is giving me an error: Invalid number of arguments provided. Expected 3-4 only (line 21, file "Code")

The methods available are:
delete
get
list
patch
update
There is no option to set a revision, so I am playing with the patch and update methods with little success. Any ideas?

Here's what I have so far:

function setRevisions() {
  listRevisions("1rMy631GhjrfaSlcRhUoICD4dYxNTBVJMwCzteGwl2wo")
}

function listRevisions(fileId) {
  var revisions = Drive.Revisions.list(fileId);
  if (revisions.items && revisions.items.length > 0) {
    for (var i = 0; i < revisions.items.length; i++) {
      var revision = revisions.items[i];
      Logger.log(revision.id);
    }
  } else {
    Logger.log('No revisions found.');
  }
  if(revision.id = '18') {
  Drive.Revisions.patch(revision.id);
} else {
  Logger.log("18 is not available");
  }

}

Thanks in advance

Body:
First obtain the revision Ids using Drive.Revisions.list(fileId). After obtaining the differevent revision Ids, use the regular Revision methods like Drive.Revisions.get and  Drive.Revisions.update through Advanced Drive Service.

A demo sample can be found in this post:

function listRevisions(fileId) {
  var fileId = '1yck2UQDJztdqD3Ji8UT3KcwTKiA0bgLd2-4xqwbU824';
  var revisions = Drive.Revisions.list(fileId);

  if (revisions.items && revisions.items.length > 0) {
    for (var i = 0; i < revisions.items.length; i++) {
      var revision = revisions.items[i];
      var date = new Date(revision.modifiedDate);
      Logger.log(revision.id);
    }
  } else {
   Logger.log('No revisions found.');
  }
}

function alterRevision(){
  var fileId = '1yck2UQDJztdqD3Ji8UT3KcwTKiA0bgLd2-4xqwbU824';
  var change = Drive.Revisions.get(fileId, 1306);
  var update = Drive.Revisions.update(change, fileId, 1306);
  Logger.log(update.id + update.modifiedDate);
}


问:
Integrate LLVM Clang 4.x.x / 5.x.x / 6.x.x into Visual Studio 2017
The official LLVM 4.0 build for Windows integrates with Visual Studio up to Visual Studio 2015. Unfortunately it still doesn't support Visual Studio 2017.

When you try to set the Platform Toolset of a project to LLVM-vs2014, it pops up an error.

Do you know any way to make it work?

Update

In 2018, LLVM 6.0 officially still doesn't support integration with Visual Studio 2017 (version 15.X.X), only with the Visual Studio 2015 (version 14.X.X) toolset.

答: LLVM/Clang now has an updated patch that allows you to use it with VS2017.  But they still don't directly support VS2017.  I asked on the LLVM developer mailing list for them to update their support for VS2017, so hopefully they'll do it.  If they listen to what I said.  </p>


问:
What's the issue with this code?
This is my part of the code:

```<code>import functions
def assign_tasks(operators, requests, current_time):
    sort_requests(requests)
    print(requests)
</code>```

The error is:

```<code>NameError: name 'sort_requests' is not defined
</code>```

The function module has the following functions:

```<code>def sort_requests(requests):
   requests.sort(key=operator.itemgetter(3),reverse=True)
   return requests
def sort_operators_hours(operators):
   operators.sort(key=operator.itemgetter(4))
   return operators
</code>```

答: add from functions import sort_requests or replace sort_requests(requests) by functions.sort_requests(requests)

Title: What's the issue with this code?

Body:
This is my part of the code:

import functions
def assign_tasks(operators, requests, current_time):
    sort_requests(requests)
    print(requests)

The error is:

NameError: name 'sort_requests' is not defined

The function module has the following functions:

def sort_requests(requests):
   requests.sort(key=operator.itemgetter(3),reverse=True)
   return requests
def sort_operators_hours(operators):
   operators.sort(key=operator.itemgetter(4))
   return operators


问:
Show div's based on a randomly shuffled array using javascript/jquery
Essentially I'm trying to write a Javascript/Jquery script which will show/hide a number of div's one at a time in an order determined by a randomly shuffled series of numbers.

I've managed to get the scripts to shuffle the numbers and cycle through the divs working but I'm not sure how to combine the two.

The script so far looks like this

```<code>$(document).ready(function() {

    function shuffle(arra1) {
        var ctr = arra1.length, temp, index;

        // While there are elements in the array
        while (ctr > 0) {
            // Pick a random index
            index = Math.floor(Math.random() * ctr);
            // Decrease ctr by 1
            ctr--;
            // And swap the last element with it
            temp = arra1[ctr];
            arra1[ctr] = arra1[index];
            arra1[index] = temp;
        }

        return arra1;
    }

    var myArray = [0, 1, 2, 3, 4, 5];
    console.log(shuffle(myArray));

    var divs = $('div[id^="random"]').hide(),
        i = 0;

    (function cycle() {
        divs.eq(i).fadeIn(400)
                  .delay(1000)
                  .fadeOut(400, cycle);

        i = ++i % divs.length;
    })();
});
</code>```

The div's that I'm trying to cycle through in the HTML look Like this

```<code><div id="random-divs">
    <div id="random0">Div 0</div>
    <div id="random1">Div 1</div>
    <div id="random2">Div 2</div>
    <div id="random3">Div 3</div>
    <div id="random4">Div 4</div>
    <div id="random5">Div 5</div>
</div>
</code>```

If anyone could point me in the right direction I'd greatly appreciate it.

答: Try to update jQuery selector "div[id^="random]" because it also affects the container div with the id "random-divs". I think You dont want to hide container div but just its childrens.</p>

Body:
Essentially I'm trying to write a Javascript/Jquery script which will show/hide a number of div's one at a time in an order determined by a randomly shuffled series of numbers.

I've managed to get the scripts to shuffle the numbers and cycle through the divs working but I'm not sure how to combine the two.

The script so far looks like this

$(document).ready(function() {

    function shuffle(arra1) {
        var ctr = arra1.length, temp, index;

        // While there are elements in the array
        while (ctr > 0) {
            // Pick a random index
            index = Math.floor(Math.random() * ctr);
            // Decrease ctr by 1
            ctr--;
            // And swap the last element with it
            temp = arra1[ctr];
            arra1[ctr] = arra1[index];
            arra1[index] = temp;
        }

        return arra1;
    }

    var myArray = [0, 1, 2, 3, 4, 5];
    console.log(shuffle(myArray));

    var divs = $('div[id^="random"]').hide(),
        i = 0;

    (function cycle() {
        divs.eq(i).fadeIn(400)
                  .delay(1000)
                  .fadeOut(400, cycle);

        i = ++i % divs.length;
    })();
});

The div's that I'm trying to cycle through in the HTML look Like this

Div 0

Div 1

Div 2

Div 3

Div 4

Div 5

If anyone could point me in the right direction I'd greatly appreciate it.


问:
Cast type to va_arg return
Can i cast type to va_arg return as on example?
As i know va_arg can't read-return char/short int types</p>

```<code>if (flags->size == 0)
    u->s = (char)va_arg(pt, int);
if (flags->size == 1)
    u->s = (short int)va_arg(pt, int);
</code>```

答:
The standard specifies that

The va_arg macro expands to an expression that has the specified type and the value of the next argument in the call.

(C2011 7.16.1.1/2)

The fact that such an expression resulted from expansion of a macro has no bearing on how it can be used.  In particular, when the type specified to va_arg is int, the resulting int-type expression can certainly be cast to other integer types, provided that va_arg()'s behavior is defined (roughly meaning that int is compatible with the promoted type of the actual argument).

So yes, you can cast the result of va_arg().

Title: Cast type to va_arg return

Body:
Can i cast type to va_arg return as on example?
As i know va_arg can't read-return char/short int types

if (flags->size == 0)
    u->s = (char)va_arg(pt, int);
if (flags->size == 1)
    u->s = (short int)va_arg(pt, int);


问:
jquery effect highlight not working
I'm banging my head against the wall using the highlight feature, for which i use quite often.

In the console when I run:

```<code>$('.2').effect('highlight', {}, 3000);
</code>```

It returns:

[…]

Which is the element i'd like to highlight.  However it doesn't highlight it and I get no errors.

Funny story, because when this it works; but what I like about highlight, it natively has a duration it removes the highlight.

```<code>$(".2").css({ backgroundColor: "#FFFF88" });
</code>```

Any ideas are welcome!

http://jsfiddle.net/XxyjE/1/

答:
This ia an old question I know, but I encountered a similar problem just recently, and wanted to share the fix for any others who are having similar issues.

The problem was that the element I was trying to highlight had the transition CSS property set, and this apparently interfered with the highlight effect (making it completely invisible).

Title: jquery effect highlight not working

Body:
I'm banging my head against the wall using the highlight feature, for which i use quite often.

In the console when I run:

$('.2').effect('highlight', {}, 3000);

It returns:

[…]

Which is the element i'd like to highlight.  However it doesn't highlight it and I get no errors.

Funny story, because when this it works; but what I like about highlight, it natively has a duration it removes the highlight.

$(".2").css({ backgroundColor: "#FFFF88" });

Any ideas are welcome!

http://jsfiddle.net/XxyjE/1/