答:
Each time the method

```<code>mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            new AlertDialog.Builder(MapsActivity.this)
                    .setTitle(Designacao)
                    .setMessage("Endereço: " + Morada + "\n" + "Telefone: " )
                    .setPositiveButton("Ir", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            new GetDirecoes().execute();//Enviar as coordenadas
                            mBottomSheetBehavior.setPeekHeight(250);
                        }
                    })
                    .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // do nothing
                        }
                    })
                    .show();
            return false;
        }
    });
</code>```

is called, it is overriding the OnMarkerClickListener that you set previously. For this reason eventually the last OnMarkerClickListener is being set to map and that is why it is giving the same place information on every click (the information of the last place).

In order to solve the problem you must work with the marker object that is being received from the onMarkerClick(Marker marker) method and set the listener outside the loop. You may set the position as the tag to the marker and later in onMarkerClick(Marker marker) you can check the position and get related place info from listaOportunidades.

```<code>Marker m = mMap.addMarker(new MarkerOptions().position(new LatLng(lat1, lng1)));
m.setTag(i);
</code>```

and later

```<code>    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                int position = (int) marker.getTag();
// Show your alert dialog for the information related to the position
                return false;
            }
        });
</code>```

Title: Creating markers with onClickListener that opens AlertDialog dynamically

Body:
I'm trying to add markers to the map dynamically, getting the data from JSON, and that part is working, I can add multiple marker in multiple places, but when I click on the marker I want that a alert dialog opens, this alert dialog must contain some information regarding that marker, but right now the information I have is always the same, it's like if the the creation of the alert dialog is not in the same cycle that creates the marker.

See my code:

final JSONArray array = new JSONArray(jsonStrOportunidades);
for (int i = 0; i < array.length(); i++)
{
    JSONObject jsonObject = array.getJSONObject(i);
    final String Designacao = jsonObject.getString("Designacao");
    String Coord_LAT = jsonObject.getString("Coord_LAT");
    String Coord_LONG = jsonObject.getString("Coord_LONG");
    final String Morada = jsonObject.getString("Morada");

    final HashMap<String, String> oportunidades = new HashMap<>();

    oportunidades.put("Designacao", Designacao);
    oportunidades.put("Coord_LAT", Coord_LAT);
    oportunidades.put("Coord_LONG", Coord_LONG);
    oportunidades.put("Morada", Morada);

    double lat1 = Double.parseDouble(Coord_LAT);
    double lng1 = Double.parseDouble(Coord_LONG);

    mMap.addMarker(new MarkerOptions().position(new LatLng(lat1, lng1)));

    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            new AlertDialog.Builder(MapsActivity.this)
                    .setTitle(Designacao)
                    .setMessage("Endereço: " + Morada + "\n" + "Telefone: " )
                    .setPositiveButton("Ir", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            new GetDirecoes().execute();//Enviar as coordenadas
                            mBottomSheetBehavior.setPeekHeight(250);
                        }
                    })
                    .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // do nothing
                        }
                    })
                    .show();
            return false;
        }
    });
    listaOportunidades.add(oportunidades);
}

Body:
Each time the method

mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            new AlertDialog.Builder(MapsActivity.this)
                    .setTitle(Designacao)
                    .setMessage("Endereço: " + Morada + "\n" + "Telefone: " )
                    .setPositiveButton("Ir", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            new GetDirecoes().execute();//Enviar as coordenadas
                            mBottomSheetBehavior.setPeekHeight(250);
                        }
                    })
                    .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // do nothing
                        }
                    })
                    .show();
            return false;
        }
    });

is called, it is overriding the OnMarkerClickListener that you set previously. For this reason eventually the last OnMarkerClickListener is being set to map and that is why it is giving the same place information on every click (the information of the last place).

In order to solve the problem you must work with the marker object that is being received from the onMarkerClick(Marker marker) method and set the listener outside the loop. You may set the position as the tag to the marker and later in onMarkerClick(Marker marker) you can check the position and get related place info from listaOportunidades.

Marker m = mMap.addMarker(new MarkerOptions().position(new LatLng(lat1, lng1)));
m.setTag(i);

and later

    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                int position = (int) marker.getTag();
// Show your alert dialog for the information related to the position
                return false;
            }
        });


来源: stackexchange

问:
How to convert a specific string to integer?
Hi here is the scenario that I have strings like this;

```<code>$a="08";
$b="00";
$c="0";
</code>```

actually this is time part of a datetime i want to get these as integer

答:
For situations where you do want to explicitly convert the type, cast it:

```<code>$a="08";
$b="00";
$c="0";
$seconds=(int)$a*3600;
var_dump((int)$a);
print_r($seconds);
</code>```

Hope it helps!

ContentLicense: CC BY-SA 3.0

Body:
Hi here is the scenario that I have strings like this;

$a="08";
$b="00";
$c="0";

actually this is time part of a datetime i want to get these as integer

Body:
For situations where you do want to explicitly convert the type, cast it:

$a="08";
$b="00";
$c="0";
$seconds=(int)$a*3600;
var_dump((int)$a);
print_r($seconds);

Hope it helps!


问:
Cannot execute Git commands from Gradle build script on Windows 10
I have recently forked and cloned a repositroy from GitHub that uses Gradle, but I am unable to execute any Gradle tasks.

It fails on:

```<code>def process = 'git rev-parse --short HEAD'.execute()
</code>```

with:

```<code>FAILURE: Build failed with an exception.
* Where:
Build file 'C:\Users\Joseph\Desktop\Minecraft\ObsidianSuite\ForgeGradle\ForgeGradle\build.gradle' line: 286

* What went wrong:
A problem occurred evaluating root project 'ForgeGradle'.
> Cannot run program "git": CreateProcess error=2, The system cannot find the file specified
</code>```

I am running Windows 10, and have Git working with MinGW. I have set the path variable to include (C:\Program Files\Git\cmd) such that I can run Git from command prompt. The Git command that is called by the build.gradle file executes fine if I run it from the command line, it is just not working when run through the Gradle wrapper.

Any help or advice would be much appreciated; I am able to answer any questions that might help work out what the issue is. Thanks.

EDIT: I normally use Git by running git-bash in the relevant folder rather than git from command prompt.

答: Please, don't call executables from Java/Groovy/Gradle/etc. There are many java/groovy libraries to deal with Git repositories, including Gradle plugins</p>

Body:
I have recently forked and cloned a repositroy from GitHub that uses Gradle, but I am unable to execute any Gradle tasks.

It fails on:

def process = 'git rev-parse --short HEAD'.execute()

with:

FAILURE: Build failed with an exception.
* Where:
Build file 'C:\Users\Joseph\Desktop\Minecraft\ObsidianSuite\ForgeGradle\ForgeGradle\build.gradle' line: 286

* What went wrong:
A problem occurred evaluating root project 'ForgeGradle'.
> Cannot run program "git": CreateProcess error=2, The system cannot find the file specified

I am running Windows 10, and have Git working with MinGW. I have set the path variable to include (C:\Program Files\Git\cmd) such that I can run Git from command prompt. The Git command that is called by the build.gradle file executes fine if I run it from the command line, it is just not working when run through the Gradle wrapper.

Any help or advice would be much appreciated; I am able to answer any questions that might help work out what the issue is. Thanks.

EDIT: I normally use Git by running git-bash in the relevant folder rather than git from command prompt.


问:
Why private method does not became overwritten
I'm trying to execute code from official php docs, but I can not understand why private Bar method does not became overwritten by Foo?

```<code>class Bar
{
    public function test() {
        $this->testPrivate();
        $this->testPublic();
    }

    public function testPublic() {
        echo "Bar::testPublic\n";
    }

    private function testPrivate() {
        echo "Bar::testPrivate\n";
    }
}

class Foo extends Bar
{
    public function testPublic() {
        echo "Foo::testPublic\n";
    }

    private function testPrivate() {
        echo "Foo::testPrivate\n";
    }
}

$myFoo = new Foo();
$myFoo->test();
</code>```

Prints Bar::testPrivate Foo::testPublic, but why?

答:
In a comment from the same documentation you are probbaly using

If you have problems with overriding private methods in extended
  classes, read this:)

The manual says that "Private limits visibility only to the class that
  defines the item". That means extended children classes do not see the
  private methods of parent class and vice versa also.

As a result, parents and children can have different implementations
  of the "same" private methods, depending on where you call them (e.g.
  parent or child class instance). Why? Because private methods are
  visible only for the class that defines them and the child class does
  not see the parent's private methods. If the child doesn't see the
  parent's private methods, the child can't override them. Scopes are
  different. In other words -- each class has a private set of private
  variables that no-one else has access to.

A sample demonstrating the percularities of private methods when
  extending classes:

```<code><?php  abstract class base {
     public function inherited() {
         $this->overridden();
     }
     private function overridden() {
         echo 'base';
     }  }

 class child extends base {
     private function overridden() {
         echo 'child';
     }  }

 $test = new child();  $test->inherited();  ?>
</code>```

Output will be "base".

If you want the inherited methods to use overridden functionality in
  extended classes but public sounds too loose, use protected. That's
  what it is for:)

A sample that works as intended:

```<code><?php  abstract class base {
     public function inherited() {
         $this->overridden();
     }
     protected function overridden() {
         echo 'base';
     }  }

 class child extends base {
     protected function overridden() {
         echo 'child';
     }  }

 $test = new child();  $test->inherited();  ?>  Output will be "child".
</code>```

See Php docs for the original comment

Body:
I'm trying to execute code from official php docs, but I can not understand why private Bar method does not became overwritten by Foo?

class Bar
{
    public function test() {
        $this->testPrivate();
        $this->testPublic();
    }

    public function testPublic() {
        echo "Bar::testPublic\n";
    }

    private function testPrivate() {
        echo "Bar::testPrivate\n";
    }
}

class Foo extends Bar
{
    public function testPublic() {
        echo "Foo::testPublic\n";
    }

    private function testPrivate() {
        echo "Foo::testPrivate\n";
    }
}

$myFoo = new Foo();
$myFoo->test();

Prints Bar::testPrivate Foo::testPublic, but why?

Body:
In a comment from the same documentation you are probbaly using

If you have problems with overriding private methods in extended
  classes, read this:)

The manual says that "Private limits visibility only to the class that
  defines the item". That means extended children classes do not see the
  private methods of parent class and vice versa also.

As a result, parents and children can have different implementations
  of the "same" private methods, depending on where you call them (e.g.
  parent or child class instance). Why? Because private methods are
  visible only for the class that defines them and the child class does
  not see the parent's private methods. If the child doesn't see the
  parent's private methods, the child can't override them. Scopes are
  different. In other words -- each class has a private set of private
  variables that no-one else has access to.

A sample demonstrating the percularities of private methods when
  extending classes:

<?php  abstract class base {
     public function inherited() {
         $this->overridden();
     }
     private function overridden() {
         echo 'base';
     }  }

 class child extends base {
     private function overridden() {
         echo 'child';
     }  }

 $test = new child();  $test->inherited();  ?>

Output will be "base".

If you want the inherited methods to use overridden functionality in
  extended classes but public sounds too loose, use protected. That's
  what it is for:)

A sample that works as intended:

<?php  abstract class base {
     public function inherited() {
         $this->overridden();
     }
     protected function overridden() {
         echo 'base';
     }  }

 class child extends base {
     protected function overridden() {
         echo 'child';
     }  }

 $test = new child();  $test->inherited();  ?>  Output will be "child".

See Php docs for the original comment


问:
gulp-image-optimization build gives error
My Node and Npm Vesrions are below

node v6.9.1
npm  v3.10.9

My code is

```<code>'use strict';
const gulp = require('gulp');
const imageop = require('gulp-image-optimization');

let dir = {
    srcImages: 'public/wps/source/images',
    build: 'public/wps/build/'
};

const config = {
    src: dir.srcImages + '/**/*',
    dest: dir.build + 'images/'
};

gulp.task('img-prod', function (cb) {
   gulp.src(config.src).pipe(imageop({
           optimizationLevel: 5,
           progressive: true,
           interlaced: true
       })).pipe(gulp.dest(config.dest)).on('end', cb).on('error', cb);
});
</code>```

When i do gulp build it throws an error

internal/child_process.js:289
  var err = this._handle.spawn(options);
                         ^

TypeError: Bad argument
      at TypeError (native)
      at ChildProcess.spawn (internal/child_process.js:289:26)
      at exports.spawn (child_process.js:380:9)
      at Imagemin._optimizeJpeg (/Users/sureshraju/xxx/Wps/web-pres/node_modules/image-min/imagemin.js:126:12)
      at Imagemin.optimize (/Users/sureshraju/xxxx/Wps/web-pres/node_modules/image-min/imagemin.js:57:26)
      at module.exports (/Users/sureshraju/xxxx/Wps/web-pres/node_modules/image-min/imagemin.js:179:21)
      at /Users/sureshraju/xxxx/Wps/web-pres/node_modules/gulp-image-optimization/index.js:38:17
      at FSReqWrap.oncomplete (fs.js:123:15)

答:
Do you have svg files in your source directory?
I have just been getting the exact same problem in a project I have picked up from someone else.

I omitted svg files from the glob and the task then ran without errors.

Body:
My Node and Npm Vesrions are below

node v6.9.1
npm  v3.10.9

My code is

'use strict';
const gulp = require('gulp');
const imageop = require('gulp-image-optimization');

let dir = {
    srcImages: 'public/wps/source/images',
    build: 'public/wps/build/'
};

const config = {
    src: dir.srcImages + '/**/*',
    dest: dir.build + 'images/'
};

gulp.task('img-prod', function (cb) {
   gulp.src(config.src).pipe(imageop({
           optimizationLevel: 5,
           progressive: true,
           interlaced: true
       })).pipe(gulp.dest(config.dest)).on('end', cb).on('error', cb);
});

When i do gulp build it throws an error

internal/child_process.js:289
  var err = this._handle.spawn(options);
                         ^

TypeError: Bad argument
      at TypeError (native)
      at ChildProcess.spawn (internal/child_process.js:289:26)
      at exports.spawn (child_process.js:380:9)
      at Imagemin._optimizeJpeg (/Users/sureshraju/xxx/Wps/web-pres/node_modules/image-min/imagemin.js:126:12)
      at Imagemin.optimize (/Users/sureshraju/xxxx/Wps/web-pres/node_modules/image-min/imagemin.js:57:26)
      at module.exports (/Users/sureshraju/xxxx/Wps/web-pres/node_modules/image-min/imagemin.js:179:21)
      at /Users/sureshraju/xxxx/Wps/web-pres/node_modules/gulp-image-optimization/index.js:38:17
      at FSReqWrap.oncomplete (fs.js:123:15)


问:
Get attachment from single page by id, and paged it. (Wordpress)
How to get attachment from single page by ID, and set 12 img per page?

'post_parent' => 145, // not working, but without this param I get all attachments

```<code><?php
                $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
                $attachment = new WP_Query( array(
                    'post_parent' => 145, // not working, but without this param I get all attachments
                    'post_status' => 'inherit',
                    'post_type' => 'attachment',
                    'post_mime_type' => 'image/jpeg,image/gif,image/jpg,image/png',
                    'posts_per_page'  => 12,
                    'paged'           => $paged
                ) );
                if ( $attachment->have_posts() ) :
                    while ( $attachment->have_posts() ) : $attachment->the_post();

            ?>
                        <div class="gallery__item"><a href="<?php echo wp_get_attachment_url( $attachment->ID , false ); ?>" data-fancybox><img src="<?php echo wp_get_attachment_url( $attachment->ID , false ); ?>" alt=""></a></div>
            <?php

                    endwhile;
                    wp_reset_postdata();
                endif;
            ?>
</code>```

答:
By looking to the code, you are using post_parent which is quiet clearly explain in

Codex WP Query

which basically says that only the post that has child will be return of the currently provided post id i.e. 145.

I think you have to use post_parent__in than the current one.

Hope this works for you.

Thank You

Body:
How to get attachment from single page by ID, and set 12 img per page?

'post_parent' => 145, // not working, but without this param I get all attachments

<?php
                $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
                $attachment = new WP_Query( array(
                    'post_parent' => 145, // not working, but without this param I get all attachments
                    'post_status' => 'inherit',
                    'post_type' => 'attachment',
                    'post_mime_type' => 'image/jpeg,image/gif,image/jpg,image/png',
                    'posts_per_page'  => 12,
                    'paged'           => $paged
                ) );
                if ( $attachment->have_posts() ) :
                    while ( $attachment->have_posts() ) : $attachment->the_post();

            ?>

<a href="<?php echo wp_get_attachment_url( $attachment->ID , false ); ?>" data-fancybox><img src="<?php echo wp_get_attachment_url( $attachment->ID , false ); ?>" alt="">

            <?php

                    endwhile;
                    wp_reset_postdata();
                endif;
            ?>


问:
DateTimeFormatter parsing - timezone names and daylight savings overlap times
For improving performance of some legacy code, I am considering a replacement of java.text.SimpleDateFormat by java.time.format.DateTimeFormatter.

Among the tasks performed is parsing date/time values that had been serialized using java.util.Date.toString. With SimpleDateFormat, it was possible to turn them back into the original timestamps (neglecting fractional seconds), however I am facing problems when attempting to do the same with DateTimeFormatter.

When formatting with either, my local timezone is indicated as CET or CEST, depending on whether daylight savings time is in effect for the time to be formatted. However it appears that at parsing time, both CET and CEST are treated the same by DateTimeFormatter.

This creates a problem with the overlap occurring at the end of daylight savings time. When formatting, 02:00:00 is created twice, for times one hour apart, but with CEST and CET timezone names - which is fine. But at parsing time, that difference can't be reclaimed.

Here is an example:

```<code>long msecPerHour = 3600000L;
long cet_dst_2016 = 1477778400000L;
DateTimeFormatter formatter =
    DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
ZoneId timezone = ZoneId.of("Europe/Berlin");
for (int hours = 0; hours < 6; ++hours) {
    long time = cet_dst_2016 + msecPerHour * hours;
    String formatted = formatter.format(Instant.ofEpochMilli(time).atZone(timezone));
    long parsedTime = Instant.from(formatter.parse(formatted)).toEpochMilli();
    System.out.println(formatted + ", diff: " + (parsedTime - time));
}
</code>```

which results in

```<code>Sun Oct 30 00:00:00 CEST 2016, diff: 0
Sun Oct 30 01:00:00 CEST 2016, diff: 0
Sun Oct 30 02:00:00 CEST 2016, diff: 0
Sun Oct 30 02:00:00 CET 2016, diff: -3600000
Sun Oct 30 03:00:00 CET 2016, diff: 0
Sun Oct 30 04:00:00 CET 2016, diff: 0
</code>```

It shows that the second occurrence of 02:00:00, inspite of the different timezone name, was treated like the first one. So the result effectively is off by one hour.

Obviously the formatted string has all information available, and SimpleDateFormat parsing in fact honored it. Is it possible to roundtrip through formatting and parsing, using DateTimeFormatter, with the given pattern?

答:
It is possible for a specific case:

```<code>DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .appendPattern("EEE MMM dd HH:mm:ss ")
    .appendText(OFFSET_SECONDS, ImmutableMap.of(2L * 60 * 60, "CEST", 1L * 60 * 60, "CET"))
    .appendPattern(" yyyy")
    .toFormatter(Locale.ENGLISH);
</code>```

This maps the exact offset to the expected text. Where this fails is when you need to deal with more than one time-zone.

To do the job properly requires a JDK change.

Body:
For improving performance of some legacy code, I am considering a replacement of java.text.SimpleDateFormat by java.time.format.DateTimeFormatter.

Among the tasks performed is parsing date/time values that had been serialized using java.util.Date.toString. With SimpleDateFormat, it was possible to turn them back into the original timestamps (neglecting fractional seconds), however I am facing problems when attempting to do the same with DateTimeFormatter.

When formatting with either, my local timezone is indicated as CET or CEST, depending on whether daylight savings time is in effect for the time to be formatted. However it appears that at parsing time, both CET and CEST are treated the same by DateTimeFormatter.

This creates a problem with the overlap occurring at the end of daylight savings time. When formatting, 02:00:00 is created twice, for times one hour apart, but with CEST and CET timezone names - which is fine. But at parsing time, that difference can't be reclaimed.

Here is an example:

long msecPerHour = 3600000L;
long cet_dst_2016 = 1477778400000L;
DateTimeFormatter formatter =
    DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
ZoneId timezone = ZoneId.of("Europe/Berlin");
for (int hours = 0; hours < 6; ++hours) {
    long time = cet_dst_2016 + msecPerHour * hours;
    String formatted = formatter.format(Instant.ofEpochMilli(time).atZone(timezone));
    long parsedTime = Instant.from(formatter.parse(formatted)).toEpochMilli();
    System.out.println(formatted + ", diff: " + (parsedTime - time));
}

which results in

Sun Oct 30 00:00:00 CEST 2016, diff: 0
Sun Oct 30 01:00:00 CEST 2016, diff: 0
Sun Oct 30 02:00:00 CEST 2016, diff: 0
Sun Oct 30 02:00:00 CET 2016, diff: -3600000
Sun Oct 30 03:00:00 CET 2016, diff: 0
Sun Oct 30 04:00:00 CET 2016, diff: 0

It shows that the second occurrence of 02:00:00, inspite of the different timezone name, was treated like the first one. So the result effectively is off by one hour.

Obviously the formatted string has all information available, and SimpleDateFormat parsing in fact honored it. Is it possible to roundtrip through formatting and parsing, using DateTimeFormatter, with the given pattern?

Body:
It is possible for a specific case:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .appendPattern("EEE MMM dd HH:mm:ss ")
    .appendText(OFFSET_SECONDS, ImmutableMap.of(2L * 60 * 60, "CEST", 1L * 60 * 60, "CET"))
    .appendPattern(" yyyy")
    .toFormatter(Locale.ENGLISH);

This maps the exact offset to the expected text. Where this fails is when you need to deal with more than one time-zone.

To do the job properly requires a JDK change.


问:
Error occurred when passing r-value reference to r-value reference parameter
I have code

```<code>void print(string &&str) {
   cout << str << endl;
}
int main() {
   string tmp("Hello");
   string&& str = move(tmp);
   //print(move(str));
   print(str);
   return 0;
}
</code>```

After compiling I get error: cannot bind rvalue reference of type 'std::__cxx11::string&&' to lvalue of type 'std::__cxx11::string'.

But str is r-value reference to r-value(isn't it?), so passing it into print makes sense I believe. Why this error occurred?

答:
You're confusing with value categories and types.

(emphasis mine)

lvalue

The following expressions are lvalue expressions:

the name of a variable or a function in scope, regardless of type, such as std::cin or std::endl. Even if the variable's type is rvalue
  reference, the expression consisting of its name is an lvalue
  expression;

...

The type of str is rvalue-reference (to string), but as a named variable it's an lvalue, which can't be bound to rvalue reference.

Consider the following case if this is allowed:

```<code>string tmp("Hello");
string&& str = move(tmp);
print(str);               // str might be moved here

cout << str << endl;      // dangerous; str's state is undeterminate
</code>```

So you need to use std::move explicitly (to convert str to an xvalue) if you're sure of the effects.

Body:
I have code

void print(string &&str) {
   cout << str << endl;
}
int main() {
   string tmp("Hello");
   string&& str = move(tmp);
   //print(move(str));
   print(str);
   return 0;
}

After compiling I get error: cannot bind rvalue reference of type 'std::__cxx11::string&&' to lvalue of type 'std::__cxx11::string'.

But str is r-value reference to r-value(isn't it?), so passing it into print makes sense I believe. Why this error occurred?

Body:
You're confusing with value categories and types.

(emphasis mine)

lvalue

The following expressions are lvalue expressions:

the name of a variable or a function in scope, regardless of type, such as std::cin or std::endl. Even if the variable's type is rvalue
  reference, the expression consisting of its name is an lvalue
  expression;

...

The type of str is rvalue-reference (to string), but as a named variable it's an lvalue, which can't be bound to rvalue reference.

Consider the following case if this is allowed:

string tmp("Hello");
string&& str = move(tmp);
print(str);               // str might be moved here

cout << str << endl;      // dangerous; str's state is undeterminate

So you need to use std::move explicitly (to convert str to an xvalue) if you're sure of the effects.


问:
Copy values from one column to another in the same table
How can I make a copy values from one column to another?

I have:

```<code>Database name: list

-------------------
number | test
-------------------
123456 | somedata
123486 | somedata1
232344 | 34
</code>```

I want to have:

```<code>Database name: list

----------------
number | test
----------------
123456 | 123456
123486 | 123486
232344 | 232344
</code>```

What MySQL query should I have?

答:
Following worked for me..

Ensure you are not using Safe-mode in your query editor application. If you are, disable it!

Then run following sql command

for a table say, 'test_update_cmd', source value column col2, target
  value column col1 and condition column col3: -

```<code>UPDATE  test_update_cmd SET col1=col2 WHERE col3='value';
</code>```

Good Luck!

ContentLicense: CC BY-SA 4.0

Body:
How can I make a copy values from one column to another?

I have:

Database name: list

-------------------
number | test
-------------------
123456 | somedata
123486 | somedata1
232344 | 34

I want to have:

Database name: list

----------------
number | test
----------------
123456 | 123456
123486 | 123486
232344 | 232344

What MySQL query should I have?

Body:
Following worked for me..

Ensure you are not using Safe-mode in your query editor application. If you are, disable it!

Then run following sql command

for a table say, 'test_update_cmd', source value column col2, target
  value column col1 and condition column col3: -

UPDATE  test_update_cmd SET col1=col2 WHERE col3='value';

Good Luck!


问:
How to create awk regex to match only one "space" between two words?
I have a sentence of form 2016-23-12 90-34-23 want to create an awk script to match it.

a.awk

```<code>$1 ~ /^[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}[[:space:]][[:digit:]]{2}-[[:digit:]]{2}-[[:digit:]]{2}/{
  ts = $1 " " $2
  print
}
</code>```

Run using:

```<code>awk -f a.awk --posix

2016-23-12 90-34-23
</code>```

Output:

Nothing

答:
I assume your intention is match the whole string, in which $1 is incorrect, use it as $0

The problem you are seeing is Awk dynamic regular-expressions like the one you used don't need the $0 ~ /regex/ type match, the // is not needed here, just do as with your script being,

```<code>dynamicRegex = "[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}[[:space:]][[:digit:]]{2}-[[:digit:]]{2}-[[:digit:]]{2}"

$0 ~ dynamicRegex {
    print "match success"
}
</code>```

and now running the script as

```<code>echo "2016-23-12 90-34-23"| awk -f a.awk --posix
2016-23-12 90-34-23
match success
</code>```

Quoting from the page,

[..]The righthand side of a ~ or !~ operator need not be a regexp constant (i.e., a string of characters between slashes). It may be any expression. The expression is evaluated and converted to a string if necessary; the contents of the string are used as the regexp. A regexp that is computed in this way is called a dynamic regexp [..]

Another way would be to use the normal Regular Expression syntax over the POSIX character classes as a regexp constant as below,

```<code>$0 ~ /^[0-9]{4}-[0-9]{2}-[0-9]{2}\s[0-9]{2}-[0-9]{2}-[0-9]{2}$/ {
    print "match success"
}
</code>```

Remember with the above regex, your script is not longer POSIX compatible and running with --posix won't work here, also the \s here is a GNU Awk specific construct. Running it as

```<code>echo "2016-23-12 90-34-23"| awk -f a.awk
match success
</code>```

Now to print the line upon the match, upon success just do,

```<code>print $1 FS $2
</code>```

after the earlier print command.

Body:
I have a sentence of form 2016-23-12 90-34-23 want to create an awk script to match it.

a.awk

$1 ~ /^[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}[[:space:]][[:digit:]]{2}-[[:digit:]]{2}-[[:digit:]]{2}/{
  ts = $1 " " $2
  print
}

Run using:

awk -f a.awk --posix

2016-23-12 90-34-23

Output:

Nothing

Body:
I assume your intention is match the whole string, in which $1 is incorrect, use it as $0

The problem you are seeing is Awk dynamic regular-expressions like the one you used don't need the $0 ~ /regex/ type match, the // is not needed here, just do as with your script being,

dynamicRegex = "[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}[[:space:]][[:digit:]]{2}-[[:digit:]]{2}-[[:digit:]]{2}"

$0 ~ dynamicRegex {
    print "match success"
}

and now running the script as

echo "2016-23-12 90-34-23"| awk -f a.awk --posix
2016-23-12 90-34-23
match success

Quoting from the page,

[..]The righthand side of a ~ or !~ operator need not be a regexp constant (i.e., a string of characters between slashes). It may be any expression. The expression is evaluated and converted to a string if necessary; the contents of the string are used as the regexp. A regexp that is computed in this way is called a dynamic regexp [..]

Another way would be to use the normal Regular Expression syntax over the POSIX character classes as a regexp constant as below,

$0 ~ /^[0-9]{4}-[0-9]{2}-[0-9]{2}\s[0-9]{2}-[0-9]{2}-[0-9]{2}$/ {
    print "match success"
}

Remember with the above regex, your script is not longer POSIX compatible and running with --posix won't work here, also the \s here is a GNU Awk specific construct. Running it as

echo "2016-23-12 90-34-23"| awk -f a.awk
match success

Now to print the line upon the match, upon success just do,

print $1 FS $2

after the earlier print command.


问:
How to use Material-UI in asp.net mvc project
Is there a way of using Material-UI without having to go through installing all of the dependencies using NodeJS. I would love to use this in an ASP.NET Project but dont know where to begin as per installing dependencies and all of that.</p>

答:
it's very easy.. Follow the below steps.

Commit all the existing changes to your source control or backup existing code.

delete or comment twitter bootstrap bundles in bundle config.

using NPN .. install material design lite package.

add all the .css and .js references to bundles.

add new bundles you added to the layout page.

Remember to change all the class that uses twitter bootstrap to material design lite.

useful sources:

Learning Material Design

MDL Website


问:
select2: default selection in multiple select with AJAX
I am using the awesome select2 to create a multiple selection combo.

I would like to programmatically select default values (as in selections the user has made previously), but I don't know how. I read that using initSelection does the trick but this is called when creating the combo and I don't want this default selection to be always done.

答:
Figured it out finally!!
Select2 iterates through the <option> tag under the <select>.

```<code><select class="js-data-example-ajax" style="width:100%">
  <option value="3620194" selected="selected">Put the pre-selected options here</option>
</select>
</code>```

The inner html of the <option> is put into the repo object under the text key. So repo.text will give the innerhtml. That is, all we have to do is supply repo.text to the formatSelection option in the init. Also the json being passed from the servlet (controller) should have the desired label text put under the text key!!
Still figuring out how to add attributes to the li elements created, so that I can save the changed list.
Any ideas?

Body:
Figured it out finally!!
Select2 iterates through the <option> tag under the <select>.

<select class="js-data-example-ajax" style="width:100%">
  <option value="3620194" selected="selected">Put the pre-selected options here</option>
</select>

The inner html of the <option> is put into the repo object under the text key. So repo.text will give the innerhtml. That is, all we have to do is supply repo.text to the formatSelection option in the init. Also the json being passed from the servlet (controller) should have the desired label text put under the text key!!
Still figuring out how to add attributes to the li elements created, so that I can save the changed list.
Any ideas?


问:
Is This An Example Of Recursion (Python)
Hi I am struggling to understand exactly what recursion is, It is a requirement of the program I am writing(a snake game) and I cannot find a clear definition of what is classified as recursion. Could someone tell me if the code below is an example of this?

while True:
    #recieve input
    player_name = input("Enter a name between 0 and 20 characters: ")
    #if length is within boundaries the loop is stopped
    if len(player_name) > 0 and len(player_name) <= 20: break
    #if the name is outwith the boundaries a message is printed and the loop restarts
    print("Too long/short, try again.")

答:
You have recursion when you define something in terms of itself. For example, the following definition of "walk staircase" is recursive:

"walk staircase" :=

if there's a step left: take a step and "walk staircase"

else if there's no step left: stop

In programming recursion is most often seen in the form of recursive function definitions, that is functions that call themselves.

Here's an example function that computes the sum 1 + 2 + 3 + ... + n for some number n > 0.

```<code>>>> def cumsum(n):
...     if n == 1:
...         return n
...     else:
...         return n + cumsum(n - 1)
...
>>> cumsum(5)
15
>>> 1+2+3+4+5
15
</code>```

What makes this function recursive is the fact that cumsum is used in the definition on cumsum itself.

Since you don't have any recursive calls in your code, it is not an example of recursion. Your while True loop is an example of iteration.

Body:
You have recursion when you define something in terms of itself. For example, the following definition of "walk staircase" is recursive:

"walk staircase" :=

if there's a step left: take a step and "walk staircase"

else if there's no step left: stop

In programming recursion is most often seen in the form of recursive function definitions, that is functions that call themselves.

Here's an example function that computes the sum 1 + 2 + 3 + ... + n for some number n > 0.

>>> def cumsum(n):
...     if n == 1:
...         return n
...     else:
...         return n + cumsum(n - 1)
...
>>> cumsum(5)
15
>>> 1+2+3+4+5
15

What makes this function recursive is the fact that cumsum is used in the definition on cumsum itself.

Since you don't have any recursive calls in your code, it is not an example of recursion. Your while True loop is an example of iteration.


问:
How do I call all comments for a post (workout in this case) where workout.user_id == current_user.id?
I have created a Ruby on Rails app where users can record their workouts and other users can comment on those workouts. I am using a Dashboard resource to aggregate information for current_user. I am trying to display recent comments on a current_user's workouts but can't seem to figure out how to do this correctly. I think I need a named_scope which I am not great at yet.

I essentially want the app to loop through the comments table but only return comments on Workouts where workout.user_id == to current_user.id.

/views/dashboard/index.html.erb

```<code><% @comments.each do |comment| %>
  <%= link_to (comment.user.username), comment.user %><br/>
  <%= time_ago_in_words(comment.created_at) %><br/>
  <%= link_to (comment.workout.title), comment.workout %><br/>
<% end %>
</code>```

dashboard_controller.rb

```<code>def index
  @comments = Comment.all(:order => "created_at DESC", :limit => 10)
  @workouts = Workout.all(:order => "created_at DESC", :limit => 10)
end
</code>```

*I don't think I need the @workouts line in their but put it anyway.

答:
Assuming that you have the models setup properly, here's something you can try:</p>

```<code>class Comment < ActiveRecord::Base
  named_scope :for_user, lambda { |user| { :joins => :workout, :conditions => ["workouts.user_id = ?", user.id] } }
  named_scope :order, lambda { |order| { :order => order } }
  named_scope :limit, lambda { |limit| { :limit => limit } }
end

class DashboardsController < ApplicationController
  def index
    @comments = Comment.for_user(current_user).order("created_at DESC").limit(10)
  end
end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have created a Ruby on Rails app where users can record their workouts and other users can comment on those workouts. I am using a Dashboard resource to aggregate information for current_user. I am trying to display recent comments on a current_user's workouts but can't seem to figure out how to do this correctly. I think I need a named_scope which I am not great at yet.

I essentially want the app to loop through the comments table but only return comments on Workouts where workout.user_id == to current_user.id.

/views/dashboard/index.html.erb

<% @comments.each do |comment| %>
  <%= link_to (comment.user.username), comment.user %>

  <%= time_ago_in_words(comment.created_at) %>

  <%= link_to (comment.workout.title), comment.workout %>

<% end %>

dashboard_controller.rb

def index
  @comments = Comment.all(:order => "created_at DESC", :limit => 10)
  @workouts = Workout.all(:order => "created_at DESC", :limit => 10)
end

*I don't think I need the @workouts line in their but put it anyway.

Body:
Assuming that you have the models setup properly, here's something you can try:

class Comment < ActiveRecord::Base
  named_scope :for_user, lambda { |user| { :joins => :workout, :conditions => ["workouts.user_id = ?", user.id] } }
  named_scope :order, lambda { |order| { :order => order } }
  named_scope :limit, lambda { |limit| { :limit => limit } }
end

class DashboardsController < ApplicationController
  def index
    @comments = Comment.for_user(current_user).order("created_at DESC").limit(10)
  end
end


问:
Displaying images with img tag in React.js
Iv'e been trying to load images to a simple  tag, but it simply doesn't work. I wish to use ES6 syntax, and not dynamically injecting the image in this case:

```<code>import React from 'react'
import BackgroundImage from './Sparrow_icon.png';

const Icon = ({icon}) => {

    return (
        <img src={require('./Sparrow_icon.png')} alt=""/>
    )
};

export default Icon;
</code>```

which resulted in:

```<code><img src="data:image/png;base64,bW9kdWxlLmV4cG9ydHMgPSBfX3dlYnBhY2tfcHVibGljX3BhdGhfXyArICJlNTZlYThiOTQ5OWUzZmM2NTkyY2ZhMjgxNjg1YTBkMy5wbmciOw==" />
</code>```

which displays.. nothing.
Also, when i'm converting it with a base64 convertor- the image doesn't exist.

I'm using webpack2 with file-loader and url-loader.

答:
Replace

```<code><img src={require('./Sparrow_icon.png')} alt=""/>
</code>```

with

```<code><img src={BackgroundImage} alt=""/>
</code>```

Does that work?

Body:
Iv'e been trying to load images to a simple  tag, but it simply doesn't work. I wish to use ES6 syntax, and not dynamically injecting the image in this case:

import React from 'react'
import BackgroundImage from './Sparrow_icon.png';

const Icon = ({icon}) => {

    return (

    )
};

export default Icon;

which resulted in:

which displays.. nothing.
Also, when i'm converting it with a base64 convertor- the image doesn't exist.

I'm using webpack2 with file-loader and url-loader.

Body:
Replace

<img src={require('./Sparrow_icon.png')} alt=""/>

with

<img src={BackgroundImage} alt=""/>

Does that work?


问:
Starting Consul in docker does not expose http ports
I followed the instructions in  cosul docker hub documentation to start the server in an Eucalyptus cloud. However other than using local host the Http port is not getting exposed out

```<code>export  CONSUL_LOCAL_CONFIG=/root/consul.json
</code>```

From 1

```<code>docker run -d --net=host -e 'CONSUL_LOCAL_CONFIG={"skip_leave_on_interrupt": true}' consul agent -server -bind=127.0.0.1 -bootstrap-expect=1
</code>```

Putting bind address as 127.0.0.1 is not ever starting the server; Giving the IP adress, the server is starting but bot accessible out. I tried -P and -p 8500:8500 also. Still not able to connect from another machine.

Note that this machine had a private IP as well as public IP.

So I am guessing that is the reason why -net-host is not starting on the bind address
Still not clear. Two similar threads I found which may explain this

Docker container doesn't expose ports when --net=host is mentioned in the docker run command

https://github.com/docker/docker/issues/13914

答:
Thanks to the comment by Rishiloyola

```<code> docker run -d -p 8400:8400 -p 8500:8500/tcp -p 8600:53/udp -e 'CONSUL_LOCAL_CONFIG={"acl_datacenter":"dc1","acl_default_policy":"deny","acl_down_policy":"extend-cache","acl_master_token":"the_one_ring","bootstrap_expect":1,"datacenter":"dc1","data_dir":"/usr/local/bin/consul.d/data","server":true}' consul agent -server -bind=127.0.0.1 -client=0.0.0.0
</code>```

Client from another machine

```<code>curl 10.X.X.X:8500/v1/catalog/services
{"consul":[]}
</code>```

Edit

If you need to run without ACL for tests

docker run -d -p 8400:8400 -p 8500:8500/tcp -p 8600:53/udp -e
  'CONSUL_LOCAL_CONFIG={"bootstrap_expect":1,"data_dir":"/usr/local/bin/consul.d/data","server":true}'
  consul agent -server -bind=127.0.0.1 -client=0.0.0.0 -ui

and

To test

```<code> curl -X PUT -d '{"Datacenter": "dc1", "Node": "bing", "Address": "www.bing.com", "Service": {"Service": "search", "Port": 80}}' myip:8500/v1/catalog/register
</code>```

(from https://jlordiales.me/2015/01/23/docker-consul/)

Body:
I followed the instructions in  cosul docker hub documentation to start the server in an Eucalyptus cloud. However other than using local host the Http port is not getting exposed out

export  CONSUL_LOCAL_CONFIG=/root/consul.json

From 1

docker run -d --net=host -e 'CONSUL_LOCAL_CONFIG={"skip_leave_on_interrupt": true}' consul agent -server -bind=127.0.0.1 -bootstrap-expect=1

Putting bind address as 127.0.0.1 is not ever starting the server; Giving the IP adress, the server is starting but bot accessible out. I tried -P and -p 8500:8500 also. Still not able to connect from another machine.

Note that this machine had a private IP as well as public IP.

So I am guessing that is the reason why -net-host is not starting on the bind address
Still not clear. Two similar threads I found which may explain this

Docker container doesn't expose ports when --net=host is mentioned in the docker run command

https://github.com/docker/docker/issues/13914

Body:
Thanks to the comment by Rishiloyola

 docker run -d -p 8400:8400 -p 8500:8500/tcp -p 8600:53/udp -e 'CONSUL_LOCAL_CONFIG={"acl_datacenter":"dc1","acl_default_policy":"deny","acl_down_policy":"extend-cache","acl_master_token":"the_one_ring","bootstrap_expect":1,"datacenter":"dc1","data_dir":"/usr/local/bin/consul.d/data","server":true}' consul agent -server -bind=127.0.0.1 -client=0.0.0.0

Client from another machine

curl 10.X.X.X:8500/v1/catalog/services
{"consul":[]}

Edit

If you need to run without ACL for tests

docker run -d -p 8400:8400 -p 8500:8500/tcp -p 8600:53/udp -e
  'CONSUL_LOCAL_CONFIG={"bootstrap_expect":1,"data_dir":"/usr/local/bin/consul.d/data","server":true}'
  consul agent -server -bind=127.0.0.1 -client=0.0.0.0 -ui

and

To test

 curl -X PUT -d '{"Datacenter": "dc1", "Node": "bing", "Address": "www.bing.com", "Service": {"Service": "search", "Port": 80}}' myip:8500/v1/catalog/register

(from https://jlordiales.me/2015/01/23/docker-consul/)


问:
Change size of UIBarButtonItem (image) in Swift 3
I am trying to change the size of some icons in my navBar, but I am a little confused as to how to do this? My code so far is: </p>

```<code>func setUpNavBarButtons() {
    let moreButton = UIBarButtonItem (image: UIImage(named:"ic_more_vert_3")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(handleMore))
    navigationItem.rightBarButtonItems = [moreButton]
    let refreshButton = UIBarButtonItem (image: UIImage(named:"ic_refresh")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(refreshDataButton))
    navigationItem.leftBarButtonItems = [refreshButton]
}
</code>```

<p>any help? </p>

答:
In the end I did it like this and it worked:

```<code>let moreButton = UIButton(frame: CGRect(x: 0, y: 0, width: 35, height: 35))
moreButton.setBackgroundImage(UIImage(named: "ic_more_vert_3"), for: .normal)
moreButton.addTarget(self, action: #selector(TableViewController.handleMore), for: .touchUpInside)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: moreButton)
</code>```

Answer from: Change width of a UIBarButtonItem in a UINavigationBar in swift

Body:
I am trying to change the size of some icons in my navBar, but I am a little confused as to how to do this? My code so far is:

func setUpNavBarButtons() {
    let moreButton = UIBarButtonItem (image: UIImage(named:"ic_more_vert_3")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(handleMore))
    navigationItem.rightBarButtonItems = [moreButton]
    let refreshButton = UIBarButtonItem (image: UIImage(named:"ic_refresh")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(refreshDataButton))
    navigationItem.leftBarButtonItems = [refreshButton]
}

any help?

Body:
In the end I did it like this and it worked:

let moreButton = UIButton(frame: CGRect(x: 0, y: 0, width: 35, height: 35))
moreButton.setBackgroundImage(UIImage(named: "ic_more_vert_3"), for: .normal)
moreButton.addTarget(self, action: #selector(TableViewController.handleMore), for: .touchUpInside)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: moreButton)

Answer from: Change width of a UIBarButtonItem in a UINavigationBar in swift


问:
How to break objects with flexbox and react correctly
I have a case where elements are grouped in rows, so that their heights are the same, when one element in the row resizes, but when screen gets smaller I want to flex elements in column, but changing their order somewhat. The problem is that I do not want to create separate react component just for this different layout. I have a drawing here:

答:
Add this in your outer div's style

```<code>   flexWrap: 'wrap'
</code>```

Check doc for more information on it

Body:
Add this in your outer div's style

   flexWrap: 'wrap'

Check doc for more information on it


问:
How do I make intellij Idea to highlight Scala script correctly with #! (shebang)
How do I make intellij Idea to highlight Scala script correctly.

Attempt 1
change filename to 'test.sc' . Intellij does not like the first line i.e it is not valid scala comment syntax

Attempt 2
change filename to 'test.sh' . Intellij thinks all of the syntax is bash script.

filenName = ./test.sh

```<code>#!/usr/bin/env amm
import ammonite.ops._ , ImplicitWd._

println("Stop script")
val x = 1 + 1
</code>```

答:
If you have a .scala extension, IDEA recognizes as a valid Scala script file.
Even a multiline shebang line is supported:

```<code>#!/bin/sh
  DIR=$(cd `dirname "${BASH_SOURCE[0]}"` && pwd)
  exec scala -classpath $DIR/scalaj-http_2.11-2.3.0.jar -savecompiled "$0" "$@"
!#
/* Scala code*/
</code>```

Make sure:

you are using a relatively recent version of IDEA.

Scala plugin is installed.

The script lies in a Scala module.

It works even if the script is outside of a declared source folder.
I can even edit scripts outside of my project.

Body:
How do I make intellij Idea to highlight Scala script correctly.

Attempt 1
change filename to 'test.sc' . Intellij does not like the first line i.e it is not valid scala comment syntax

Attempt 2
change filename to 'test.sh' . Intellij thinks all of the syntax is bash script.

filenName = ./test.sh

#!/usr/bin/env amm
import ammonite.ops._ , ImplicitWd._

println("Stop script")
val x = 1 + 1

Body:
If you have a .scala extension, IDEA recognizes as a valid Scala script file.
Even a multiline shebang line is supported:

#!/bin/sh
  DIR=$(cd `dirname "${BASH_SOURCE[0]}"` && pwd)
  exec scala -classpath $DIR/scalaj-http_2.11-2.3.0.jar -savecompiled "$0" "$@"
!#
/* Scala code*/

Make sure:

you are using a relatively recent version of IDEA.

Scala plugin is installed.

The script lies in a Scala module.

It works even if the script is outside of a declared source folder.
I can even edit scripts outside of my project.


问:
How to change the structure of JSON
I have a JSON like this

```<code>{"a":1,"b":2,"c":3}
</code>```

how can I convert its structure like this

```<code>[{
"option_id": "a",
"option_value": "1"
},
{
"option_id": "b",
"option_value": "2"
},
{
"option_id": "c",
"option_value": "3"
}]
</code>```

I tried JSON.stringify, result.push([i,data[i]]) etc but to no success so far

答:
Using Array#reduce.

var json = {"a":1,"b":2,"c":3},
    result = Object.keys(json).reduce(function(s,a){
      s.push({ "option_id": a, "option_value": json[a] });
      return s;
    }, []);

    console.log(result);```

Title: How to change the structure of JSON

Body:
I have a JSON like this

{"a":1,"b":2,"c":3}

how can I convert its structure like this

[{
"option_id": "a",
"option_value": "1"
},
{
"option_id": "b",
"option_value": "2"
},
{
"option_id": "c",
"option_value": "3"
}]

I tried JSON.stringify, result.push([i,data[i]]) etc but to no success so far


问:
Append Script file on HTML
I append script dynamically on html file, i put alert on my js file and its working. But the problem is document.write(); is not working anymore. Here is my code:

For the JS file: LANG_EN.js

```<code>alert("en");
var lang = {
  "USERNAME":"USERNAME",
  "PASSWORD":"PASSWORD",
};
</code>```

common.js

```<code>function createScript(id) {
  var elementID = id;
  var area = document.getElementById(elementID),

  script = document.createElement('script');
  script.src = 'js/lang_en.js';
  area.innerHTML = '';
  area.appendChild(script); // Append it
}

createScript('languagefile');
</code>```

HTML file:

```<code><label for="username">document.write(lang.USERNAME);</label>
</code>```

if i dont append the script the document.write is working properly.

I want to append it so that i can control the languages for all contents.

Please help. Thanks!

Title: Append Script file on HTML

Body:
I append script dynamically on html file, i put alert on my js file and its working. But the problem is document.write(); is not working anymore. Here is my code:

For the JS file: LANG_EN.js

alert("en");
var lang = {
  "USERNAME":"USERNAME",
  "PASSWORD":"PASSWORD",
};

common.js

function createScript(id) {
  var elementID = id;
  var area = document.getElementById(elementID),

  script = document.createElement('script');
  script.src = 'js/lang_en.js';
  area.innerHTML = '';
  area.appendChild(script); // Append it
}

createScript('languagefile');

HTML file:

document.write(lang.USERNAME);

if i dont append the script the document.write is working properly.

I want to append it so that i can control the languages for all contents.

Please help. Thanks!

Body:
try putting it inside an script tag or add id on yout label like this

<label for="username" id="username"></label>
<script>
document.getElementById('username').innerHTML = lang.USERNAME;
</script>


问:
facebook through curl auth was failed
I use FB authorization through curl. Till now during a half an year All have been working well. But during the last couple of days I have found a message:</p>

```<code>    [{"error":{"message":"This_authorization_code_has_been_used_","type":"OAuthException","code":100,"fbtrace_id":"HuUHKJv\/zGu"}}] =>
    $params = array(
        'client_id'     => FACEBOOK_ID,
        'redirect_uri'  => PATH_ROOT.REDIRECT_URI,
        'response_type' => 'code',
        'scope'         => 'email, user_birthday'
);
<a href="<?php echo FACEBOOK_OAUTH . '?' . urldecode(http_build_query($params))?>" class="facebook-icon-edit">Change</a>

callback:

if(isset($_GET['code']) and strlen($_GET['code']) > 100){

        $url = 'https://graph.facebook.com/oauth/access_token';
        $tokenInfo = null;

        $token_url = "https://graph.facebook.com/oauth/access_token?"
                . "client_id=" . FACEBOOK_ID . "&redirect_uri=" .      urlencode(PATH_ROOT.REDIRECT_URI)
                . "&client_secret=" . FACEBOOK_SECRET . "&code=" . $_GET['code'];
            $curl = curl_init();
            curl_setopt($curl,CURLOPT_URL, $token_url);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            parse_str(curl_exec($curl), $tokenInfo);
            curl_close($curl);
        echo "```";
        print_r($tokenInfo);
        echo "```";
///the three last rows get the message written above
</code>```

答:
The source of error was that, so far, responce from facebook was a string.
and now bacame as a json one.
so I change

```<code>parse_str(curl_exec($curl), $tokenInfo);
</code>```

to

```<code>$tokenInfo= curl_exec($curl);
$tokenInfo = json_decode($tokenInfo, true);
</code>```

message: this authorization code has been used

this message was appeared may be for a reason of several applying to one page

Title: facebook through curl auth was failed

Body:
I use FB authorization through curl. Till now during a half an year All have been working well. But during the last couple of days I have found a message:

    [{"error":{"message":"This_authorization_code_has_been_used_","type":"OAuthException","code":100,"fbtrace_id":"HuUHKJv\/zGu"}}] =>
    $params = array(
        'client_id'     => FACEBOOK_ID,
        'redirect_uri'  => PATH_ROOT.REDIRECT_URI,
        'response_type' => 'code',
        'scope'         => 'email, user_birthday'
);
<a href="<?php echo FACEBOOK_OAUTH . '?' . urldecode(http_build_query($params))?>" class="facebook-icon-edit">Change

callback:

if(isset($_GET['code']) and strlen($_GET['code']) > 100){

        $url = 'https://graph.facebook.com/oauth/access_token';
        $tokenInfo = null;

        $token_url = "https://graph.facebook.com/oauth/access_token?"
                . "client_id=" . FACEBOOK_ID . "&redirect_uri=" .      urlencode(PATH_ROOT.REDIRECT_URI)
                . "&client_secret=" . FACEBOOK_SECRET . "&code=" . $_GET['code'];
            $curl = curl_init();
            curl_setopt($curl,CURLOPT_URL, $token_url);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            parse_str(curl_exec($curl), $tokenInfo);
            curl_close($curl);
        echo "
";
        print_r($tokenInfo);
        echo "
";
///the three last rows get the message written above

Body:
The source of error was that, so far, responce from facebook was a string.
and now bacame as a json one.
so I change

parse_str(curl_exec($curl), $tokenInfo);

to

$tokenInfo= curl_exec($curl);
$tokenInfo = json_decode($tokenInfo, true);

message: this authorization code has been used

this message was appeared may be for a reason of several applying to one page


问:
Simple Puzzle Algorithm
I develop a (really) simple puzzle game that asks you to join a point A to a B (enter/exit) using a ball and mechanisms that you can rotate to give the correct direction to the ball in order to join the exit.

Here is screenshots of a simple level, showing clearly the purpose of the game:

1) New level started, the mechanisms are rotated in a random way

2) Level is completed, all the mechanisms are rotated properly to give the ball the right path to join the exit

Question:

How can I create an algorithm allowing me to automatically generate levels by taking into account the rotations and leaving only one possibility for the player to complete the level?

I'd also like to add more complexity by adding more mechanisms (to create creating difficulty levels).

I don't think it's necessary to talk about tech, but I'm using C# and Unity.

Let me know if you need more information.

Thank you!

答:
If you look at the second image, the game solution is the broken line starting at "ENTER" and ending at "EXIT".

You can create a new level by creating such a line (randomize the number of 'breaks' and their direction). Then you turn each corner into a rotating mechanism thingy. There will only be one legal solution since you will have to rotate the thingies just the right way.

Title: Simple Puzzle Algorithm


问:
iPad SQLite database
Is it possible to create a table in SQLite which has more than 25000 rows...? I would like to create an iPad application which will work in association with a web application, the web application use MS SQL as back end. Is it possible to fetch large amount of data from MS SQL database..?, If it possible up to how much amount of data can fetch...?</p>

答:
a table in sqlite is limited to 2^64 rows but you'd hit the disk space problems way before that

i've used sqlite on a table having just over 2 million rows which is the most i've put in one

so it's mostly limited by the disk space available

but indexes on a table cost about 0.1 second per 10k inserts per index so really don't put more then is required i tested this with a table of 750 columns and 750 indexes it took hours to put in test data but i was testing extremes most tables will not have that many columns

Title: iPad SQLite database


问:
"Cannot read property 'mergeConfig' of undefined" error while Installing VueJS
On Installing VueJS while running Gulp in Laravel Project, I get following:

```<code>Me-MBP:simpleb2b AdnanAhmad$ gulp build
/Applications/MAMP/htdocs//myProject//node_modules/laravel-elixir-vue/main.js:4
    Elixir.webpack.mergeConfig({
                  ^

TypeError: Cannot read property 'mergeConfig' of undefined
    at /Applications/MAMP/htdocs//myProject/node_modules/laravel-elixir-vue/main.js:4:19
    at /Applications/MAMP/htdocs//myProject//node_modules/laravel-elixir/dist/index.js:29:16
    at Array.forEach (native)
    at global.Elixir (/Applications/MAMP/htdocs//myProject//node_modules/laravel-elixir/dist/index.js:28:24)
    at Object.<anonymous> (/Applications/MAMP/htdocs//myProject//gulpfile.js:16:1)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)
</code>```

答:
Deleting and rebuilding \node_modules didn't change anything for me.

Try

```<code>npm install --save laravel-elixir-webpack-official
</code>```

After this gulp should work.

Body:
On Installing VueJS while running Gulp in Laravel Project, I get following:

Me-MBP:simpleb2b AdnanAhmad$ gulp build
/Applications/MAMP/htdocs//myProject//node_modules/laravel-elixir-vue/main.js:4
    Elixir.webpack.mergeConfig({
                  ^

TypeError: Cannot read property 'mergeConfig' of undefined
    at /Applications/MAMP/htdocs//myProject/node_modules/laravel-elixir-vue/main.js:4:19
    at /Applications/MAMP/htdocs//myProject//node_modules/laravel-elixir/dist/index.js:29:16
    at Array.forEach (native)
    at global.Elixir (/Applications/MAMP/htdocs//myProject//node_modules/laravel-elixir/dist/index.js:28:24)
    at Object.<anonymous> (/Applications/MAMP/htdocs//myProject//gulpfile.js:16:1)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)

Body:
Deleting and rebuilding \node_modules didn't change anything for me.

Try

npm install --save laravel-elixir-webpack-official

After this gulp should work.


问:
Long text going to image backside
When I add a long text, it goes on the back of my icon.
When I try this code

```<code>overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
display: block;
</code>```

It's showing 2 lines only.

答:
Simply add the following style in your CSS.</p>

```<code>overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
display: block;
word-wrap: break-word;
word-break: break-word;
opacity: 100;
</code>```

Title: Long text going to image backside

Body:
When I add a long text, it goes on the back of my icon.
When I try this code

overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
display: block;

It's showing 2 lines only.

Body:
Simply add the following style in your CSS.

overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
display: block;
word-wrap: break-word;
word-break: break-word;
opacity: 100;


答:
You have to use map function, which accepts a callback function.

Also, you should use Object.keys() method in order to get the keys of an object.

var object={"a":1,"b":2,"c":3}
console.log(Object.keys(object).map(function(item){
    return {"option_id": item,"option_value":object[item]};
}));```

Title: How to change the structure of JSON


问:
Cannot execute Git commands from Gradle build script on Windows 10
I have recently forked and cloned a repositroy from GitHub that uses Gradle, but I am unable to execute any Gradle tasks.

It fails on:

```<code>def process = 'git rev-parse --short HEAD'.execute()
</code>```

with:

```<code>FAILURE: Build failed with an exception.
* Where:
Build file 'C:\Users\Joseph\Desktop\Minecraft\ObsidianSuite\ForgeGradle\ForgeGradle\build.gradle' line: 286

* What went wrong:
A problem occurred evaluating root project 'ForgeGradle'.
> Cannot run program "git": CreateProcess error=2, The system cannot find the file specified
</code>```

I am running Windows 10, and have Git working with MinGW. I have set the path variable to include (C:\Program Files\Git\cmd) such that I can run Git from command prompt. The Git command that is called by the build.gradle file executes fine if I run it from the command line, it is just not working when run through the Gradle wrapper.

Any help or advice would be much appreciated; I am able to answer any questions that might help work out what the issue is. Thanks.

EDIT: I normally use Git by running git-bash in the relevant folder rather than git from command prompt.

答:
I have found a solution, it doesn't provide an answer to why it wasn't working originally, but gives a work around. </p>

<p>I followed this answer to install GitHub for Windows and changed the old Git path variable to the one the tutorial suggested. Although I don't want to use the GitHub software (I like doing everything via git-bash), at least Gradle is happy with it now. </p>

Body:
I have recently forked and cloned a repositroy from GitHub that uses Gradle, but I am unable to execute any Gradle tasks.

It fails on:

def process = 'git rev-parse --short HEAD'.execute()

with:

FAILURE: Build failed with an exception.
* Where:
Build file 'C:\Users\Joseph\Desktop\Minecraft\ObsidianSuite\ForgeGradle\ForgeGradle\build.gradle' line: 286

* What went wrong:
A problem occurred evaluating root project 'ForgeGradle'.
> Cannot run program "git": CreateProcess error=2, The system cannot find the file specified

I am running Windows 10, and have Git working with MinGW. I have set the path variable to include (C:\Program Files\Git\cmd) such that I can run Git from command prompt. The Git command that is called by the build.gradle file executes fine if I run it from the command line, it is just not working when run through the Gradle wrapper.

Any help or advice would be much appreciated; I am able to answer any questions that might help work out what the issue is. Thanks.

EDIT: I normally use Git by running git-bash in the relevant folder rather than git from command prompt.

Body:
I have found a solution, it doesn't provide an answer to why it wasn't working originally, but gives a work around.

I followed this answer to install GitHub for Windows and changed the old Git path variable to the one the tutorial suggested. Although I don't want to use the GitHub software (I like doing everything via git-bash), at least Gradle is happy with it now.


问:
Cucumber Step Definition from dependency jars
I have multiple projects using similar step definition across the different projects. Hence using all step definition in single project and added as dependency jar in maven.
When I run using maven command it says :

You can implement missing steps with the snippets below:

```<code>@When("^Import a canvas from \"(.*?)\" to project \"(.*?)\"$")
public void import_a_canvas_from_to_project(String arg1, String arg2) throws Throwable {
 // Write code here that turns the phrase above into concrete actions
  throw new PendingException();
  }
</code>```

but when I add package in same project it works fine. (Even in eclipse from different projects works). Is there any way to run such scenarios from maven and jenkins?

I am using eclipse IDE. maven command I used is :
     mvn -DprofileTest=cucumberID clean -P cucumberID test

cucumberID is my profile name.

Following profile I added in pom.xml

```<code><profile>
<id>cucumberID</id>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <version>2.11</version>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <testFailureIgnore>true</testFailureIgnore>
                    <includes>
                                <include>step_definitions/LoginTest.java</include>
                    </includes>
                    <parallel>classes</parallel>
                    <threadCount>3</threadCount>
                    <useFile>true</useFile>
                </configuration>
            </plugin>
        </plugins>
    </build>
</profile>
</code>```

答:
use classpath: prefix for the package name to solve this.

for example:

@CucumberOptions(glue = { "classpath:com.example.test.steps" })

Body:
I have multiple projects using similar step definition across the different projects. Hence using all step definition in single project and added as dependency jar in maven.
When I run using maven command it says :

You can implement missing steps with the snippets below:

@When("^Import a canvas from \"(.*?)\" to project \"(.*?)\"$")
public void import_a_canvas_from_to_project(String arg1, String arg2) throws Throwable {
 // Write code here that turns the phrase above into concrete actions
  throw new PendingException();
  }

but when I add package in same project it works fine. (Even in eclipse from different projects works). Is there any way to run such scenarios from maven and jenkins?

I am using eclipse IDE. maven command I used is :
     mvn -DprofileTest=cucumberID clean -P cucumberID test

cucumberID is my profile name.

Following profile I added in pom.xml

<profile>
<id>cucumberID</id>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <version>2.11</version>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <testFailureIgnore>true</testFailureIgnore>
                    <includes>
                                <include>step_definitions/LoginTest.java</include>
                    </includes>
                    <parallel>classes</parallel>
                    <threadCount>3</threadCount>
                    <useFile>true</useFile>
                </configuration>
            </plugin>
        </plugins>
    </build>
</profile>


问:
Software-based load-balancing + some of ESB tool for .NET. What are the options? (if any)
I need some piece of software that will fulfill the following functions:

1. Give a single endpoint to a client (abstracting it from several service endpoints)

2. Keep a queue of incoming requests

3. Balance load between several service endpoints on several machines

4. Control availability of these endpoints

5. Give client some readable error when the max CPS or max message queue size are reached

6. Give some msg processing time prediction based on queue size and known service endpoint performance

This thing should be .NET-based and WCF-friendly. I think it is some mixture of load-balancer and ESB.
Can you please name any existing products (OSS projects) of such a type?

答:
That is quite a shopping list. We use an Apache load balancer compiled for Windows 64 bit.
It is simple to set up, cluster, and manage, but you need to use Http/Https as a transport.

It would satisfy items 1, 3, 4 on the list (50% out the box).

On other items, I  am not aware of any existing product, so you would need to write a WCF Router type application to satisfy items 2, 5, 6, but be aware it may not be as robust as something like Apache load balancer.

Cheers


问:
Why am I getting deadlocks? Using Thread, Queue, and ActiveRecord. Ruby 1.9.3, Rails 2.3.18
I mitigate the low success rate of a particular operation by running multiple threads and waiting for the first one to return with a valid answer. I've created a minimal example below:

```<code>THREADS = [] if !defined?(THREADS)

def threadtest
  THREADS.clear
  queue, mutex, result = Queue.new, Mutex.new, nil

  10.times do |i|
    THREADS << Thread.new do
      counted = (10e6 + rand(10e6)).to_i.times { }    # randomize computation time
      num = rand(8)                                   # succeed only 1/8 of the time

      #mutex.synchronize do                           # even if wrapped in mutex
      #  print "#{User.last.inspect}\n"               # deadlocks below if uncommented
      #end

      queue << [num, counted, i]
    end
  end

  10.times do |i|
    result, counted, num = queue.pop                  # deadlocks here

    if result.zero?
      puts "#{i}: #{num} succeeds after #{counted} counts"
      break
    elsif num.present?
      puts "#{i}: #{num} failed with #{result} after #{counted} counts"
    end
  end

  THREADS.each(&:exit)

  return result
end

30.times { threadtest }                               # deadlock happens on "high load"
</code>```

The error looks like:

```<code>fatal: deadlock detected
        from /usr/lib/ruby/1.9.1/thread.rb:189:in `sleep'
        from /usr/lib/ruby/1.9.1/thread.rb:189:in `block in pop'
        from <internal:prelude>:10:in `synchronize'
        from /usr/lib/ruby/1.9.1/thread.rb:184:in `pop'
        from (irb):38:in `block in threadtest'
        from (irb):37:in `times'
        from (irb):37:in `threadtest'
        from (irb):53:in `block in irb_binding'
        from (irb):53:in `times'
        from (irb):53
        from /usr/local/bin/irb:12:in `<main>'
</code>```

I've tried many variations in an attempt to prevent the deadlock, all to no avail. I can detail some of the experimentations I've done so far if requested. I do have one more idea that I've been avoiding due to the amount of refactoring it'd require in my application.

Is it simply the case that ActiveRecord can't be accessed via multiple threads?

I'll update with a few more details as I think of them.

'deadlock detected' error in rails is the the closest related question I found, but it's got no answers.

答:
I had the same error and had to add the

```<code>gem 'net-ssh-gateway'
</code>```

in the file Gemfile.lock, because the version that was bundled didn't work with the installed ruby. Seems like the dependency wasn't resolved any more in the newer ruby version.

Body:
I mitigate the low success rate of a particular operation by running multiple threads and waiting for the first one to return with a valid answer. I've created a minimal example below:

THREADS = [] if !defined?(THREADS)

def threadtest
  THREADS.clear
  queue, mutex, result = Queue.new, Mutex.new, nil

  10.times do |i|
    THREADS << Thread.new do
      counted = (10e6 + rand(10e6)).to_i.times { }    # randomize computation time
      num = rand(8)                                   # succeed only 1/8 of the time

      #mutex.synchronize do                           # even if wrapped in mutex
      #  print "#{User.last.inspect}\n"               # deadlocks below if uncommented
      #end

      queue << [num, counted, i]
    end
  end

  10.times do |i|
    result, counted, num = queue.pop                  # deadlocks here

    if result.zero?
      puts "#{i}: #{num} succeeds after #{counted} counts"
      break
    elsif num.present?
      puts "#{i}: #{num} failed with #{result} after #{counted} counts"
    end
  end

  THREADS.each(&:exit)

  return result
end

30.times { threadtest }                               # deadlock happens on "high load"

The error looks like:

fatal: deadlock detected
        from /usr/lib/ruby/1.9.1/thread.rb:189:in `sleep'
        from /usr/lib/ruby/1.9.1/thread.rb:189:in `block in pop'
        from <internal:prelude>:10:in `synchronize'
        from /usr/lib/ruby/1.9.1/thread.rb:184:in `pop'
        from (irb):38:in `block in threadtest'
        from (irb):37:in `times'
        from (irb):37:in `threadtest'
        from (irb):53:in `block in irb_binding'
        from (irb):53:in `times'
        from (irb):53
        from /usr/local/bin/irb:12:in `'

I've tried many variations in an attempt to prevent the deadlock, all to no avail. I can detail some of the experimentations I've done so far if requested. I do have one more idea that I've been avoiding due to the amount of refactoring it'd require in my application.

Is it simply the case that ActiveRecord can't be accessed via multiple threads?

I'll update with a few more details as I think of them.

'deadlock detected' error in rails is the the closest related question I found, but it's got no answers.

Body:
I had the same error and had to add the

gem 'net-ssh-gateway'

in the file Gemfile.lock, because the version that was bundled didn't work with the installed ruby. Seems like the dependency wasn't resolved any more in the newer ruby version.


问:
Spring CrudRepository Insert values into mysql database
I want to create a @PostMappingwhich executes an insert statement. Here is my code:

Repository (I have findAllBy functions that are working perfectly). Here is the insert function that obviously is not working. ->

```<code>@Transactional
@Query(value = "INSERT INTO recipes(title, description) VALUES (?1, ?2)", nativeQuery = true)
    void insertRecipes(String title, String description);

@PostMapping(path = "/all/create")
public void addRecipes(@RequestParam("title") String title, @RequestParam(value = "description") String description){
    Recipes recipe = new Recipes();
    recipe.setTitle(title);
    recipe.setDescription(description);
    repo.insertRecipes(recipe.getTitle(), recipe.getDescription());
}
</code>```

I don't mention the recipes id because it's auto incremental. And here is my Entity ->

```<code>@Entity
public class Recipes {
@Column(name = "id")
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name = "title")
    private String title;

    @Column(name = "description")
    private String description;

    //getters-setters and constructions below.
}
</code>```

My problem is that I'm getting this exception -> java.sql.SQLException: Can not issue data manipulation statements with executeQuery()

Any ideas?
PS. I have done all the connections correctly. All the GET methods are working fine.

答:
With your code, Spring, and eventually EntityManager creates a Query object on which it invokes one of the query methods. This wont work as your are triggering an insert..

In order for it to invoke the executeUpdate(), which is what you are ultimately aiming for you would have to add @Modifyng annotation.

Body:
I want to create a @PostMappingwhich executes an insert statement. Here is my code:

Repository (I have findAllBy functions that are working perfectly). Here is the insert function that obviously is not working. ->

@Transactional
@Query(value = "INSERT INTO recipes(title, description) VALUES (?1, ?2)", nativeQuery = true)
    void insertRecipes(String title, String description);

@PostMapping(path = "/all/create")
public void addRecipes(@RequestParam("title") String title, @RequestParam(value = "description") String description){
    Recipes recipe = new Recipes();
    recipe.setTitle(title);
    recipe.setDescription(description);
    repo.insertRecipes(recipe.getTitle(), recipe.getDescription());
}

I don't mention the recipes id because it's auto incremental. And here is my Entity ->

@Entity
public class Recipes {
@Column(name = "id")
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name = "title")
    private String title;

    @Column(name = "description")
    private String description;

    //getters-setters and constructions below.
}

My problem is that I'm getting this exception -> java.sql.SQLException: Can not issue data manipulation statements with executeQuery()

Any ideas?
PS. I have done all the connections correctly. All the GET methods are working fine.


问:
c# - DataGridView add row runtime error cell's model
I have a DataGridView component that I use to show some value to the user. It is made of 5 columns: 4 strings and 1 check box. This is my code to create columns and add them to the conrtol:

```<code>// class variables
const int NUM_COLUMNS = 5;
DataGridViewColumn[] columns;
DataGridViewCheckBoxColumn checkColumn;
List <String> columnsHeaderName;

 // init method
 private void init_dataGridView()
    {
        // init all components
        columnsHeaderName = new List<string>();
        columns = new DataGridViewColumn[NUM_COLUMNS - 1]; // minus one becouse last one is a check box column
        checkColumn = new DataGridViewCheckBoxColumn(); // last one
        // columns descriptions
        columnsHeaderName.Add("File path");
        columnsHeaderName.Add("Sampling");
        columnsHeaderName.Add("Start Date");
        columnsHeaderName.Add("End Date");
        columnsHeaderName.Add("Select");

        for (int i = 0; i < NUM_COLUMNS - 1; i++)
        {
            // create, configure and add n-1 columns
            columns[i] = new DataGridViewColumn();
            columns[i].Name = Convert.ToString(i);
            columns[i].HeaderText = columnsHeaderName[i];
            columns[i].ReadOnly = true;
            this.dataGridView1.Columns.Add(columns[i]);
        }
         // create, configure and add last column
        checkColumn.Name = Convert.ToString(NUM_COLUMNS - 1);// (NUM_COLUMNS - 1).ToString();
        checkColumn.HeaderText = columnsHeaderName[NUM_COLUMNS - 1];
        checkColumn.Width = 50;
        checkColumn.ReadOnly = false;
        checkColumn.FillWeight = 10; //if the datagridview is resized (on form resize) the checkbox won't take up too much; value is relative to the other columns' fill values
        this.dataGridView1.Columns.Add(checkColumn);
    }
</code>```

The problem appears when I try to add a new row to my table

```<code> private void LoadFileButton_Click(object sender, EventArgs e)
    {
        string file = "";
        DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
        if (result == DialogResult.OK) // Test result.
        {
           file = openFileDialog1.FileName;
            Console.WriteLine(file);
            dataGridView1.Rows.Add(new object[] { "value 1", "value 2", "value 3", "value 4", true });
        }
    }
</code>```

The call to dataGridView1.Rows.Add() method throws me an exception. The description of the exception is: "At least one of the columns has not any cell's model"

Really I don't understand what I am doing wrong. Hope some ine can help me. Thanks in advance.

答:
Try this</p>

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace stackkcw
{
    public partial class Form1 : Form
    {
        public TcpClient client;
        private DataGridView datgdStock;
        private TextBox lablUpdates;
        private TextBox lablTime;
        private int countOfData;

        DataTable dt = new DataTable();

        public Form1()
        {

            InitializeComponent();
            init_dataGridView();
        }
        const int NUM_COLUMNS = 5;
        DataGridViewColumn[] columns;
        DataGridViewCheckBoxColumn checkColumn;
        List<String> columnsHeaderName;

        // init method
        private void init_dataGridView()
        {
            dt.Columns.Add("File path", typeof(string));
            dt.Columns.Add("Sampling", typeof(decimal));
            dt.Columns.Add("Start Date", typeof(DateTime));
            dt.Columns.Add("End Date", typeof(DateTime));
            dt.Columns.Add("Select", typeof(Boolean));

            dt.Rows.Add(new object[] { "c:\\", 123.45, DateTime.Parse("1/1/2017"), DateTime.Parse("1/2/2017"), true });
            dt.Rows.Add(new object[] { "c:\\", 123.46, DateTime.Parse("1/8/2017"), DateTime.Parse("1/9/2017"), false });
            dt.Rows.Add(new object[] { "c:\\", 123.47, DateTime.Parse("1/15/2017"), DateTime.Parse("1/16/2017"), true });
            dt.Rows.Add(new object[] { "c:\\", 123.48, DateTime.Parse("1/22/2017"), DateTime.Parse("1/23/2017"), false });
            dt.Rows.Add(new object[] { "c:\\", 123.49, DateTime.Parse("1/29/2017"), DateTime.Parse("1/30/2017"), true });

            dataGridView1.DataSource = dt;

        }

    }
}
</code>```

Body:
I have a DataGridView component that I use to show some value to the user. It is made of 5 columns: 4 strings and 1 check box. This is my code to create columns and add them to the conrtol:

// class variables
const int NUM_COLUMNS = 5;
DataGridViewColumn[] columns;
DataGridViewCheckBoxColumn checkColumn;
List <String> columnsHeaderName;

 // init method
 private void init_dataGridView()
    {
        // init all components
        columnsHeaderName = new List<string>();
        columns = new DataGridViewColumn[NUM_COLUMNS - 1]; // minus one becouse last one is a check box column
        checkColumn = new DataGridViewCheckBoxColumn(); // last one
        // columns descriptions
        columnsHeaderName.Add("File path");
        columnsHeaderName.Add("Sampling");
        columnsHeaderName.Add("Start Date");
        columnsHeaderName.Add("End Date");
        columnsHeaderName.Add("Select");

        for (int i = 0; i < NUM_COLUMNS - 1; i++)
        {
            // create, configure and add n-1 columns
            columns[i] = new DataGridViewColumn();
            columns[i].Name = Convert.ToString(i);
            columns[i].HeaderText = columnsHeaderName[i];
            columns[i].ReadOnly = true;
            this.dataGridView1.Columns.Add(columns[i]);
        }
         // create, configure and add last column
        checkColumn.Name = Convert.ToString(NUM_COLUMNS - 1);// (NUM_COLUMNS - 1).ToString();
        checkColumn.HeaderText = columnsHeaderName[NUM_COLUMNS - 1];
        checkColumn.Width = 50;
        checkColumn.ReadOnly = false;
        checkColumn.FillWeight = 10; //if the datagridview is resized (on form resize) the checkbox won't take up too much; value is relative to the other columns' fill values
        this.dataGridView1.Columns.Add(checkColumn);
    }

The problem appears when I try to add a new row to my table

 private void LoadFileButton_Click(object sender, EventArgs e)
    {
        string file = "";
        DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
        if (result == DialogResult.OK) // Test result.
        {
           file = openFileDialog1.FileName;
            Console.WriteLine(file);
            dataGridView1.Rows.Add(new object[] { "value 1", "value 2", "value 3", "value 4", true });
        }
    }

The call to dataGridView1.Rows.Add() method throws me an exception. The description of the exception is: "At least one of the columns has not any cell's model"

Really I don't understand what I am doing wrong. Hope some ine can help me. Thanks in advance.

Body:
Try this

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace stackkcw
{
    public partial class Form1 : Form
    {
        public TcpClient client;
        private DataGridView datgdStock;
        private TextBox lablUpdates;
        private TextBox lablTime;
        private int countOfData;

        DataTable dt = new DataTable();

        public Form1()
        {

            InitializeComponent();
            init_dataGridView();
        }
        const int NUM_COLUMNS = 5;
        DataGridViewColumn[] columns;
        DataGridViewCheckBoxColumn checkColumn;
        List<String> columnsHeaderName;

        // init method
        private void init_dataGridView()
        {
            dt.Columns.Add("File path", typeof(string));
            dt.Columns.Add("Sampling", typeof(decimal));
            dt.Columns.Add("Start Date", typeof(DateTime));
            dt.Columns.Add("End Date", typeof(DateTime));
            dt.Columns.Add("Select", typeof(Boolean));

            dt.Rows.Add(new object[] { "c:\\", 123.45, DateTime.Parse("1/1/2017"), DateTime.Parse("1/2/2017"), true });
            dt.Rows.Add(new object[] { "c:\\", 123.46, DateTime.Parse("1/8/2017"), DateTime.Parse("1/9/2017"), false });
            dt.Rows.Add(new object[] { "c:\\", 123.47, DateTime.Parse("1/15/2017"), DateTime.Parse("1/16/2017"), true });
            dt.Rows.Add(new object[] { "c:\\", 123.48, DateTime.Parse("1/22/2017"), DateTime.Parse("1/23/2017"), false });
            dt.Rows.Add(new object[] { "c:\\", 123.49, DateTime.Parse("1/29/2017"), DateTime.Parse("1/30/2017"), true });

            dataGridView1.DataSource = dt;

        }

    }
}


问:
How to get Xpath for the following?
I have a xml file like following

```<code><topic>
    <title>Abstract
    </title>
    <body>
        <p>
            abstract data
        </p>
    </body>
</topic>
<topic>
    <title>Keywords</title>
    <body>
        <p>
            keywords data
        </p>
    </body>
</topic>
</code>```

I have to check if title is "Keywords" than show the
text in
.
can anyone help me to get the exact xpath for this?
Thanks in advance

答:
Try this one and let me know the result:

```<code>//title[text()="Keywords"]/following::p
</code>```

or

```<code>//topic[title[text()="Keywords"]]//p
</code>```

Title: How to get Xpath for the following?

Body:
I have a xml file like following

<topic>
    <title>Abstract
    </title>

            abstract data

</topic>
<topic>
    <title>Keywords</title>

            keywords data

</topic>

I have to check if title is "Keywords" than show the
text in
.
can anyone help me to get the exact xpath for this?
Thanks in advance

Body:
Try this one and let me know the result:

//title[text()="Keywords"]/following::p

or

//topic[title[text()="Keywords"]]//p


问:
iOS dialogs don't open in app, but in background
After my cordova app is launched on iOS, the authorisation dialogs ("Do you want to grant access to your position?" etc.) do not appear in the app itself, but only open once the app is sent to the background and then reopened. This is obviously unreasonable for the user.

I'm having the same issue with the inAppBrowser, which only triggers once the app is reopened from the background.

Depending on the cordova CLI version I use to build, the results change for the better or worse. No error message anywhere.

Is there any plugin, setting or something else that could cause this behavior?

答:
Answering my own question:
This happened because of a </p>

```<code><meta http-equiv="Content-Security-Policy">
</code>```

<p>in the head of the programm. Removing this fixed the issue and everything works like it should. </p>

Body:
Answering my own question:
This happened because of a

<meta http-equiv="Content-Security-Policy">

in the head of the programm. Removing this fixed the issue and everything works like it should.


问:
Tensorflow: how do I extract/export variable values at every iteration of training?
I have been playing around with some neural networks on Tensorflow and I wanted to make a visualization of the neural network's learning process.
To do so, I intend to extract the following variables into text/JSON/csv: pre-activation result before 1st layer, activation, bias and weight values for testing and training, each layer and for all time steps. I am looking for a generalizable solution so that I don't have to modify my source code (or at least not more than one or two lines) when applying visualization to future networks. Ideally I could run some function from another python program to read any python/TF code and extract the variables described above. So far I have considered the following solutions:
1) use tf.summary and the filewriter to save as a serialized protocol buffer, then find a way to go from protocol buffer --> JSON format. This unfortunately would not fit the bill as it requires me to modify too much inner code.
2) Perhaps using https://www.tensorflow.org/api_docs/python/tf/train/export_meta_graph
Although I am not sure how to implement given my TF foundations are not quite there yet
3) I have also found this solution:

```<code>W_val, b_val= sess.run([W, b])
np.savetxt("W1.csv", W_val, delimiter=",")
np.savetxt("b1.csv", b_val, delimiter=",")
</code>```

But the problem is that it only saves the final values of the weights and biases, whereas I am looking to save their values at all timesteps of training.

If anyone has any suggestions on how to tackle this problem or any guidance I would appreciate it.

Many thanks

答:
Doing it with tf.Summaries is probably a good idea. You could then visualize it all in Tesnorboard, much like with some of the tutorials and the inception retraining code.
Alternatively you could perform fetches within your sess.run() call to grab whatever tensors you like at every step (i.e. every run call).

I have pasted a response to a similar question regarding extracting the cross entropy from another question below:
When you do your session run call (e.g. res = sess.run(...) ) then you can put in a fetch for your cross entropy variable.

For example, let's say you have a complicated sess.run() call that gets some predictions but you also want to your cross entropy then you may have code that looks like this:

```<code>feeds={x_data:x,y_data:y}
fetches=[y_result,cross_entropy]
res=sess.run(fetches=fetches, feed_dict=feeds) predictions=res[0]
#your first fetch parameter xent=res[1] #Your second fetch parameter.
</code>```

Fetches within the run call allows you to "fetch" tensors from your graph.

You should be able to do the above but instead of cross entropy, just a list of whatever you want. I use it to fetch both my summaries and also intermediate accuracy values.

Body:
I have been playing around with some neural networks on Tensorflow and I wanted to make a visualization of the neural network's learning process.
To do so, I intend to extract the following variables into text/JSON/csv: pre-activation result before 1st layer, activation, bias and weight values for testing and training, each layer and for all time steps. I am looking for a generalizable solution so that I don't have to modify my source code (or at least not more than one or two lines) when applying visualization to future networks. Ideally I could run some function from another python program to read any python/TF code and extract the variables described above. So far I have considered the following solutions:
1) use tf.summary and the filewriter to save as a serialized protocol buffer, then find a way to go from protocol buffer --> JSON format. This unfortunately would not fit the bill as it requires me to modify too much inner code.
2) Perhaps using https://www.tensorflow.org/api_docs/python/tf/train/export_meta_graph
Although I am not sure how to implement given my TF foundations are not quite there yet
3) I have also found this solution:

W_val, b_val= sess.run([W, b])
np.savetxt("W1.csv", W_val, delimiter=",")
np.savetxt("b1.csv", b_val, delimiter=",")

But the problem is that it only saves the final values of the weights and biases, whereas I am looking to save their values at all timesteps of training.

If anyone has any suggestions on how to tackle this problem or any guidance I would appreciate it.

Many thanks

Body:
Doing it with tf.Summaries is probably a good idea. You could then visualize it all in Tesnorboard, much like with some of the tutorials and the inception retraining code.
Alternatively you could perform fetches within your sess.run() call to grab whatever tensors you like at every step (i.e. every run call).

I have pasted a response to a similar question regarding extracting the cross entropy from another question below:
When you do your session run call (e.g. res = sess.run(...) ) then you can put in a fetch for your cross entropy variable.

For example, let's say you have a complicated sess.run() call that gets some predictions but you also want to your cross entropy then you may have code that looks like this:

feeds={x_data:x,y_data:y}
fetches=[y_result,cross_entropy]
res=sess.run(fetches=fetches, feed_dict=feeds) predictions=res[0]
#your first fetch parameter xent=res[1] #Your second fetch parameter.

Fetches within the run call allows you to "fetch" tensors from your graph.

You should be able to do the above but instead of cross entropy, just a list of whatever you want. I use it to fetch both my summaries and also intermediate accuracy values.