问:
how to avoid printk log dropping in linux kernel
Is there any tips or method to avoid kernel log drop or log buffer overrun ?

I have increased the log buffer size to maximum with below code change. I'm running in high end device only. But, still when when i want to get the complete log from my driver(which writes heavy logs), I see the printk logs are dropped sometimes. I use printk with KERN_INFO, gets enabled through dynamic debug(dprintk).

Change i do:

```<code>--- a/kernel/printk.c
+++ b/kernel/printk.c
@@ -55,7 +55,7 @@ void asmlinkage __attribute__((weak)) early_printk(const char *fmt, ...)
 {
 }

-#define __LOG_BUF_LEN  (1 << CONFIG_LOG_BUF_SHIFT)
+#define __LOG_BUF_LEN  (1 << 17)
</code>```

Command i use to write into a file:

```<code>cat "/proc/kmsg">/sdcard/klog.txt
</code>```

Only While debugging, I'm okay if the performance is degraded in my driver but, i don't want  drop any logs. I understand we can't make work queues/threads to wait until printing completes. But, still is there any way to get guaranteed that, logs are not dropped.

答:
Easy, just add "printk.synchronous=1" to kernel cmdline.

The printk() has became completely async now. You can add printk.synchronous=1 to let printk() be sync.

Refer to the patch "printk: Make printk() completely async":

Currently, printk() sometimes waits for message to be printed to
  console and sometimes it does not (when console_sem is held by some
  other process). In case printk() grabs console_sem and starts printing
  to console, it prints messages from kernel printk buffer until the
  buffer is empty. When serial console is attached, printing is slow and
  thus other CPUs in the system have plenty of time to append new
  messages to the buffer while one CPU is printing. Thus the CPU can
  spend unbounded amount of time doing printing in console_unlock().
  This is especially serious problem if the printk() calling
  console_unlock() was called with interrupts disabled.

In practice users have observed a CPU can spend tens of seconds
  printing in console_unlock() (usually during boot when hundreds of
  SCSI devices are discovered) resulting in RCU stalls (CPU doing
  printing doesn't reach quiescent state for a long time), softlockup
  reports (IPIs for the printing CPU don't get served and thus other
  CPUs are spinning waiting for the printing CPU to process IPIs), and
  eventually a machine death (as messages from stalls and lockups append
  to printk buffer faster than we are able to print). So these machines
  are unable to boot with serial console attached. Another observed
  issue is that due to slow printk, hardware discovery is slow and udev
  times out before kernel manages to discover all the attached HW. Also
  during artificial stress testing SATA disk disappears from the system
  because its interrupts aren't served for too long.

This patch makes printk() completely asynchronous (similar to what
  printk_deferred() did until now). It appends message to the kernel
  printk buffer and wake_up()s a special dedicated kthread to do the
  printing to console. This has the advantage that printing always
  happens from a schedulable contex and thus we don't lockup any
  particular CPU or even interrupts. Also it has the advantage that
  printk() is fast and thus kernel booting is not slowed down by slow
  serial console. Disadvantage of this method is that in case of crash
  there is higher chance that important messages won't appear in console
  output (we may need working scheduling to print message to console).
  We somewhat mitigate this risk by switching printk to the original
  method of immediate printing to console if oops is in progress.

Async printk, for the time being, is considered to be less reliable
  than the synchronous one, so by default we keep printk operating in
  synchronous mode. There is a printk.synchronous kernel parameter which
  permits to select sync/async mode as a boot parameter or later on from
  user space via sysfs knob.

printk() is expected to work under different conditions and in
  different scenarios, including corner cases of OOM when all of the
  workers are busy (e.g. allocating memory), thus printk() uses its own
  dedicated printing kthread, rather than relying on workqueue (even
  with WQ_MEM_RECLAIM bit set we potentially can receive delays in
  printing until workqueue declares a ->mayday, as noted by Tetsuo
  Handa).

Body:
Is there any tips or method to avoid kernel log drop or log buffer overrun ?

I have increased the log buffer size to maximum with below code change. I'm running in high end device only. But, still when when i want to get the complete log from my driver(which writes heavy logs), I see the printk logs are dropped sometimes. I use printk with KERN_INFO, gets enabled through dynamic debug(dprintk).

Change i do:

--- a/kernel/printk.c
+++ b/kernel/printk.c
@@ -55,7 +55,7 @@ void asmlinkage __attribute__((weak)) early_printk(const char *fmt, ...)
 {
 }

-#define __LOG_BUF_LEN  (1 << CONFIG_LOG_BUF_SHIFT)
+#define __LOG_BUF_LEN  (1 << 17)

Command i use to write into a file:

cat "/proc/kmsg">/sdcard/klog.txt

Only While debugging, I'm okay if the performance is degraded in my driver but, i don't want  drop any logs. I understand we can't make work queues/threads to wait until printing completes. But, still is there any way to get guaranteed that, logs are not dropped.


来源: stackexchange

问:
Laravel: How to handle dependency when deleting from database
I want to create an admin page for deleting images.

In admin.blade.php:

```<code>@if (Auth::check())
@foreach ($images as $image)
<img height='100px' width='100px' src="storage/images/{{$image->file_path}}" alt="Image {{ $image->file_path }}"></p>
<form action="image/{{$image->id}}/delete" method="post">
<button type="submit">Delete image</button>
<br>
@endforeach
@else
<p>Login first</p>
@endif
</code>```

In routes/web.php:

```<code>//deleting images
Route::post('image/{id}/delete', 'ImageController@destroy');
</code>```

In App/Http/Controllers/ImageController.php:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Image;
class ImageController extends Controller
{
    public function destroy($id)
    {
        $image = Image::findOrFail($id);
        $image->delete();

        return redirect('admin');
    }
}
</code>```

Upon clicking the Delete image-button, I get this lengthy error message:

```<code>QueryException in Connection.php line 647:
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`retellgram`.`captions`, CONSTRAINT `captions_image_id_foreign` FOREIGN KEY (`image_id`) REFERENCES `images` (`id`)) (SQL: delete from `images` where `id` = 1)
</code>```

Why does this happen?

EDIT: Migrations for Images and Captions, as requested in the comments.

From 2017_03_10_080608_Create_Image_Table.php:

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateImageTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->increments('id');
            $table->string('file_path');
            $table->string('md5')->index();
            $table->integer('likes')->default(0);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('images');
    }
}
</code>```

From 2017_03_20_1104_35_create_caption_table.php:

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCaptionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('captions', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('image_id')->unsigned();
            $table->foreign('image_id')->references('id')->on('images');

            $table->string('content');
            $table->integer('likes')->default(0);
            $table->boolean('approved')->default(false);

            $table->integer('character_id')->unsigned();
            $table->foreign('character_id')->references('id')->on('characters');

            $table->timestamps();

        });

        Schema::create('caption_hashtag', function (Blueprint $table) {
            $table->integer('caption_id')->unsigned()->index();
            $table->foreign('caption_id')->references('id')->on('captions')->onDelete('cascade');

            $table->integer('hashtag_id')->unsigned()->index();
            $table->foreign('hashtag_id')->references('id')->on('hashtags')->onDelete('cascade');

            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('caption_hashtag');
        Schema::dropIfExists('captions');
    }
}
</code>```

答:
You are getting the error as there are foreign keys for images in other tables (eg. captions).

Just add onDelete behaviour to the migrations.

```<code>Schema::create('captions', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('image_id')->unsigned();
    $table->foreign('image_id')
          ->references('id')
          ->on('images')
          ->onDelete('cascade'); // delete related caption
    ...
</code>```

Also, you mention in the comment that you have 'likestable with a foreign key ofimages. Do the same forlikes` migration.

Finally, rollback your migrations and run them again. This should create new tables. Then try adding and deleting an image.

ContentLicense: CC BY-SA 3.0

Body:
I want to create an admin page for deleting images.

In admin.blade.php:

@if (Auth::check())
@foreach ($images as $image)
file_path}}" alt="Image {{ $image->file_path }}">

<form action="image/{{$image->id}}/delete" method="post">
<button type="submit">Delete image</button>

@endforeach
@else

Login first

@endif

In routes/web.php:

//deleting images
Route::post('image/{id}/delete', 'ImageController@destroy');

In App/Http/Controllers/ImageController.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Image;
class ImageController extends Controller
{
    public function destroy($id)
    {
        $image = Image::findOrFail($id);
        $image->delete();

        return redirect('admin');
    }
}

Upon clicking the Delete image-button, I get this lengthy error message:

QueryException in Connection.php line 647:
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`retellgram`.`captions`, CONSTRAINT `captions_image_id_foreign` FOREIGN KEY (`image_id`) REFERENCES `images` (`id`)) (SQL: delete from `images` where `id` = 1)

Why does this happen?

EDIT: Migrations for Images and Captions, as requested in the comments.

From 2017_03_10_080608_Create_Image_Table.php:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateImageTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->increments('id');
            $table->string('file_path');
            $table->string('md5')->index();
            $table->integer('likes')->default(0);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('images');
    }
}

From 2017_03_20_1104_35_create_caption_table.php:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCaptionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('captions', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('image_id')->unsigned();
            $table->foreign('image_id')->references('id')->on('images');

            $table->string('content');
            $table->integer('likes')->default(0);
            $table->boolean('approved')->default(false);

            $table->integer('character_id')->unsigned();
            $table->foreign('character_id')->references('id')->on('characters');

            $table->timestamps();

        });

        Schema::create('caption_hashtag', function (Blueprint $table) {
            $table->integer('caption_id')->unsigned()->index();
            $table->foreign('caption_id')->references('id')->on('captions')->onDelete('cascade');

            $table->integer('hashtag_id')->unsigned()->index();
            $table->foreign('hashtag_id')->references('id')->on('hashtags')->onDelete('cascade');

            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('caption_hashtag');
        Schema::dropIfExists('captions');
    }
}

Body:
You are getting the error as there are foreign keys for images in other tables (eg. captions).

Just add onDelete behaviour to the migrations.

Schema::create('captions', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('image_id')->unsigned();
    $table->foreign('image_id')
          ->references('id')
          ->on('images')
          ->onDelete('cascade'); // delete related caption
    ...

Also, you mention in the comment that you have 'likestable with a foreign key ofimages. Do the same forlikes` migration.

Finally, rollback your migrations and run them again. This should create new tables. Then try adding and deleting an image.


问:
AVCaptureSession returning blank image on iphone 4
I am trying to call the 'media capture putting it all together' example from AVFoundation Programming Guide. I keep getting a blank (black) image. Is there anything I need to call first to have this code access the camera?
thanks

This is unmodified code from the example:

```<code>-(void) setupCapture {
AVCaptureSession *session = [[AVCaptureSession alloc] init];
session.sessionPreset = AVCaptureSessionPresetLow;

AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (!input) {
    // Handle the error appropriately.
    NSLog(@"no input");
    return;
}
[session addInput:input];

AVCaptureVideoDataOutput *output = [[[AVCaptureVideoDataOutput alloc] init] autorelease];
[session addOutput:output];
output.videoSettings = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA]
                                                   forKey:(id)kCVPixelBufferPixelFormatTypeKey];
output.minFrameDuration = CMTimeMake(1, 15);

dispatch_queue_t queue = dispatch_queue_create("MyQueue", NULL);
[output setSampleBufferDelegate:self queue:queue];
dispatch_release(queue);

[session startRunning];
}

UIImage *imageFromSampleBuffer(CMSampleBufferRef sampleBuffer) {
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
// Lock the base address of the pixel buffer.
CVPixelBufferLockBaseAddress(imageBuffer,0);

// Get the number of bytes per row for the pixel buffer.
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
// Get the pixel buffer width and height.
size_t width = CVPixelBufferGetWidth(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);

// Create a device-dependent RGB color space.
static CGColorSpaceRef colorSpace = NULL;
if (colorSpace == NULL) {
    colorSpace = CGColorSpaceCreateDeviceRGB();
    if (colorSpace == NULL) {
        // Handle the error appropriately.
        return nil;
    }
}

// Get the base address of the pixel buffer.
void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);
// Get the data size for contiguous planes of the pixel buffer.
size_t bufferSize = CVPixelBufferGetDataSize(imageBuffer);

// Create a Quartz direct-access data provider that uses data we supply.
CGDataProviderRef dataProvider =
CGDataProviderCreateWithData(NULL, baseAddress, bufferSize, NULL);
// Create a bitmap image from data supplied by the data provider.
CGImageRef cgImage =
CGImageCreate(width, height, 8, 32, bytesPerRow,
              colorSpace, kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little,
              dataProvider, NULL, true, kCGRenderingIntentDefault);
CGDataProviderRelease(dataProvider);

// Create and return an image object to represent the Quartz image.
UIImage *image = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);

CVPixelBufferUnlockBaseAddress(imageBuffer, 0);

return image;
}
</code>```

and my callback method is:

```<code>- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
   fromConnection:(AVCaptureConnection *)connection {

UIImage *image = imageFromSampleBuffer(sampleBuffer);
NSLog(@"am I nil?: %@", image);
self.imageV.image = image;
[self.view setNeedsDisplay];
}
</code>```

答:
tip 1:
  do not start capturesession in main viewDidLoad method, but a little later
tip 2:
  do not update your ui in the capturesession callback method, do it on the main thread.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am trying to call the 'media capture putting it all together' example from AVFoundation Programming Guide. I keep getting a blank (black) image. Is there anything I need to call first to have this code access the camera?
thanks

This is unmodified code from the example:

-(void) setupCapture {
AVCaptureSession *session = [[AVCaptureSession alloc] init];
session.sessionPreset = AVCaptureSessionPresetLow;

AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (!input) {
    // Handle the error appropriately.
    NSLog(@"no input");
    return;
}
[session addInput:input];

AVCaptureVideoDataOutput *output = [[[AVCaptureVideoDataOutput alloc] init] autorelease];
[session addOutput:output];
output.videoSettings = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA]
                                                   forKey:(id)kCVPixelBufferPixelFormatTypeKey];
output.minFrameDuration = CMTimeMake(1, 15);

dispatch_queue_t queue = dispatch_queue_create("MyQueue", NULL);
[output setSampleBufferDelegate:self queue:queue];
dispatch_release(queue);

[session startRunning];
}

UIImage *imageFromSampleBuffer(CMSampleBufferRef sampleBuffer) {
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
// Lock the base address of the pixel buffer.
CVPixelBufferLockBaseAddress(imageBuffer,0);

// Get the number of bytes per row for the pixel buffer.
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
// Get the pixel buffer width and height.
size_t width = CVPixelBufferGetWidth(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);

// Create a device-dependent RGB color space.
static CGColorSpaceRef colorSpace = NULL;
if (colorSpace == NULL) {
    colorSpace = CGColorSpaceCreateDeviceRGB();
    if (colorSpace == NULL) {
        // Handle the error appropriately.
        return nil;
    }
}

// Get the base address of the pixel buffer.
void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);
// Get the data size for contiguous planes of the pixel buffer.
size_t bufferSize = CVPixelBufferGetDataSize(imageBuffer);

// Create a Quartz direct-access data provider that uses data we supply.
CGDataProviderRef dataProvider =
CGDataProviderCreateWithData(NULL, baseAddress, bufferSize, NULL);
// Create a bitmap image from data supplied by the data provider.
CGImageRef cgImage =
CGImageCreate(width, height, 8, 32, bytesPerRow,
              colorSpace, kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little,
              dataProvider, NULL, true, kCGRenderingIntentDefault);
CGDataProviderRelease(dataProvider);

// Create and return an image object to represent the Quartz image.
UIImage *image = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);

CVPixelBufferUnlockBaseAddress(imageBuffer, 0);

return image;
}

and my callback method is:

- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
   fromConnection:(AVCaptureConnection *)connection {

UIImage *image = imageFromSampleBuffer(sampleBuffer);
NSLog(@"am I nil?: %@", image);
self.imageV.image = image;
[self.view setNeedsDisplay];
}


问:
vue , can we send request parameter for vue template
Want to send parameters(like http GET/POST paramaters ) to the vue template.
How can we do this and where in (webpack or vue)</p>

答:
First of all, it depends on your library, I am using vue-resource, because I find it easy to use and compatible with Vue semantically.

If you want to send a URL argument in a GET, it is simple.

```<code>// Trashs a task, won't delete from db.
TrashTask: function (taskIndex, taskID, category) {
  this.$http.delete('/task/' + taskID).then(response => response.json()).then(result => {
    this.tasks.splice(taskIndex, 1);
    this.notify("Task deleted");
    this.UpdateCategoryCount(category, "-", 1);
  }).catch(err => {
    console.log(err);
    this.notify("Unable to trash Tash");
  });
},
</code>```

POST/PUT arguments are a bit different though.

First, define your data, here, we are sending the this.task. In the $http.put, the second argument is the data which you pass, the third argument is {emulateJSON: true}, that way, the JSON gets converted into your normal parameters like name=sh&age=25.

If you want to read more: https://github.com/thewhitetulip/intro-to-vuejs/blob/master/5_interacting_with_backend.md

Complete code:  https://github.com/thewhitetulip/Tasks-vue/blob/master/public/static/js/app.js#L227

```<code>AddTask: function (item) {
  this.$http.put('/task/', this.task, {
    emulateJSON: true
  }).then(response => response).then(result => {
    if (this.task.ishidden == false) {
      this.tasks.push(this.task);
    }

    this.UpdateCategoryCount(this.task.category, "+", 1);

    this.task = {
      title: '',
      content: '',
      category: '',
      priority: '',
      comments: [],
      showComment: false
    }
  }).catch(err => {
    console.log(err);
    this.notify("Unable to add Task");
  });
  $('#addNoteModal').modal('hide');
},
</code>```

Body:
First of all, it depends on your library, I am using vue-resource, because I find it easy to use and compatible with Vue semantically.

If you want to send a URL argument in a GET, it is simple.

// Trashs a task, won't delete from db.
TrashTask: function (taskIndex, taskID, category) {
  this.$http.delete('/task/' + taskID).then(response => response.json()).then(result => {
    this.tasks.splice(taskIndex, 1);
    this.notify("Task deleted");
    this.UpdateCategoryCount(category, "-", 1);
  }).catch(err => {
    console.log(err);
    this.notify("Unable to trash Tash");
  });
},

POST/PUT arguments are a bit different though.

First, define your data, here, we are sending the this.task. In the $http.put, the second argument is the data which you pass, the third argument is {emulateJSON: true}, that way, the JSON gets converted into your normal parameters like name=sh&age=25.

If you want to read more: https://github.com/thewhitetulip/intro-to-vuejs/blob/master/5_interacting_with_backend.md

Complete code:  https://github.com/thewhitetulip/Tasks-vue/blob/master/public/static/js/app.js#L227

AddTask: function (item) {
  this.$http.put('/task/', this.task, {
    emulateJSON: true
  }).then(response => response).then(result => {
    if (this.task.ishidden == false) {
      this.tasks.push(this.task);
    }

    this.UpdateCategoryCount(this.task.category, "+", 1);

    this.task = {
      title: '',
      content: '',
      category: '',
      priority: '',
      comments: [],
      showComment: false
    }
  }).catch(err => {
    console.log(err);
    this.notify("Unable to add Task");
  });
  $('#addNoteModal').modal('hide');
},


问:
How can I append one list to another where Indices match in Python?
I have two lists :

```<code>List1 = [['ab' , 'bc' ] , ['ef' , 'ij' ]]
List2 = [['pq' , 'rs' ] , ['uv' , 'xy' ]]
</code>```

I want a list that looks like this:

```<code>FinalList = [['ab', 'bc', 'pq', 'rs'], ['ef', 'ij', 'uv', 'xy']]
</code>```

Elements in the first position of List1 must be appended to elements in first position of list 2 , elements in second position of list 1 must be appended to elements in second position of list 2 and so on.

Thanks!

Body:
I have two lists :

List1 = [['ab' , 'bc' ] , ['ef' , 'ij' ]]
List2 = [['pq' , 'rs' ] , ['uv' , 'xy' ]]

I want a list that looks like this:

FinalList = [['ab', 'bc', 'pq', 'rs'], ['ef', 'ij', 'uv', 'xy']]

Elements in the first position of List1 must be appended to elements in first position of list 2 , elements in second position of list 1 must be appended to elements in second position of list 2 and so on.

Thanks!

Body:
Use below code too,

List1 = [['ab' , 'bc' ] , ['ef' , 'ij' ]]
List2 = [['pq' , 'rs' ] , ['uv' , 'xy' ]]

Finallist = [List1[0]+List2[0]]+[List1[1]+List2[1]]


问:
How to process files in nested directories?
I'm trying to make my JavaScript files a little smaller.

I've got a javascripts/ directory, and then a _website/javascripts/ directory where my static assets get compiled. Inside of the javascripts/ directory I have a few nested directories for polyfills, libraries and so on, and then files for my site.

How can I recursively iterate through all the nested directories of javascripts/ and pump out minified, compressed, but not concatenated files into my _website/javascripts/ directory?

Here's the code I have so far. Ideally I can do this in an npm script. It's totally cool if it only works on Linux for now.

```<code>find scripts/ -name '*.js' -print0 | xargs -0 uglifyjs
</code>```

And then I don't know how to pass the inputs to each xargs execution as names for the --output flag of uglifyjs.

How do I do this with xargs? Is it the {} notion?

答:
To recursively iterate, you can use the globstar option on a newer version of bash:

```<code>#!/bin/bash
shopt -s globstar
shopt -s nullglob

for file in javascripts/**/*.js
do
    name=$(basename "$file")
    uglifyjs "$file" > "_website/javascripts/$name"
done
</code>```

Also you were missing a semicolon before do (necessary if your code is on one line) and missing the done at the end.

Body:
I'm trying to make my JavaScript files a little smaller.

I've got a javascripts/ directory, and then a _website/javascripts/ directory where my static assets get compiled. Inside of the javascripts/ directory I have a few nested directories for polyfills, libraries and so on, and then files for my site.

How can I recursively iterate through all the nested directories of javascripts/ and pump out minified, compressed, but not concatenated files into my _website/javascripts/ directory?

Here's the code I have so far. Ideally I can do this in an npm script. It's totally cool if it only works on Linux for now.

find scripts/ -name '*.js' -print0 | xargs -0 uglifyjs

And then I don't know how to pass the inputs to each xargs execution as names for the --output flag of uglifyjs.

How do I do this with xargs? Is it the {} notion?

Body:
To recursively iterate, you can use the globstar option on a newer version of bash:

#!/bin/bash
shopt -s globstar
shopt -s nullglob

for file in javascripts/**/*.js
do
    name=$(basename "$file")
    uglifyjs "$file" > "_website/javascripts/$name"
done

Also you were missing a semicolon before do (necessary if your code is on one line) and missing the done at the end.


问:
extract values in array and create variable php
Hi Stackoverflow and programmer!

I have this code :

```<code>$result = print_r($reponse, true);

echo $result;
</code>```

Wich give me this output :

```<code>Array ( [333212] => Array ( [view] => 323 [sold] => 3 [buy] => 43 [number] => 333212 ) )
</code>```

I need to find a way to have something like :

```<code>echo $variable['view']; (323)

echo $variable['buy']; (3)

echo $variable['sold']; (43)
</code>```

I check and try a lot of things like extract(); serialize(); dumb_var i try explode("")  i search a little everywhere but dint find answer.

Thanks a lot for the help ! much apreciated !!!

Pierre-luc

答:
```<code>$reponse = array(); //Replace with your array

echo $reponse['view'];
//Returns: 323
</code>```

Body:
Hi Stackoverflow and programmer!

I have this code :

$result = print_r($reponse, true);

echo $result;

Wich give me this output :

Array ( [333212] => Array ( [view] => 323 [sold] => 3 [buy] => 43 [number] => 333212 ) )

I need to find a way to have something like :

echo $variable['view']; (323)

echo $variable['buy']; (3)

echo $variable['sold']; (43)

I check and try a lot of things like extract(); serialize(); dumb_var i try explode("")  i search a little everywhere but dint find answer.

Thanks a lot for the help ! much apreciated !!!

Pierre-luc


问:
How best store year, month, and day in a MySQL database?
How best store year, month, and day in a MySQL database so that it would be easily retrieved by year, by year-month, by year-month-day combinations?</p>

答:
If you're doing analytics against a fixed range of dates consider using a date dimension (fancy name for table) and use a foreign key into the date dimension. Check out this link:

http://www.ipcdesigns.com/dim_date/

If you use this date dimension consider how easily it will be to construct queries against any kind of dates you can think of.

```<code>SELECT * FROM my_table
JOIN DATE_DIM date on date.PK = my_table.date_FK
WHERE date.day = 30 AND
      date.month = 1 AND
      date.year = 2010
</code>```

Or

```<code>SELECT * FROM my_table
JOIN DATE_DIM date on date.PK = my_table.date_FK
WHERE date.day_of_week = 1 AND
      date.month = 1 AND
      date.year = 2010
</code>```

Or

```<code>SELECT *, date.day_of_week_name FROM my_table
JOIN DATE_DIM date on date.PK = my_table.date_FK
WHERE date.is_US_civil_holiday = 1
</code>```

Body:
If you're doing analytics against a fixed range of dates consider using a date dimension (fancy name for table) and use a foreign key into the date dimension. Check out this link:

http://www.ipcdesigns.com/dim_date/

If you use this date dimension consider how easily it will be to construct queries against any kind of dates you can think of.

SELECT * FROM my_table
JOIN DATE_DIM date on date.PK = my_table.date_FK
WHERE date.day = 30 AND
      date.month = 1 AND
      date.year = 2010

Or

SELECT * FROM my_table
JOIN DATE_DIM date on date.PK = my_table.date_FK
WHERE date.day_of_week = 1 AND
      date.month = 1 AND
      date.year = 2010

Or

SELECT *, date.day_of_week_name FROM my_table
JOIN DATE_DIM date on date.PK = my_table.date_FK
WHERE date.is_US_civil_holiday = 1


问:
Jekyll or Hugo theme with multilanguage support
I'd like to start designing a website using Jekyll or Hugo. The plan is to publish it on GitHub or GitLab pages.

After hours of searching I'm pretty confused about all the facts. Hugo support natively a multilanguage utility while Jekyll not. There are some plugins for Jekyll but plugins are not supported on GitHub pages anyway.

With Jekyll I tried to follow this solution without any concrete solution for the translation of the layouts while with Hugo I've found the instruction pretty confused (but that's my fault).

What I'm looking for is a theme (Jekyll or Hugo it doesn't matter) that is already designed with 2 (or more) languages.

答:
Beside the official Hugo instructions for creating a multilingual site, you also have:

multilingual examples which has been recently updated

multilingual mode

themes with multilingual already baked in as (from the Hugo themes list site):

hugo-scriptor-theme

dimension

docuapi

Plus, with Hugo 0.87 (Aug. 2021), you also have Date/time formatting layouts and localized string for the current language.

ContentLicense: CC BY-SA 4.0


问:
Segmentation Fault with DataFrame.to_json()
I have a Python code that works correctly with a file having 20 rows, but when I'm trying to send the same file with 60.000 records, it shows a "108936 Segmentation fault".

Is there any way to avoid this error, is this my machine? or there is a better way to do this? I'm using Pandas because I need to do a merge to the DataFrame sometimes (pd.merge()).

Here is my code:

```<code>import pandas as pd
import json

columns = [u'SalesOrderID', u'OrderDate', u'DueDate', u'ShipDate', u'SalesOrderNumber', u'Title', u'FirstName', u'MiddleName', u'LastName', u'Suffix', u'PhoneNumber', u'PhoneNumberType', u'EmailAddress', u'EmailPromotion', u'AddressType', u'AddressLine1', u'AddressLine2', u'City', u'StateProvinceName', u'PostalCode', u'CountryRegionName', u'SubTotal', u'TaxAmt', u'Freight', u'TotalDue', u'UnitPrice', u'ProductName', u'ProductSubcategory', u'ProductCategory']
data = pd.read_csv('../Uploads/TxtData.txt', header=0, names=columns, sep='\t')
data.to_json(orient='records')
</code>```

Files used:

Little File

Big File

答:
There is a known issue in DataFrame.to_json.

https://github.com/pandas-dev/pandas/issues/14256#issuecomment-249583941

The only current way to account for this is to us a default_handler for converting your objects to standard json datatypes. I don't know what is in txt.data and I don't know what could possibly be in a csv file that is exotic enough, but you need a default_handler.

Body:
I have a Python code that works correctly with a file having 20 rows, but when I'm trying to send the same file with 60.000 records, it shows a "108936 Segmentation fault".

Is there any way to avoid this error, is this my machine? or there is a better way to do this? I'm using Pandas because I need to do a merge to the DataFrame sometimes (pd.merge()).

Here is my code:

import pandas as pd
import json

columns = [u'SalesOrderID', u'OrderDate', u'DueDate', u'ShipDate', u'SalesOrderNumber', u'Title', u'FirstName', u'MiddleName', u'LastName', u'Suffix', u'PhoneNumber', u'PhoneNumberType', u'EmailAddress', u'EmailPromotion', u'AddressType', u'AddressLine1', u'AddressLine2', u'City', u'StateProvinceName', u'PostalCode', u'CountryRegionName', u'SubTotal', u'TaxAmt', u'Freight', u'TotalDue', u'UnitPrice', u'ProductName', u'ProductSubcategory', u'ProductCategory']
data = pd.read_csv('../Uploads/TxtData.txt', header=0, names=columns, sep='\t')
data.to_json(orient='records')

Files used:

Little File

Big File


问:
ms-access shorten vba code
I'm using the following code alot in my project:

```<code>txtVoornaam.Locked = False
txtVoornaam.BorderStyle = 4
txtVoornaam.BorderColor = RGB(255, 165, 0

txtAchternaam.Locked = False
txtAchternaam.BorderStyle = 4
txtAchternaam.BorderColor = RGB(255, 165, 0)

txtAfdeling.Locked = False
txtAfdeling.BorderStyle = 4
txtAfdeling.BorderColor = RGB(255, 165, 0)
</code>```

I wonder if there is a way to not display this in my code or shorten this. The code gets very long if i use this a few times..

答:
if your controls are the same, obviously put them in a single sub/function that you can call from anywhere. i would not try to lock or change the format of textboxes, instead just enable/disable, and it will handle the format for you:

textbox.enabled = true/false

if you are doing this on multiple forms and really want a single sub/function to control enabling/disabling the textboxes on each form, then there are various ways of doing that as well, solution will depend on your needs, but certainly doable and some have already commented above.

for example, you can use the "tag" property of the textboxes to flag the textboxes on that form that you want to enable/disable. you can then have a single sub/function that would take in the form as reference, and then you can read the "tag" property of all textboxes on that form and if they are the ones you flagged, you would proceed to enable/disable them

Title: ms-access shorten vba code

Body:
I'm using the following code alot in my project:

txtVoornaam.Locked = False
txtVoornaam.BorderStyle = 4
txtVoornaam.BorderColor = RGB(255, 165, 0

txtAchternaam.Locked = False
txtAchternaam.BorderStyle = 4
txtAchternaam.BorderColor = RGB(255, 165, 0)

txtAfdeling.Locked = False
txtAfdeling.BorderStyle = 4
txtAfdeling.BorderColor = RGB(255, 165, 0)

I wonder if there is a way to not display this in my code or shorten this. The code gets very long if i use this a few times..


问:
Difference between FetchType LAZY and EAGER in Java Persistence API?
What is the difference between FetchType.LAZY and FetchType.EAGER in Java Persistence API?

答:
LAZY: It fetches the child entities lazily i.e at the time of fetching parent entity it just fetches proxy(created by cglib or any other utility) of the child entities and when you access any property of child entity then it is actually fetched by hibernate.

EAGER: it fetches the child entities along with parent.

For better understanding go to Jboss documentation or you can use hibernate.show_sql=true for your app and check the queries issued by the hibernate.


问:
ERROR ITMS-90512: Invalid sdk value... 8.2 is higher than maximum allowed value of 10.3?
Trying to upload a binary, which includes a watch app.  The error I'm getting (which I wasn't getting a couple days ago) is the value provided for LC_VERSION_MIN_IPHONEOS for the watchkit extension is 8.2 which is greater than the maximum allowed value of 10.3... apparently 8.2 > 10.3?

I'm updated to the latest XCode, 8.3, that didn't fix the problem.  Tried changing the iOS deployment target for the watch app and extension, no apparent effect on the message.

答:
EDIT: Although successfully uploaded to iTunes Connect, when trying to submit a Testflight beta build, still got rejected by the same message

Invalid sdk value. The value provided for the sdk portion of
  LC_VERSION_MIN_IPHONEOS in XXX.app/PlugIns/XXX WatchKit
  Extension.appex/XXX WatchKit App.app/XXX WatchKit App is 8.2
  which is greater than the maximum allowed value of 10.3.

Guess Apple's still working on it...

I am having this issue earlier, also with a watchOS1 target in my project.

I've tried to upload the binary again few minutes ago, no more warning shows, and passed the processing of iTunes Connect.

Everybody having this issue should give it a try!


问:
Python 3.x : Jupyter Notebook and Pandas
I have a got problem in my Pandas. I want to group my pcap file by ip_src, but it wasn't shown.

```<code>import pandas as pd
df = pd.read_csv("C:\Anaconda\esktrak_uji_1.csv")
df

g = df.groupby('ip_src')
g
for ip_src, df.ip_src in g:
    print (ip_src)
    print (df.ip_src)
</code>```

Jupyter Notebook image:

答:
```<code>for n,g in df.groupby('ip_src'):
    print(n)
    print(g)
</code>```

To do a sort on df:

```<code>df.sort_values(by='ip_src')
</code>```

Examples of some summary stats:

```<code>df.groupby('ip_src').agg({'no_paket':{'Sum':'sum'},'ip_dst':{'Count Distinct':'nunique'},'ttl':{'Mean':'mean'}})
</code>```

Body:
I have a got problem in my Pandas. I want to group my pcap file by ip_src, but it wasn't shown.

import pandas as pd
df = pd.read_csv("C:\Anaconda\esktrak_uji_1.csv")
df

g = df.groupby('ip_src')
g
for ip_src, df.ip_src in g:
    print (ip_src)
    print (df.ip_src)

Jupyter Notebook image:

Body:
for n,g in df.groupby('ip_src'):
    print(n)
    print(g)

To do a sort on df:

df.sort_values(by='ip_src')

Examples of some summary stats:

df.groupby('ip_src').agg({'no_paket':{'Sum':'sum'},'ip_dst':{'Count Distinct':'nunique'},'ttl':{'Mean':'mean'}})


问:
How to have a Text Area in my Web application?
I want to make a blog page in my web application. I want to have a large text area to enter atleast 300 words in my blog page. it should have spell check. making bold option. It should be like the s*ame window in StackOverFlow where am entering my question now*.

How to achieve this. Any suggestions Please?

答: Checkout mootools version of WSIWYG editor.  It is very lightweight and simple.  http://cheeaun.github.com/mooeditable/  build from javascript framework Mootools</p>


问:
aws cli get error "The security token included in the request is invalid"
I did aws configure and test it worked before. But it didn't work today, I got the the error when tried to get hosted zone

```<code> $ aws route53 list-hosted-zones

 An error occurred (InvalidClientTokenId) when calling the ListHostedZones operation: The security token included in the request is invalid.
</code>```

I deleted ~/.aws and did aws configure again, but I still got the same error.
Could you please help? Thanks!

答:
Do you have MFA enabled on your account?  You might have to run </p>

```<code>aws sts get-session-token
</code>```

<p>Details for how to use MFA with the cli are documented here. </p>

Body:
I did aws configure and test it worked before. But it didn't work today, I got the the error when tried to get hosted zone

 $ aws route53 list-hosted-zones

 An error occurred (InvalidClientTokenId) when calling the ListHostedZones operation: The security token included in the request is invalid.

I deleted ~/.aws and did aws configure again, but I still got the same error.
Could you please help? Thanks!

Body:
Do you have MFA enabled on your account?  You might have to run

aws sts get-session-token

Details for how to use MFA with the cli are documented here.


问:
Read a mixed encoding json file in python
I have a json file with following contents

```<code>{
"2ndStrike": {
    "SECONDSTKE_FIGHT_BUTTON": "攻撃を続ける",
    "SECONDSTKE_RESOURCE_DESC": "残り資源",
    "SECONDSTKE_RESOURCE_REM1": "残りの資源を得るため小隊を修理し戦闘を続けろ：",
    "SECONDSTKE_RESOURCE_REM2": "悪名を高めるためにも戦い続け、この基地を破壊しろ！",
    "SECONDSTKE_SURR_BUTTON": "降伏",
    "SECONDSTKE_TITLE": "敗北"
},
"AccountManagementUI": {
    "CHOOSE_BASE_AGE_{x}": "{x} 日目",
    "CHOOSE_BASE_CC_LEVEL_{x}": "CC レベル {x}",
    "CHOOSE_BASE_CONFIRM_MESSAGE": "本当にこれから全てのデバイスでこの基地を使用しますか？",
    "CHOOSE_BASE_CONTINUE_BUTTON": "続ける",
    "CHOOSE_BASE_DESCRIPTION": "この{social_network}アカウントには2つの基地が存在してます。基地の数は一人のプレイヤーにつき一つに限定されています。基地を選択するか、キャンセルしてください。",
    "CHOOSE_BASE_LEVEL_{x}": "レベル {x}",
    "CHOOSE_BASE_LOCKED_BUTTON": "基地の選択",
    "CHOOSE_BASE_PANEL_TITLE": "アクティブな基地の選択"
}
}
</code>```

I want to extract the occurences of all the unique non-English characters in this file . Could anyone tell me how to do that?

Body:
I have a json file with following contents

{
"2ndStrike": {
    "SECONDSTKE_FIGHT_BUTTON": "攻撃を続ける",
    "SECONDSTKE_RESOURCE_DESC": "残り資源",
    "SECONDSTKE_RESOURCE_REM1": "残りの資源を得るため小隊を修理し戦闘を続けろ：",
    "SECONDSTKE_RESOURCE_REM2": "悪名を高めるためにも戦い続け、この基地を破壊しろ！",
    "SECONDSTKE_SURR_BUTTON": "降伏",
    "SECONDSTKE_TITLE": "敗北"
},
"AccountManagementUI": {
    "CHOOSE_BASE_AGE_{x}": "{x} 日目",
    "CHOOSE_BASE_CC_LEVEL_{x}": "CC レベル {x}",
    "CHOOSE_BASE_CONFIRM_MESSAGE": "本当にこれから全てのデバイスでこの基地を使用しますか？",
    "CHOOSE_BASE_CONTINUE_BUTTON": "続ける",
    "CHOOSE_BASE_DESCRIPTION": "この{social_network}アカウントには2つの基地が存在してます。基地の数は一人のプレイヤーにつき一つに限定されています。基地を選択するか、キャンセルしてください。",
    "CHOOSE_BASE_LEVEL_{x}": "レベル {x}",
    "CHOOSE_BASE_LOCKED_BUTTON": "基地の選択",
    "CHOOSE_BASE_PANEL_TITLE": "アクティブな基地の選択"
}
}

I want to extract the occurences of all the unique non-English characters in this file . Could anyone tell me how to do that?

Body:
You can still use json.load, it will work the same as any other normal ascii strings.

import json
data = json.load(open("yourfilename.json"))

If you couldn't print the data on screen, it's a whole different topic.

If you only want to count the time a single char occur, you can do this:

import re, collections
with open("/users/apple/desktop/me.txt", 'rb') as data:
    counted = collections.Counter(re.findall('[^\x00-\x7F]', data.read().decode(), re.UNICODE))
print(counted)

Output:

Counter({'の': 10, 'を': 8, '基': 7, '地': 7, 'る': 5, 'し': 5, 'に': 5, '続': 4, 'け': 4, 'こ': 4, 'て': 4, 'す': 4, 'め': 3, 'い': 3, 'レ': 3, 'ル': 3, 'か': 3, 'ま': 3, 'つ': 3, '。': 3, '選': 3, '択': 3, '残': 2, 'り': 2, '資': 2, '源': 2, 'た': 2, '戦': 2, 'ろ': 2, '、': 2, 'ベ': 2, 'れ': 2, 'イ': 2, 'ア': 2, 'ン': 2, 'は': 2, '一': 2, 'さ': 2, '攻': 1, '撃': 1, '得': 1, '小': 1, '隊': 1, '修': 1, '理': 1, '闘': 1, '：': 1, '悪': 1, '名': 1, '高': 1, 'も': 1, '破': 1, '壊': 1, '！': 1, '降': 1, '伏': 1, '敗': 1, '北': 1, '日': 1, '目': 1, '本': 1, '当': 1, 'ら': 1, '全': 1, 'デ': 1, 'バ': 1, 'ス': 1, 'で': 1, '使': 1, '用': 1, '？': 1, 'カ': 1, 'ウ': 1, 'ト': 1, 'が': 1, '存': 1, '在': 1, '数': 1, '人': 1, 'プ': 1, 'ヤ': 1, 'ー': 1, 'き': 1, '限': 1, '定': 1, 'キ': 1, 'ャ': 1, 'セ': 1, 'く': 1, 'だ': 1, 'ク': 1, 'テ': 1, 'ィ': 1, 'ブ': 1, 'な': 1})


问:
python object oriented programming methods
I have defined the below code but there seems to be issues regarding methods load and damage.

(edited based on suggestions by ShadowRanger):

```<code>class RangedWeapon(Weapon):
        def __init__(self, name, min_dmg, max_dmg):
            super().__init__(name, min_dmg, max_dmg)
            self.shots=0

        def shots_left(self):
            return self.shots

        def load(self, ammo):
            if ammo.weapon_type()==self.name:
                self.shots+=ammo.get_quantity()
                ammo.remove_all()

        def damage(self):
            if self.shots==0:
                return 0
            else:
                self.shots-=1
                return super().damage()
</code>```

_

```<code>bow = RangedWeapon('bow', 10, 40)
crossbow = RangedWeapon('crossbow', 15, 45)
arrows = Ammo('arrow', bow, 5)
bolts = Ammo('bolt', crossbow, 10)

bow.load(arrows)
print(bow.shots_left()) # should return 5
print(arrows.get_quantity()) #should return 0
</code>```

But for print(bow.shots_left()) I got 0 and print(arrows.get_quantity()) I got 5 instead. They are reversed. I think my problem is that I didn't load the Ammo quantity? I'm not very sure. Any help would be appreciated. Thank you!

```<code>class Ammo(Thing):
    def __init__(self, name, weapon, quantity):
        self.name=name
        self.weapon=weapon
        self.quantity=quantity

    def get_quantity(self):
        return self.quantity

    def weapon_type(self):
        return self.weapon.name

    def remove_all(self):
        self.quantity=0
</code>```

答:
Primary problem: Ammo's weapon_type is a method, not an attribute or property, and you didn't call it, so you're comparing the method itself to the name, not the result of calling it. This is the reason why load does nothing; no method is ever equal to a string.

Other issues:

It looks like you're calling methods on the class, not on the instances. You pass ammo (an instance) as an argument, then call methods on Ammo (the class).

Similarly, your damage method should probably be calling super().damage() not Weapon.damage(), since the latter doesn't use your instance state. And you've got typos (shots vs. shot) that should make this code non-functional in other ways.

Short version: This code is broken in a million ways, and you'll run into each of them as you fix the previous issues.

Body:
I have defined the below code but there seems to be issues regarding methods load and damage.

(edited based on suggestions by ShadowRanger):

class RangedWeapon(Weapon):
        def __init__(self, name, min_dmg, max_dmg):
            super().__init__(name, min_dmg, max_dmg)
            self.shots=0

        def shots_left(self):
            return self.shots

        def load(self, ammo):
            if ammo.weapon_type()==self.name:
                self.shots+=ammo.get_quantity()
                ammo.remove_all()

        def damage(self):
            if self.shots==0:
                return 0
            else:
                self.shots-=1
                return super().damage()

_

bow = RangedWeapon('bow', 10, 40)
crossbow = RangedWeapon('crossbow', 15, 45)
arrows = Ammo('arrow', bow, 5)
bolts = Ammo('bolt', crossbow, 10)

bow.load(arrows)
print(bow.shots_left()) # should return 5
print(arrows.get_quantity()) #should return 0

But for print(bow.shots_left()) I got 0 and print(arrows.get_quantity()) I got 5 instead. They are reversed. I think my problem is that I didn't load the Ammo quantity? I'm not very sure. Any help would be appreciated. Thank you!

class Ammo(Thing):
    def __init__(self, name, weapon, quantity):
        self.name=name
        self.weapon=weapon
        self.quantity=quantity

    def get_quantity(self):
        return self.quantity

    def weapon_type(self):
        return self.weapon.name

    def remove_all(self):
        self.quantity=0


问:
TypeError: 'tuple' object cannot be interpreted as an integer"
I'm trying to make a super basic evolution simulator to generate ten random "creatures" that are each a number value and then give them a random "mutation" but it keeps throwing me this error: "for i in range(creatures):
TypeError: 'tuple' object cannot be interpreted as an integer"</p>

```<code>import random
from random import randint

creatures = (random.randint(1, 10), random.randint(1, 10))

print(creatures)

for i in range(creatures):
    mutation = random.randint(1, 2)
    newEvolution = creatures[i] + mutation

print("New evolution", newEvolution)
</code>```

答:
The creatures is a tuple and range() function as an argument takes integers.

```<code>Syntax for range:
range([start], stop[, step])

start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
step: Difference between each number in the sequence.

Note that:
All parameters must be integers.
</code>```

the solution:

```<code>import random
creatures = random.sample(range(1, 11), 10)
print(creatures)

newEvolution = []
for i in range(len(creatures)):
    mutation = random.randint(1, 2)
    newEvolution.append(creatures[i] + mutation)

print("New evolution", newEvolution)
</code>```

Body:
I'm trying to make a super basic evolution simulator to generate ten random "creatures" that are each a number value and then give them a random "mutation" but it keeps throwing me this error: "for i in range(creatures):
TypeError: 'tuple' object cannot be interpreted as an integer"

import random
from random import randint

creatures = (random.randint(1, 10), random.randint(1, 10))

print(creatures)

for i in range(creatures):
    mutation = random.randint(1, 2)
    newEvolution = creatures[i] + mutation

print("New evolution", newEvolution)

Body:
The creatures is a tuple and range() function as an argument takes integers.

Syntax for range:
range([start], stop[, step])

start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
step: Difference between each number in the sequence.

Note that:
All parameters must be integers.

the solution:

import random
creatures = random.sample(range(1, 11), 10)
print(creatures)

newEvolution = []
for i in range(len(creatures)):
    mutation = random.randint(1, 2)
    newEvolution.append(creatures[i] + mutation)

print("New evolution", newEvolution)


问:
Responsive design: Mobile version of site shows full version while loading
I'm trying to build mobile version of my website using CSS and jQuery. Website works fine but when page is still loading on mobile browser, it shows full version of website for a second then shows mobile version when page is fully loaded. Last time even I made different website for mobile for same domain name using:

```<code>if($(window).width()<500){window.loacation('mobile.webtsite.com')}
</code>```

still I have the same problem.
But this time what I am doing is:

```<code> if($(window).width()<500){
        $("#linkCss").attr('href','styles/mobile.css');
        var high=$(window).height()*60/100;
</code>```

答:
Just call your function before the document ready statement.

```<code><script>
   thisWillFireImmediately();

   $(function() {
      thisWillFireOnDocumentReady();
   });
</script>
</code>```

for more infos: Running jQuery code before the DOM is ready?

Body:
I'm trying to build mobile version of my website using CSS and jQuery. Website works fine but when page is still loading on mobile browser, it shows full version of website for a second then shows mobile version when page is fully loaded. Last time even I made different website for mobile for same domain name using:

if($(window).width()<500){window.loacation('mobile.webtsite.com')}

still I have the same problem.
But this time what I am doing is:

 if($(window).width()<500){
        $("#linkCss").attr('href','styles/mobile.css');
        var high=$(window).height()*60/100;

Body:
Just call your function before the document ready statement.

<script>
   thisWillFireImmediately();

   $(function() {
      thisWillFireOnDocumentReady();
   });
</script>

for more infos: Running jQuery code before the DOM is ready?


问:
database and asp.net
My goal is to connect to my database either manually or using an sqladapater, and get information from two of my databases on sql server 2005.
Then I want to take this information and on run-time begin to add/subtract/divide/multiply certain columns and place the information into other columns. I can do this in queries, however, I want to do it on run-time what is the best way to achieve this.
I had some of this working, but I just want to start fresh and see how you would go about doing this.

```<code>Partial Class _Default
    Inherits System.Web.UI.Page
    Public cmd As New SqlCommand()
    Public da As New SqlDataAdapter(cmd)
  conn string here.....
    Dim ds As New DataSet

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        cmd.Connection = conn
        conn.Open()

        ' Dim ds As New DataSet
        Dim x As New DataTable

        cmd.CommandText = "SELECT B603SalesAsOFMASTER.DIVISION, B603SalesAsOFMASTER.SDESCR, B603SalesAsOFMASTER.DYYYY, B603SalesAsOFMASTER.AsOFSales, B603SalesAsOFMASTER.ASOFPAX, B603SalesAsOFMASTER.YESales, B603SalesAsOFMASTER.YEPAX, B603SalesAsOFMASTER.PCTofSales, B603SalesAsOFMASTER.PCTofPAX, B601SalesAsOF.Sales AS [Current Sales], B601SalesAsOF.PAX AS [Current PAX], B601SalesAsOF.Sales / B601SalesAsOF.PAX AS [AVG PAX], B601SalesAsOF.Sales / B603SalesAsOFMASTER.PCTofSales AS [Projected Year End] FROM B603SalesAsOFMASTER INNER JOIN B601SalesAsOF ON B603SalesAsOFMASTER.SDESCR = B601SalesAsOF.SDESCR WHERE (B603SalesAsOFMASTER.DYYYY = '2008') AND (B601SalesAsOF.DYYYY = '2010')"
        'da.Fill(ds)
        da.Fill(x)

        GridView1.DataSource = x

        GridView1.DataBind()

        da.FillSchema(ds, SchemaType.Mapped)

        conn.Close()
    End Sub

End Class
</code>```

That is what i am playing around with right now, some of my calculations are done directly in the sql command, but i want to change this.

答:
Create a Data Access Layer (DAL)
2 - Sqlconnections, one for each db
Use a sqlreader if you are just reading data and an adapter if you need to make changes.
Use either a sql string or stored procedures to retrieve your 'uncalculated' data, but make sure they are parametarized if you plan on allowing the user interface to do any filtering.

*Study up on avoiding SQL Injection

Create a Business Logic Layer
This is where you can take the data from the DAL and do your calculations.

Presentation Layer
Looks like this is going to be a web page(s) with a grid viewer or maybe a repeater control based on your needs. Here are some ideas to get you going: http://msdn.microsoft.com/en-us/library/bb498211.aspx

Title: database and asp.net

Body:
My goal is to connect to my database either manually or using an sqladapater, and get information from two of my databases on sql server 2005.
Then I want to take this information and on run-time begin to add/subtract/divide/multiply certain columns and place the information into other columns. I can do this in queries, however, I want to do it on run-time what is the best way to achieve this.
I had some of this working, but I just want to start fresh and see how you would go about doing this.

Partial Class _Default
    Inherits System.Web.UI.Page
    Public cmd As New SqlCommand()
    Public da As New SqlDataAdapter(cmd)
  conn string here.....
    Dim ds As New DataSet

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        cmd.Connection = conn
        conn.Open()

        ' Dim ds As New DataSet
        Dim x As New DataTable

        cmd.CommandText = "SELECT B603SalesAsOFMASTER.DIVISION, B603SalesAsOFMASTER.SDESCR, B603SalesAsOFMASTER.DYYYY, B603SalesAsOFMASTER.AsOFSales, B603SalesAsOFMASTER.ASOFPAX, B603SalesAsOFMASTER.YESales, B603SalesAsOFMASTER.YEPAX, B603SalesAsOFMASTER.PCTofSales, B603SalesAsOFMASTER.PCTofPAX, B601SalesAsOF.Sales AS [Current Sales], B601SalesAsOF.PAX AS [Current PAX], B601SalesAsOF.Sales / B601SalesAsOF.PAX AS [AVG PAX], B601SalesAsOF.Sales / B603SalesAsOFMASTER.PCTofSales AS [Projected Year End] FROM B603SalesAsOFMASTER INNER JOIN B601SalesAsOF ON B603SalesAsOFMASTER.SDESCR = B601SalesAsOF.SDESCR WHERE (B603SalesAsOFMASTER.DYYYY = '2008') AND (B601SalesAsOF.DYYYY = '2010')"
        'da.Fill(ds)
        da.Fill(x)

        GridView1.DataSource = x

        GridView1.DataBind()

        da.FillSchema(ds, SchemaType.Mapped)

        conn.Close()
    End Sub

End Class

That is what i am playing around with right now, some of my calculations are done directly in the sql command, but i want to change this.


问:
Search and replace text using Regex in IntelliJ
I am using the latest version of the IntelliJ Idea 2017.1

In my project I have many calls to this function

foo.bar(x)

I want to search and replace this to x.toFoo

The problem is that X can be anything. it can be any variable, it can be a long function call. So we don't really know the pattern for x.

I tried this regex

foo.bar(\S+) but this doesn't work as it selects many other things.

I also tried foo.bar(\()(.*)(\)) this seems to select the right thing. but at the time of replacing. how do I remember to capture whatever was there in .*?

Example

```<code>foo.bar(myobj.copy(myid = hisId))
</code>```

this should become

```<code>myobj.copy(myid = hisId).toFoo
</code>```

another example can be

```<code>foo.bar(List(1, 2, 3))

List(1, 2, 3).toFoo
</code>```

答:
Since your string can have nested parenthesis, I would have suggested using recursion:

```<code>foo\.bar(\(([^()]|(?1))*\))
</code>```

Live preview

However IntelliJ doesn't support that (actually haven't seen any IDE supporting recursion).

So instead you can use:

```<code>foo\.bar[^\(]*(\(.*\))[^\)]*?
</code>```

Live preview

Which given this:

```<code>foo.bar()
foo.bar(1, 2, 3)
foo.bar(1, (2 + (3 + 4)), 5)
</code>```

You didn't give any example, so I just made some containing nested parenthesis.

Results in:

```<code>().toFoo
(1, 2, 3).toFoo
(1, (2 + (3 + 4)), 5).toFoo
</code>```

Body:
I am using the latest version of the IntelliJ Idea 2017.1

In my project I have many calls to this function

foo.bar(x)

I want to search and replace this to x.toFoo

The problem is that X can be anything. it can be any variable, it can be a long function call. So we don't really know the pattern for x.

I tried this regex

foo.bar(\S+) but this doesn't work as it selects many other things.

I also tried foo.bar(\()(.*)(\)) this seems to select the right thing. but at the time of replacing. how do I remember to capture whatever was there in .*?

Example

foo.bar(myobj.copy(myid = hisId))

this should become

myobj.copy(myid = hisId).toFoo

another example can be

foo.bar(List(1, 2, 3))

List(1, 2, 3).toFoo

Body:
Since your string can have nested parenthesis, I would have suggested using recursion:

foo\.bar(\(([^()]|(?1))*\))

Live preview

However IntelliJ doesn't support that (actually haven't seen any IDE supporting recursion).

So instead you can use:

foo\.bar[^\(]*(\(.*\))[^\)]*?

Live preview

Which given this:

foo.bar()
foo.bar(1, 2, 3)
foo.bar(1, (2 + (3 + 4)), 5)

You didn't give any example, so I just made some containing nested parenthesis.

Results in:

().toFoo
(1, 2, 3).toFoo
(1, (2 + (3 + 4)), 5).toFoo


问:
Swift StompClient Vs SockJS not consistent behavior during connection
I am using StompClient (https://github.com/ShengHuaWu/StompClient) to connect my iOS (swift 3) app to a stomp socket that is hosted in a Spring container.

It seems when using sockjs from a web browser, and connect to ws:/server/topic_name, it automatically adds a server_id and a session_id to the url (ws://server/server_id/socket_id/topic_name).

When I use the Swift StompClient, it doesn't seem to add these additional items to the path.

anyone know how get around this?

答:
Sockjs is designed for use in browsers, since WebSocket is not supported in all browsers yet. The url you mentioned above is the part of the sockjs protocol.

iOS has the native support for WebSocket. So you don't need to rely on sockjs. There are Stomp libraries like this one you can use https://github.com/mobile-web-messaging/StompKit.

One thing to notice is that, if you are using Spring container, and provided that you have the configuration blow in your application context:

```<code>    <websocket:stomp-endpoint path="/spring-websocket-portfolio/portfolio" allowed-origins="*">
        <websocket:sockjs/>
    </websocket:stomp-endpoint>
</code>```

You should connect to ws://localhost/spring-websocket-portfolio/portfolio/websocket.

Body:
Sockjs is designed for use in browsers, since WebSocket is not supported in all browsers yet. The url you mentioned above is the part of the sockjs protocol.

iOS has the native support for WebSocket. So you don't need to rely on sockjs. There are Stomp libraries like this one you can use https://github.com/mobile-web-messaging/StompKit.

One thing to notice is that, if you are using Spring container, and provided that you have the configuration blow in your application context:

    <websocket:stomp-endpoint path="/spring-websocket-portfolio/portfolio" allowed-origins="*">
        <websocket:sockjs/>
    </websocket:stomp-endpoint>

You should connect to ws://localhost/spring-websocket-portfolio/portfolio/websocket.


问:
Universal Reactjs with Nashorn and Tomcat
For my current project I'm trying to create a universal reactjs website. My current server architecture restricts me to only use Tomcat application servers. Installing a nodejs server is not an option.

As a POC I use an example repository (https://github.com/pgrimard/spring-boot-react) that contains react with react-router that renders on the server. While running this example I get the following error:

```<code>org.springframework.scripting.support.StandardScriptEvalException: TypeError: 0 ,> u.createServerRenderContext is not a function in <eval> at line number 1
</code>```

This error happens in the server.js file while setting up the react-router context. Does anyone have any experience with bigger react application within a Tomcat container and that use SSR? Or are there any other solutions?

Thanks in advance!

答:
I published an article about using nashorn to do react SSR. https://medium.com/@jimmy_shen/use-nashorn-engine-to-do-server-side-rendering-with-react-eba835e33d77 or 使用Nashorn Engine进行React Server-Side Rendering

The key is the polyfill to Nashorn about XmlHttpRequest and WebAPI. nashorn-polyfill will do it.

And you may check out Demo. The app is with stack of React, Apollo, React-Router v4.

Body:
For my current project I'm trying to create a universal reactjs website. My current server architecture restricts me to only use Tomcat application servers. Installing a nodejs server is not an option.

As a POC I use an example repository (https://github.com/pgrimard/spring-boot-react) that contains react with react-router that renders on the server. While running this example I get the following error:

org.springframework.scripting.support.StandardScriptEvalException: TypeError: 0 ,> u.createServerRenderContext is not a function in <eval> at line number 1

This error happens in the server.js file while setting up the react-router context. Does anyone have any experience with bigger react application within a Tomcat container and that use SSR? Or are there any other solutions?

Thanks in advance!


问:
Joining two dataframes
I have a dataframe that looks like this:

```<code>RIC | base
AAPL| AA
IBM |
AMD |
</code>```

and another table with same fields but different values:

```<code>RIC | base
AAPL | AA
IBM |
AMD | AM
</code>```

I would like to join the two tables to get this resultant table:

```<code>RIC | base
AAPL | AA
IBM |
AMD | AM
</code>```

How can I do that?

答:
Do you notice that your desired result is the same as your second dataframe?

I think you meant something like this:

Consider the two dataframes d1 and d2

```<code>d1 = pd.DataFrame(dict(RIC=['AAPL', 'IBM', 'AMD'], base=['AA', None, None]))
d2 = pd.DataFrame(dict(RIC=['AAPL', 'IBM', 'AMD'], base=['aa', 'IB', 'AM']))

print(d1)
print()
print(d2)

    RIC  base
0  AAPL    AA
1   IBM  None
2   AMD  None

    RIC base
0  AAPL   aa
1   IBM   IB
2   AMD   AM
</code>```

We'll use set_index and combine_first

```<code>d1.set_index('RIC').combine_first(d2.set_index('RIC')).reset_index()

    RIC base
0  AAPL   AA
1   IBM   IB
2   AMD   AM
</code>```

This approach takes the values from the first dataframe when it exists.  Otherwise, it takes the value from the second dataframe.

Title: Joining two dataframes

Body:
I have a dataframe that looks like this:

RIC | base
AAPL| AA
IBM |
AMD |

and another table with same fields but different values:

RIC | base
AAPL | AA
IBM |
AMD | AM

I would like to join the two tables to get this resultant table:

RIC | base
AAPL | AA
IBM |
AMD | AM

How can I do that?

Body:
Do you notice that your desired result is the same as your second dataframe?

I think you meant something like this:

Consider the two dataframes d1 and d2

d1 = pd.DataFrame(dict(RIC=['AAPL', 'IBM', 'AMD'], base=['AA', None, None]))
d2 = pd.DataFrame(dict(RIC=['AAPL', 'IBM', 'AMD'], base=['aa', 'IB', 'AM']))

print(d1)
print()
print(d2)

    RIC  base
0  AAPL    AA
1   IBM  None
2   AMD  None

    RIC base
0  AAPL   aa
1   IBM   IB
2   AMD   AM

We'll use set_index and combine_first

d1.set_index('RIC').combine_first(d2.set_index('RIC')).reset_index()

    RIC base
0  AAPL   AA
1   IBM   IB
2   AMD   AM

This approach takes the values from the first dataframe when it exists.  Otherwise, it takes the value from the second dataframe.


问:
How to check if input is an enumeration type
I am reading input from the keyboard. The input is supposed to match one of the elements defined in an enumeration type. Here is an example of the enum type:

```<code>type NameType is (Bob, Jamie, Steve);
</code>```

If I receive an input that is not one of these 3, Ada raises an IO exception. How do I handle this to where I can simply display a "try again" message and not have the program stop?

答:
Create an instance of Enumeration_IO for Name_Type, say Name_IO. In a loop, enter a nested block to handle any Data_Error that arises. When Name_IO.Get succeeds, exit the loop.

```<code>with Ada.IO_Exceptions;
with Ada.Text_IO;

procedure Ask is

type Name_Type is (Bob, Jamie, Steve);
package Name_IO is new Ada.Text_IO.Enumeration_IO (Name_Type);

begin
   loop
      declare
         Name : Name_Type;
      begin
         Ada.Text_IO.Put("Enter a name: ");
         Name_IO.Get(Name);
         exit;
      exception
         when Ada.IO_Exceptions.Data_Error =>
            Ada.Text_IO.Put_Line("Unrecognized name; try again.");
      end;
   end loop;
end Ask;
</code>```

Alternative approaches include these:

Name_Type'Value, defined here and illustrated here.

Enumeration_IO.Get, defined here and discussed here.

Body:
I am reading input from the keyboard. The input is supposed to match one of the elements defined in an enumeration type. Here is an example of the enum type:

type NameType is (Bob, Jamie, Steve);

If I receive an input that is not one of these 3, Ada raises an IO exception. How do I handle this to where I can simply display a "try again" message and not have the program stop?

Body:
Create an instance of Enumeration_IO for Name_Type, say Name_IO. In a loop, enter a nested block to handle any Data_Error that arises. When Name_IO.Get succeeds, exit the loop.

with Ada.IO_Exceptions;
with Ada.Text_IO;

procedure Ask is

type Name_Type is (Bob, Jamie, Steve);
package Name_IO is new Ada.Text_IO.Enumeration_IO (Name_Type);

begin
   loop
      declare
         Name : Name_Type;
      begin
         Ada.Text_IO.Put("Enter a name: ");
         Name_IO.Get(Name);
         exit;
      exception
         when Ada.IO_Exceptions.Data_Error =>
            Ada.Text_IO.Put_Line("Unrecognized name; try again.");
      end;
   end loop;
end Ask;

Alternative approaches include these:

Name_Type'Value, defined here and illustrated here.

Enumeration_IO.Get, defined here and discussed here.


问:
How can I turn a DataTable to a CSV?
Could somebody please tell me why the following code is not working.  The data is saved into the csv file, however the data is not separated.  It all exists within the first cell of each row.

```<code>StringBuilder sb = new StringBuilder();

foreach (DataColumn col in dt.Columns)
{
    sb.Append(col.ColumnName + ',');
}

sb.Remove(sb.Length - 1, 1);
sb.Append(Environment.NewLine);

foreach (DataRow row in dt.Rows)
{
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        sb.Append(row[i].ToString() + ",");
    }

    sb.Append(Environment.NewLine);
}

File.WriteAllText("test.csv", sb.ToString());
</code>```

Thanks.

答:
Possibly, most easy way will be to use:

https://github.com/ukushu/DataExporter

especially in case of your data of datatable containing /r/n characters or separator symbol inside of your dataTable cells. Almost all of other answers will not work with such cells.

only you need is to write the following code:

```<code>Csv csv = new Csv("\t");//Needed delimiter

var columnNames = dt.Columns.Cast<DataColumn>().
    Select(column => column.ColumnName).ToArray();

csv.AddRow(columnNames);

foreach (DataRow row in dt.Rows)
{
    var fields = row.ItemArray.Select(field => field.ToString()).ToArray;
    csv.AddRow(fields);
}

csv.Save();
</code>```

Title: How can I turn a DataTable to a CSV?

Body:
Could somebody please tell me why the following code is not working.  The data is saved into the csv file, however the data is not separated.  It all exists within the first cell of each row.

StringBuilder sb = new StringBuilder();

foreach (DataColumn col in dt.Columns)
{
    sb.Append(col.ColumnName + ',');
}

sb.Remove(sb.Length - 1, 1);
sb.Append(Environment.NewLine);

foreach (DataRow row in dt.Rows)
{
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        sb.Append(row[i].ToString() + ",");
    }

    sb.Append(Environment.NewLine);
}

File.WriteAllText("test.csv", sb.ToString());

Thanks.

Body:
Possibly, most easy way will be to use:

https://github.com/ukushu/DataExporter

especially in case of your data of datatable containing /r/n characters or separator symbol inside of your dataTable cells. Almost all of other answers will not work with such cells.

only you need is to write the following code:

Csv csv = new Csv("\t");//Needed delimiter

var columnNames = dt.Columns.Cast<DataColumn>().
    Select(column => column.ColumnName).ToArray();

csv.AddRow(columnNames);

foreach (DataRow row in dt.Rows)
{
    var fields = row.ItemArray.Select(field => field.ToString()).ToArray;
    csv.AddRow(fields);
}

csv.Save();


问:
How can I save a changelist state in WebStorm without committing them nor resetting the changes?
I want to save (back up) temporary states of WIP on complex feature development without committing them. This is specially useful on exploration work, when you figure out this solution path is not the best and want to continue from a specific point.

You can stash or shelve a changelist on WebStorm, but both features reset the state to HEAD, which causes issues on my hot deploy feature, plus the extra work to unstash or unshelve.

I also notice that putting labels is only usable for changes on a single file and tags only work for committed changes.

答:
w/o committing

Yet, simply commit in Webstorm, and then change your code.

You can do an interactive rebase (still in Webstorm) later, in which you will drop those intermediate commits, or squash together other intermediate commits.

That way (commit, plus refactoring), you don't have any hot deploy issue when saving your WIP.


问:
How can i hide the status bar in the browser?
I have a simple question, how can I hide a link in the status bar in my browser.

I've tried with this:

```<code><a href="http://www.sell.com/?referrer=225"
   onMouseOver="window.status='http://www.sell.com';
               return true" onMouseOut="window.status=''">Click here</a>
</code>```

(Taken from a tutorial)
But it doesn't work, if somebody would help me, I would be very happy! ;-)

答:
You can do this by using javascript for your link:

Here's how:

```<code>function goToBing() {
  window.location.href = "http://bing.com";
}
</code>```

and

```<code><a href="http://google.com" onclick="goToBing();return false;">Link to Google</a>
</code>```

As Nick Craver said, this doesn't work in all circumstances (control-click, middle-click etc.) but should work for you, because you don't relay on the javascript link.

Body:
I have a simple question, how can I hide a link in the status bar in my browser.

I've tried with this:

Click here

(Taken from a tutorial)
But it doesn't work, if somebody would help me, I would be very happy! ;-)

Body:
You can do this by using javascript for your link:

Here's how:

function goToBing() {
  window.location.href = "http://bing.com";
}

and

<a href="http://google.com" onclick="goToBing();return false;">Link to Google</a>

As Nick Craver said, this doesn't work in all circumstances (control-click, middle-click etc.) but should work for you, because you don't relay on the javascript link.


问:
isset PHP isset($_GET['something']) ? $_GET['something'] : ''
I am looking to expand on my PHP knowledge, and I came across something I am not sure what it is or how to even search for it.  I am looking at php.net isset code, and I see isset($_GET['something']) ? $_GET['something'] : ''

I understand normal isset operations, such as if(isset($_GET['something']){ If something is exists, then it is set and we will do something } but I don't understand the ?, repeating the get again, the : or the ''.  Can someone help break this down for me or at least point me in the right direction?

答:
If you want an empty string default then a preferred way is one of these (depending on your need):

```<code>$str_value = strval($_GET['something']);
$trimmed_value = trim($_GET['something']);
$int_value = intval($_GET['somenumber']);
</code>```

If the url parameter something doesn't exist in the url then $_GET['something'] will return null

strval($_GET['something']) -> strval(null) -> ""

and your variable $value is set to an empty string.

trim() might be prefered over strval() depending on code (e.g. a Name parameter might want to use it)

intval() if only numeric values are expected and the default is zero. intval(null) -> 0

Cases to consider:

...&something=value1&key2=value2 (typical)

...&key2=value2 (parameter missing from url $_GET will return null for it)

...&something=+++&key2=value (parameter is "   ")

Why this is a preferred approach:

It fits neatly on one line and is clear what's going on.

It's readable than $value = isset($_GET['something']) ? $_GET['something'] : '';

Lower risk of copy/paste mistake or a typo: $value=isset($_GET['something'])?$_GET['somthing']:'';

It's compatible with older and newer php.

Update
Strict mode may require something like this:

```<code>$str_value = strval(@$_GET['something']);
$trimmed_value = trim(@$_GET['something']);
$int_value = intval(@$_GET['somenumber']);
</code>```

Body:
If you want an empty string default then a preferred way is one of these (depending on your need):

$str_value = strval($_GET['something']);
$trimmed_value = trim($_GET['something']);
$int_value = intval($_GET['somenumber']);

If the url parameter something doesn't exist in the url then $_GET['something'] will return null

strval($_GET['something']) -> strval(null) -> ""

and your variable $value is set to an empty string.

trim() might be prefered over strval() depending on code (e.g. a Name parameter might want to use it)

intval() if only numeric values are expected and the default is zero. intval(null) -> 0

Cases to consider:

...&something=value1&key2=value2 (typical)

...&key2=value2 (parameter missing from url $_GET will return null for it)

...&something=+++&key2=value (parameter is "   ")

Why this is a preferred approach:

It fits neatly on one line and is clear what's going on.

It's readable than $value = isset($_GET['something']) ? $_GET['something'] : '';

Lower risk of copy/paste mistake or a typo: $value=isset($_GET['something'])?$_GET['somthing']:'';

It's compatible with older and newer php.

Update
Strict mode may require something like this:

$str_value = strval(@$_GET['something']);
$trimmed_value = trim(@$_GET['something']);
$int_value = intval(@$_GET['somenumber']);