问:
What is the advantage of using call method instead of passing an object in the parameter
In the below code, which one is the right and how these two are different

Using call method

```<code>var obj = {
  num: 10
 };

var add = function(a) {
  return this.num + a
}
console.log(add.call(obj,4))
</code>```

Passing object in parameter

```<code>var obj = {
  num: 10
};
var add = function(obj,a) {
  return obj.num + a
}
console.log(add(obj,4))
</code>```

答:
Your second code block is just a regular function. The first one however is a bit more tricky. So the question is basically:

When to work with context in javascript?

In javascript, the term context basically means this. It is usually used when you call a method of an object, so that you can refer to the object. That's one of the core concepts of OOP, were we only define a function once inside the prototype, and every object of that class which inherits from it exposes this method, it won't work without context. So that's what this was invented for. However there are some cases, were context is useful without inheritance. E.g. Eventhandlers are usually contextless, as they are not part of any object:

```<code>window.addEventListener("load", function(evt){
  const el = evt.target;
};
</code>```

However as it is an Eventhandler of window, wouldn't it make sense that it is executed in the context of window? If you now say "YES", then you (will) probably love JS:

```<code>window.addEventListener("load", function(){
 this.document.body.innerHTML = "Dynamic context can be cool!";
});
</code>```

So in JS this is the way of refering to the object, the function refers to. Through Function.prototype.call we can make use of this everywhere. However that does not mean that we should use it everywhere. this should stay in the sense of context, as using it somewhere else will create confusion / uglify your code / make your code buggy.

```<code>var add = function(a) {
 return this.num + a;
}
</code>```

In your codesnippet i think its unclear what thisrefers to. So its rather a misuse of this. However it could get a meaning if you make it a method of obj, so its context becomes clear from the code:

```<code>const num = {
  value:10,
  add(a){ return this.value + a }
};
</code>```

It gets even more beautiful if you use inheritance to make it reusable:

```<code>class CustomNumber {
  constructor(n = 0){
    this.value = n;
  }

  add(a){ return this.value + a; }
}

const num = new CustomNumber(10);
</code>```

Body:
In the below code, which one is the right and how these two are different

Using call method

var obj = {
  num: 10
 };

var add = function(a) {
  return this.num + a
}
console.log(add.call(obj,4))

Passing object in parameter

var obj = {
  num: 10
};
var add = function(obj,a) {
  return obj.num + a
}
console.log(add(obj,4))

Body:
Your second code block is just a regular function. The first one however is a bit more tricky. So the question is basically:

When to work with context in javascript?

In javascript, the term context basically means this. It is usually used when you call a method of an object, so that you can refer to the object. That's one of the core concepts of OOP, were we only define a function once inside the prototype, and every object of that class which inherits from it exposes this method, it won't work without context. So that's what this was invented for. However there are some cases, were context is useful without inheritance. E.g. Eventhandlers are usually contextless, as they are not part of any object:

window.addEventListener("load", function(evt){
  const el = evt.target;
};

However as it is an Eventhandler of window, wouldn't it make sense that it is executed in the context of window? If you now say "YES", then you (will) probably love JS:

window.addEventListener("load", function(){
 this.document.body.innerHTML = "Dynamic context can be cool!";
});

So in JS this is the way of refering to the object, the function refers to. Through Function.prototype.call we can make use of this everywhere. However that does not mean that we should use it everywhere. this should stay in the sense of context, as using it somewhere else will create confusion / uglify your code / make your code buggy.

var add = function(a) {
 return this.num + a;
}

In your codesnippet i think its unclear what thisrefers to. So its rather a misuse of this. However it could get a meaning if you make it a method of obj, so its context becomes clear from the code:

const num = {
  value:10,
  add(a){ return this.value + a }
};

It gets even more beautiful if you use inheritance to make it reusable:

class CustomNumber {
  constructor(n = 0){
    this.value = n;
  }

  add(a){ return this.value + a; }
}

const num = new CustomNumber(10);


来源: stackexchange

问:
How to Save Excel Worksheet as PDF with Command Button?
I am getting a 'Syntax Error' with the coding beneath the Next R line toward the bottom below.  I am trying to save the open worksheet as a PDF file referencing the order number found in cell D3.  Thanks for your help!</p>

```<code>Private Sub CommandButton1_Click()
Dim OrderDate As String, PONumber As String, Vendor As String, ShipTo As String, SKU As String, Path As String, filename As String
Dim R As Long, LastSKURow As Long, NextDBRow As Long, OFrm As Worksheet, DB As Worksheet
Set OFrm = Worksheets("Order Form 1")
Set DB = Worksheets("Database")
OrderDate = OFrm.Range("B3")
PONumber = OFrm.Range("D3")
Vendor = OFrm.Range("B7")
ShipTo = OFrm.Range("D7")
LastSKURow = OFrm.Cells(OFrm.Rows.Count, "F").End(xlUp).Row
For R = 3 To LastSKURow
    SKU = OFrm.Range("F" & R).Value
    NextDBRow = DB.Cells(DB.Rows.Count, "A").End(xlUp).Row + 1
    DB.Range("A" & NextDBRow).Value = OrderDate
    DB.Range("B" & NextDBRow).Value = PONumber
    DB.Range("C" & NextDBRow).Value = Vendor
    DB.Range("D" & NextDBRow).Value = ShipTo
    DB.Range("E" & NextDBRow).Value = SKU
Next R
Application.ScreenUpdating = False
OFrm.ExportAsFixedFormat Type:=xlTypePDF, _
        Path ="C:\PDF\"
        filename = OFrm.Range("D3")
        OpenAfterPublish = False
OFRrm.SaveAs filename:=Path & filename & ".pdf", FileFormat:=xlTypePDF
End Sub
</code>```

答:
The SaveAs line is redundant. You just need to fix the ExportAsFixedFormat to work properly. When using named parameters, you need to use := instead of just =. I recommend creating a new Sub for the PDF save.

```<code>Sub SaveOrderAsPDF()
    Dim PDFName As String
    PDFName = Worksheets("Order Form 1").Range("D3").Value
    ChDir "C:\PDF"
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    "C:\PDF\" & PDFName, Quality:=xlQualityStandard, IncludeDocProperties:= _
    True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End Sub
</code>```

With that working, just add SaveOrderAsPDF to your existing sub.

ContentLicense: CC BY-SA 3.0

Body:
I am getting a 'Syntax Error' with the coding beneath the Next R line toward the bottom below.  I am trying to save the open worksheet as a PDF file referencing the order number found in cell D3.  Thanks for your help!

Private Sub CommandButton1_Click()
Dim OrderDate As String, PONumber As String, Vendor As String, ShipTo As String, SKU As String, Path As String, filename As String
Dim R As Long, LastSKURow As Long, NextDBRow As Long, OFrm As Worksheet, DB As Worksheet
Set OFrm = Worksheets("Order Form 1")
Set DB = Worksheets("Database")
OrderDate = OFrm.Range("B3")
PONumber = OFrm.Range("D3")
Vendor = OFrm.Range("B7")
ShipTo = OFrm.Range("D7")
LastSKURow = OFrm.Cells(OFrm.Rows.Count, "F").End(xlUp).Row
For R = 3 To LastSKURow
    SKU = OFrm.Range("F" & R).Value
    NextDBRow = DB.Cells(DB.Rows.Count, "A").End(xlUp).Row + 1
    DB.Range("A" & NextDBRow).Value = OrderDate
    DB.Range("B" & NextDBRow).Value = PONumber
    DB.Range("C" & NextDBRow).Value = Vendor
    DB.Range("D" & NextDBRow).Value = ShipTo
    DB.Range("E" & NextDBRow).Value = SKU
Next R
Application.ScreenUpdating = False
OFrm.ExportAsFixedFormat Type:=xlTypePDF, _
        Path ="C:\PDF\"
        filename = OFrm.Range("D3")
        OpenAfterPublish = False
OFRrm.SaveAs filename:=Path & filename & ".pdf", FileFormat:=xlTypePDF
End Sub

Body:
The SaveAs line is redundant. You just need to fix the ExportAsFixedFormat to work properly. When using named parameters, you need to use := instead of just =. I recommend creating a new Sub for the PDF save.

Sub SaveOrderAsPDF()
    Dim PDFName As String
    PDFName = Worksheets("Order Form 1").Range("D3").Value
    ChDir "C:\PDF"
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    "C:\PDF\" & PDFName, Quality:=xlQualityStandard, IncludeDocProperties:= _
    True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End Sub

With that working, just add SaveOrderAsPDF to your existing sub.


问:
Pass "generic" JsonProvider to function in F#
I have two JsonProvider types:

```<code>type Provider1 = JsonProvider<"""{structure}""">
type Provider2 = JsonProvider<"""{}structure2""">
</code>```

I'd like to have a function, that can accept any of these and parse json using provided JsonProvider, something like this:(pseudo code, not compiling)

```<code>let parseUsingSpecificProvider json (provider : JsonProvider<GENERIC>) =
    provider.Parse json
</code>```

答:
In functional programming it is common to replace 'single function interfaces' with the function itself. I.e. instead of passing in a parser having a Parse method, just use the Parse function as a first class value:

```<code>#r @"packages\FSharp.Data\lib\net40\FSharp.Data.dll"
open FSharp.Data

type Provider1 = JsonProvider<""" { "name":"John"           } """>
type Provider2 = JsonProvider<""" { "name":"John", "age":94 } """>

let parse parseFn json =
    parseFn json

let p1 = parse Provider1.Parse """{ "name": "Not John" }"""
let p2 = parse Provider2.Parse """{ "name": "Not John either", "age": 12 }"""
</code>```

If you need several methods of the provided type, you could use e.g. a record containing all necessary data:

```<code>type Parser<'b> = {
    Parse : string -> 'b
    GetSample : unit -> 'b
}

let parseUsing parser text =
    printfn "Parsing things like %A" <| parser.GetSample()
    parser.Parse text

let parser1 = { Parse = Provider1.Parse; GetSample = Provider1.GetSample }
let parser2 = { Parse = Provider2.Parse; GetSample = Provider2.GetSample }

let p1' = parseUsing parser1 """{ "name": "Not John" }"""
let p2' = parseUsing parser2 """{ "name": "Not John either", "age": 12 }"""
</code>```

While SRTPs are powerful (and cool), their usage should be limited. Overuse slows down the compiler and makes code harder to understand.

Body:
I have two JsonProvider types:

type Provider1 = JsonProvider<"""{structure}""">
type Provider2 = JsonProvider<"""{}structure2""">

I'd like to have a function, that can accept any of these and parse json using provided JsonProvider, something like this:(pseudo code, not compiling)

let parseUsingSpecificProvider json (provider : JsonProvider<GENERIC>) =
    provider.Parse json

Body:
In functional programming it is common to replace 'single function interfaces' with the function itself. I.e. instead of passing in a parser having a Parse method, just use the Parse function as a first class value:

#r @"packages\FSharp.Data\lib\net40\FSharp.Data.dll"
open FSharp.Data

type Provider1 = JsonProvider<""" { "name":"John"           } """>
type Provider2 = JsonProvider<""" { "name":"John", "age":94 } """>

let parse parseFn json =
    parseFn json

let p1 = parse Provider1.Parse """{ "name": "Not John" }"""
let p2 = parse Provider2.Parse """{ "name": "Not John either", "age": 12 }"""

If you need several methods of the provided type, you could use e.g. a record containing all necessary data:

type Parser<'b> = {
    Parse : string -> 'b
    GetSample : unit -> 'b
}

let parseUsing parser text =
    printfn "Parsing things like %A" <| parser.GetSample()
    parser.Parse text

let parser1 = { Parse = Provider1.Parse; GetSample = Provider1.GetSample }
let parser2 = { Parse = Provider2.Parse; GetSample = Provider2.GetSample }

let p1' = parseUsing parser1 """{ "name": "Not John" }"""
let p2' = parseUsing parser2 """{ "name": "Not John either", "age": 12 }"""

While SRTPs are powerful (and cool), their usage should be limited. Overuse slows down the compiler and makes code harder to understand.


问:
How to get time by this string in javascript 2017-11-29T10:27:15.2327188Z
I have this string 2017-11-29T10:27:15.2327188Z I just need to get time in javascript any idea how ?</p>

答:
First, convert the string into a date object:

```<code>var date = new Date('2017-11-29T10:27:15.2327188Z');
</code>```

Then, you can call toLocaleTimeString() to return a string with a language sensitive representation of the time portion of this date:

```<code>console.log(date.toLocaleTimeString());
</code>```

Body:
First, convert the string into a date object:

var date = new Date('2017-11-29T10:27:15.2327188Z');

Then, you can call toLocaleTimeString() to return a string with a language sensitive representation of the time portion of this date:

console.log(date.toLocaleTimeString());


问:
Session, cookies and ids
It was suggested to me to use sessions for cross page storage, and maintain the session ID by storing it in a GET parameter or cookie.

What's the safest way to save data into a session and make it last forever (like login informations)?

答: Sessions are a standard feature in PHP. Start from this page to read some detail about how sessions are handled in PHP. Anyway, be aware that even session aren't 100% safe. There are a number of security concerns even about sessions (you can read something about session security, Session Fixation, Session Poisoning to understand the security implications of sessions).</p>

Title: Session, cookies and ids

ContentLicense: CC BY-SA 2.5


问:
java | Return a reversed array by FOR loop
I am stuck with an exercise which tells me to create a reversed array from the given one.

After some thinking I made such code:

```<code>    public int[] reverse3(int[] nums) {

  int[] nums2 = new int[3];

  for (int i = nums.length - 1; i >= 0; i--) {

     for (int j = 0; j < nums.length; j++) {

          nums2[j] = nums[i];

    }
  }
  return nums2;
}
</code>```

But it is throwing out three exact same numbers.

答:
Swap the symetric values in the array like this : </p>

```<code> public static void reverse(int[] nums) {
    for (int i = 0; i < nums.length / 2; i++) {
        int temp = nums[i];
        nums[i] = nums[nums.length - 1 - i];
        nums[nums.length - 1 - i] = temp;
    }
</code>```

Body:
I am stuck with an exercise which tells me to create a reversed array from the given one.

After some thinking I made such code:

    public int[] reverse3(int[] nums) {

  int[] nums2 = new int[3];

  for (int i = nums.length - 1; i >= 0; i--) {

     for (int j = 0; j < nums.length; j++) {

          nums2[j] = nums[i];

    }
  }
  return nums2;
}

But it is throwing out three exact same numbers.

Body:
Swap the symetric values in the array like this :

 public static void reverse(int[] nums) {
    for (int i = 0; i < nums.length / 2; i++) {
        int temp = nums[i];
        nums[i] = nums[nums.length - 1 - i];
        nums[nums.length - 1 - i] = temp;
    }


问:
Immortal token for backend API
The documentation for the API I need to connect to suggests creating an "immortal" token (that never expires) issued to an admin and then attaching that token to all requests. Here's a detailed rundown on how that works. And it does work.

But it seems like a strange way to do it, but I'm not familiar enough with all of the concepts involved to say why.

Are there security concerns with going this route?

答: I think my answer to the other question was not complete. I added some more details to the answer. </p>

Title: Immortal token for backend API


问:
Setting custom URLs with PHP
So, I need to set custom URLs so that

http://example.com/dynamic/

goes to:

http://example.com/dynamic.php

I know this is a pretty simple operation but after some googling, I can't find the answer. What is the simplest method for handling something like this?

答:
The regular expression for that would be something like this:

```<code>RewriteEngine on
RewriteRule ([^/]+)/?$ $1.php [L]
</code>```

Running the regex on the left will return "dynamic/" or "dynamic" if the forward slash is not included. Then it will replace what was captured in the first parenthesized block ("dynamic/") with dynamic.php.

You can try your URL rewrites here:

http://martinmelin.se/rewrite-rule-tester/

And your general regex here:

http://regexpal.com/

Title: Setting custom URLs with PHP

Body:
The regular expression for that would be something like this:

RewriteEngine on
RewriteRule ([^/]+)/?$ $1.php [L]

Running the regex on the left will return "dynamic/" or "dynamic" if the forward slash is not included. Then it will replace what was captured in the first parenthesized block ("dynamic/") with dynamic.php.

You can try your URL rewrites here:

http://martinmelin.se/rewrite-rule-tester/

And your general regex here:

http://regexpal.com/


问:
How to display selected value and image in edit page to perform update operation using laravel

Hello,
I am new learner in Laravel and my first post in Stackoverflow so applogy to me for my mistake and English language.

I can create a project shoppingcart & perform CRUD operation where create product information such as product name, brand, description, price & image. I can done create & read operation easily. Below my product list that can be show in browser

enter image description here

When I click edit button browser can show like that below image to perform edit operation

enter image description here

where brand name & image can't shown edit product form

My productController code below like that

```<code> namespace App\Http\Controllers;

 use Illuminate\Http\Request;
 use App\brand;
 use App\Product;
 use Illuminate\Support\Facades\DB;

class productController extends Controller
 {
  public function index(){

    $product = DB::table('products')
        ->join('brands','products.brandID','=','brands.brandID')
        -> select('products.*','brands.brandName')
        ->get();

    return view('admin.product.productList',compact('product'));
}

   public function create()
   {
    $product = brand::pluck('brandName','brandID');

    return view('admin.product.createProduct',compact('product'));
   }

  public function store(Request $request)
  {

    // image upload

    $product = $request->except('image');

    $image = $request->image;

    if ($image) {
        $imageName = $image->getClientOriginalName();

        $image->move('images', $imageName);

        $product['image'] = $imageName;
    }

    Product::create($product);

    return view('admin.product.productList', compact('product'));
 }

 public function show($id)
 {
    $product = Product::find($id);

    return view('admin.product.editProduct',compact('product'));
}

 public function edit($id)
 {

 }

 public function delete($id){

    $product= Product::find($id);

    $data=$product->delete();

    return view('admin.product.productList',compact('data'));
}
}
</code>```

my editProduct.blade file code below like that

```<code>@extends('layouts.master')

@section('content')

   <div class="container" align="center">
        <div class="col-md-6 col-md-offset-3">
       </div>
    </div>

   <div class="container">
      <div class="row">
       <div class="col-md-8 col-md-offset-2">
           <div class="panel panel-default">
                  <div class="panel-heading">Edit Product
               </div>
           <div class="panel-body">
               <form action="edit" class="form-horizontal" method="POST>

           {{csrf_field()}}

                    <div class="form-group">
                        <label for="name" class="col-md-4 control-label">Product Name :</label>

                        <div class="col-md-6">
                            <input id="name" type="text" class="form-control" value="{!! $product->productName !!}" name="name" required autofocus>

                        </div>
                    </div>

                   <div class="form-group">
                       <label for="name" class="col-md-4 control-label">Brand :</label>

                       <div class="col-md-6">

                           <select name=" " class="form-control" >

                               <option>
                               </option>

                           </select>

                       </div>
                   </div>

                    <div class="form-group">
                        <label for="description" class="col-md-4 control-label">Description:</label>

                        <div class="col-md-6">
                            <input id="description"  class="form-control" name="description" value="{!! $product->description !!}" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="price" class="col-md-4 control-label">Price:</label>

                        <div class="col-md-6">
                            <input id="price" value="{!! $product->price !!}" class="form-control" name="price" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="image" class="col-md-4 control-label">Image:</label>

                        <div class="col-md-6">
                            <input id="image" type="file" value="{!! $product->image !!}" class="btn-btn-default" name="image" value="Upload" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="col-md-6 col-md-offset-4">
                            <button type="submit" class="btn btn-primary">
                                ADD
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
</code>```

 @endsection

Here, brand name can be selected by HTML select attribute and value get another model Brand & the data can be retrieve from Brand model using join query which is included productController index method.

So how can I show brand name & image to edit in the editProduct blade file. Pls help me

答:
There are couple of ways, here's 1 way.

In your controller.

```<code> public function edit($id)
 {
        $product = Product::find($id);

        $data = [
             'product_info' => $product
        ];

        return view('your.edit.view.here', $data);

 }
</code>```

And inside your view, inside the FORM Tag, do the looping.

```<code>@foreach($product_info as $info)
  // data info here
  <input id="description"  value="{{ $product->description }}" required>
@endforeach
</code>```

EDIT::

Use Laravel Encryption, you need it especially web apps like shopping cart.

```<code>URL:: http://localhost:8000/product/show/encrypted_id_here
public function show($id) {
   $id = decrypt($id);
}
</code>```

Body:
Hello,
I am new learner in Laravel and my first post in Stackoverflow so applogy to me for my mistake and English language.

I can create a project shoppingcart & perform CRUD operation where create product information such as product name, brand, description, price & image. I can done create & read operation easily. Below my product list that can be show in browser

enter image description here

When I click edit button browser can show like that below image to perform edit operation

enter image description here

where brand name & image can't shown edit product form

My productController code below like that

 namespace App\Http\Controllers;

 use Illuminate\Http\Request;
 use App\brand;
 use App\Product;
 use Illuminate\Support\Facades\DB;

class productController extends Controller
 {
  public function index(){

    $product = DB::table('products')
        ->join('brands','products.brandID','=','brands.brandID')
        -> select('products.*','brands.brandName')
        ->get();

    return view('admin.product.productList',compact('product'));
}

   public function create()
   {
    $product = brand::pluck('brandName','brandID');

    return view('admin.product.createProduct',compact('product'));
   }

  public function store(Request $request)
  {

    // image upload

    $product = $request->except('image');

    $image = $request->image;

    if ($image) {
        $imageName = $image->getClientOriginalName();

        $image->move('images', $imageName);

        $product['image'] = $imageName;
    }

    Product::create($product);

    return view('admin.product.productList', compact('product'));
 }

 public function show($id)
 {
    $product = Product::find($id);

    return view('admin.product.editProduct',compact('product'));
}

 public function edit($id)
 {

 }

 public function delete($id){

    $product= Product::find($id);

    $data=$product->delete();

    return view('admin.product.productList',compact('data'));
}
}

my editProduct.blade file code below like that

@extends('layouts.master')

@section('content')

Edit Product

               <form action="edit" class="form-horizontal" method="POST>

           {{csrf_field()}}

                        Product Name :

                            <input id="name" type="text" class="form-control" value="{!! $product->productName !!}" name="name" required autofocus>

                       Brand :

                           <select name=" " class="form-control" >

                               <option>
                               </option>

                           </select>

                        Description:

                            <input id="description"  class="form-control" name="description" value="{!! $product->description !!}" required>

                        Price:

                            <input id="price" value="{!! $product->price !!}" class="form-control" name="price" required>

                        Image:

                            <input id="image" type="file" value="{!! $product->image !!}" class="btn-btn-default" name="image" value="Upload" required>

                            <button type="submit" class="btn btn-primary">
                                ADD
                            </button>

                </form>

 @endsection

Here, brand name can be selected by HTML select attribute and value get another model Brand & the data can be retrieve from Brand model using join query which is included productController index method.

So how can I show brand name & image to edit in the editProduct blade file. Pls help me

Body:
There are couple of ways, here's 1 way.

In your controller.

 public function edit($id)
 {
        $product = Product::find($id);

        $data = [
             'product_info' => $product
        ];

        return view('your.edit.view.here', $data);

 }

And inside your view, inside the FORM Tag, do the looping.

@foreach($product_info as $info)
  // data info here
  <input id="description"  value="{{ $product->description }}" required>
@endforeach

EDIT::

Use Laravel Encryption, you need it especially web apps like shopping cart.

URL:: http://localhost:8000/product/show/encrypted_id_here
public function show($id) {
   $id = decrypt($id);
}


问:
Unit testing of potential concurrency problems
I have had recently a small contest with one of my colleagues (whom I very respect) regarding a theoretical possibility to test whether some code is thread-safe or not.

Let us suppose that we have a some "black-box" class FooUnknown taken from the 3rd party library, so we don't have an access to its original source code. Furthermore, it might be that it internally uses some native methods (if this is a matter).

Can we write such an unit test which will tell us that usage of this class (for example, its instance shared between several threads) is 100% thread-safe or not?

My conclusion, that it is not possible. For me it is obvious and straightforward: although one can write a code which will lead to some concurrency problems which is possible to detect. But an absent of such results doesn't guarantee that there are not concurrency issues at all.

Also I believe, that this question is not too broad. For certainty let us say we have a class some.FooUnknown and we want to use it in the following way:

```<code>@ApplicationScoped
public class FooService {
    private some.FooUnkown foo = new some.FooUnknown();

    public void someStuff() {
        // ...
        String result = foo.doSomeStuff();
        // ...
    }
}
</code>```

How to test it to be sure that it is thread-safe, that we don't need to wrap it into ThreadLocal<FooUnknown> for instance?

答: It is impossible, because there are to many ways to produce thread unsafety. Just a global variable in native code could be enough. </p>

Body:
I have had recently a small contest with one of my colleagues (whom I very respect) regarding a theoretical possibility to test whether some code is thread-safe or not.

Let us suppose that we have a some "black-box" class FooUnknown taken from the 3rd party library, so we don't have an access to its original source code. Furthermore, it might be that it internally uses some native methods (if this is a matter).

Can we write such an unit test which will tell us that usage of this class (for example, its instance shared between several threads) is 100% thread-safe or not?

My conclusion, that it is not possible. For me it is obvious and straightforward: although one can write a code which will lead to some concurrency problems which is possible to detect. But an absent of such results doesn't guarantee that there are not concurrency issues at all.

Also I believe, that this question is not too broad. For certainty let us say we have a class some.FooUnknown and we want to use it in the following way:

@ApplicationScoped
public class FooService {
    private some.FooUnkown foo = new some.FooUnknown();

    public void someStuff() {
        // ...
        String result = foo.doSomeStuff();
        // ...
    }
}

How to test it to be sure that it is thread-safe, that we don't need to wrap it into ThreadLocal<FooUnknown> for instance?


问:
How to configure the positioning of optional arguments to a constructor
I have a class whose constructor looks like this:

```<code>GlslProgram(const char* vertex_shader_path, const char* fragment_shader_path, const char* tess_control_shader_path = "", const char* tess_eval_shader_path = "", const char* geom_shader_path = "");
</code>```

The final three parameters are all optional as a "" is used as a default parameter.

However, because C++ doesn't support positional arguments, if one wants to call the constructor without tess_control_shader_path and tess_eval_shader_path but with geom_shader_path they have to pass in two positional "" arguments (as opposed to nullptr or something more clear).

Is there a clean or simple way to get rid of this? Put another way: is there a way to make specific parameter placement unnecsary?

I am looking at the named constructor idiom but I do not love that idea because in this case, the naming convention wouldn't really make sense (i.e. GlslProgram::withGeometryShader, GlslProgram::withTesselation) doesn't seem to make sense.

Ideally I would have something like:

```<code>GlslProgram().vertex_path("path")
             .fragment_path("path")
             .geo_path("path")
             .tesselation_path("path");
</code>```

but the issue here is that there is a final initialization step that needs to happen when all parameters are done (all file paths done) and so I don't see how I would know what the final 'path' in the chain is.

答:
Is there a clean or simple way to get rid of this? Put another way: is there a way to make specific parameter placement unnecsary?

The simplest thing I can think of is to provide the following class design with chainable setters for the optional parameters:

```<code>class MyClass {
    int required_param1_;
    int required_param2_;
    int optional_param1_;
    int optional_param2_;
public:
     MyClass (int required_param1, int required_param2)
     : required_param1_(required_param1)
     , required_param2_(required_param2)
     , optional_param1_() // Use default
     , optional_param2_() // Use default
     {}
     // The 2 following statements are only for emphasis, and can be completely
     // omitted as well, since the compiler generates these automatically.
     MyClass (const MyClass& other) = default;
     MyClass& operator=(const MyClass& other) = default;

     // Class getter / setter declarations
     int required_param1() const { return required_param1_; }
     int required_param2() const { return required_param2_; }
     int optional_param1() const { return optional_param1_; }
     MyClass& optional_param1(int value) {
         optional_param1_ = value;
         return *this; }
     int optional_param2() const { return optional_param2_; }
     MyClass& optional_param2(int value) {
         optional_param2_ = value;
         return *this; }
};
</code>```

That allows you to use the following syntax:

```<code>MyClass myClass1 = MyClass(1,2 /* <- the required parameters*/)
                          .optional_param1(5)
                          ;
MyClass myClass2 = MyClass(3,4 /* <- the required parameters*/)
                          .optional_param2(24)
                          .optional_param1(42)
                          ;
</code>```

Here's a fully working Demo.

Ideally I would have something like:

```<code>GlslProgram().vertex_path("path")
             .fragment_path("path")
             .geo_path("path")
             .tesselation_path("path");
</code>```

My above proposal comes pretty close ...

but the issue here is that there is a final initialization step that needs to happen when all parameters are done (all file paths done) and so I don't see how I would know what the final 'path' in the chain is.

... the final initialization step is still needed and realized with the copy constructor. Though you can rely on the compiler's optimization capabilities and that copy elision would take place there.

Body:
I have a class whose constructor looks like this:

GlslProgram(const char* vertex_shader_path, const char* fragment_shader_path, const char* tess_control_shader_path = "", const char* tess_eval_shader_path = "", const char* geom_shader_path = "");

The final three parameters are all optional as a "" is used as a default parameter.

However, because C++ doesn't support positional arguments, if one wants to call the constructor without tess_control_shader_path and tess_eval_shader_path but with geom_shader_path they have to pass in two positional "" arguments (as opposed to nullptr or something more clear).

Is there a clean or simple way to get rid of this? Put another way: is there a way to make specific parameter placement unnecsary?

I am looking at the named constructor idiom but I do not love that idea because in this case, the naming convention wouldn't really make sense (i.e. GlslProgram::withGeometryShader, GlslProgram::withTesselation) doesn't seem to make sense.

Ideally I would have something like:

GlslProgram().vertex_path("path")
             .fragment_path("path")
             .geo_path("path")
             .tesselation_path("path");

but the issue here is that there is a final initialization step that needs to happen when all parameters are done (all file paths done) and so I don't see how I would know what the final 'path' in the chain is.

Body:
Is there a clean or simple way to get rid of this? Put another way: is there a way to make specific parameter placement unnecsary?

The simplest thing I can think of is to provide the following class design with chainable setters for the optional parameters:

class MyClass {
    int required_param1_;
    int required_param2_;
    int optional_param1_;
    int optional_param2_;
public:
     MyClass (int required_param1, int required_param2)
     : required_param1_(required_param1)
     , required_param2_(required_param2)
     , optional_param1_() // Use default
     , optional_param2_() // Use default
     {}
     // The 2 following statements are only for emphasis, and can be completely
     // omitted as well, since the compiler generates these automatically.
     MyClass (const MyClass& other) = default;
     MyClass& operator=(const MyClass& other) = default;

     // Class getter / setter declarations
     int required_param1() const { return required_param1_; }
     int required_param2() const { return required_param2_; }
     int optional_param1() const { return optional_param1_; }
     MyClass& optional_param1(int value) {
         optional_param1_ = value;
         return *this; }
     int optional_param2() const { return optional_param2_; }
     MyClass& optional_param2(int value) {
         optional_param2_ = value;
         return *this; }
};

That allows you to use the following syntax:

MyClass myClass1 = MyClass(1,2 /* <- the required parameters*/)
                          .optional_param1(5)
                          ;
MyClass myClass2 = MyClass(3,4 /* <- the required parameters*/)
                          .optional_param2(24)
                          .optional_param1(42)
                          ;

Here's a fully working Demo.

Ideally I would have something like:

GlslProgram().vertex_path("path")
             .fragment_path("path")
             .geo_path("path")
             .tesselation_path("path");

My above proposal comes pretty close ...

but the issue here is that there is a final initialization step that needs to happen when all parameters are done (all file paths done) and so I don't see how I would know what the final 'path' in the chain is.

... the final initialization step is still needed and realized with the copy constructor. Though you can rely on the compiler's optimization capabilities and that copy elision would take place there.


问:
Nested Loop In C#
I'm doing a simple c# exercise. Here's the problem: Write a program called SquareBoard that displays the following n×n (n=5) pattern using two nested for-loops. Here's my code:

```<code>Sample output:
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
</code>```

Here's my code:

```<code>for (int row = 1; row <=5; row++) {
    for (int col = 1;col <row ; col++)
    {
        Console.Write("#");
    }
    Console.WriteLine();
}
</code>```

But it doe's not work .can anyone help me. thank you..

答:
```<code>for(int i=0; i<5 ; i++)

    for(int j=0 ; j <5 ; j++)
    Console.Write("#");

Console.WriteLine();
</code>```

Title: Nested Loop In C#

Body:
I'm doing a simple c# exercise. Here's the problem: Write a program called SquareBoard that displays the following n×n (n=5) pattern using two nested for-loops. Here's my code:

Sample output:
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #

Here's my code:

for (int row = 1; row <=5; row++) {
    for (int col = 1;col <row ; col++)
    {
        Console.Write("#");
    }
    Console.WriteLine();
}

But it doe's not work .can anyone help me. thank you..


问:
How check if an event listener exists in javascript
I try to find a way to check if an eventListener already exists in a window, I've tried the solution in this similar question and more other solutions, but nothing works for me.

Here is the code:

```<code>   checkEvent=function()
   {
    if('keydown' in window)
        console.log('exist');
    else
        console.log('not_exist');
   }
</code>```

And here is my eventListener that I add on my page Load

```<code>document.addEventListener("keydown", PayKeydownHandler);
</code>```

But the first code, returns 'not_exist' as a result

PS: The function checkEvent(), i call it in onclick of ENTER keydown.

Any help please? Thank's in advance.

答:
try this

```<code>jQuery._data( window, "events" );
</code>```

it work in jquery 1.8 . Read this jQuery blog post.

Body:
I try to find a way to check if an eventListener already exists in a window, I've tried the solution in this similar question and more other solutions, but nothing works for me.

Here is the code:

   checkEvent=function()
   {
    if('keydown' in window)
        console.log('exist');
    else
        console.log('not_exist');
   }

And here is my eventListener that I add on my page Load

document.addEventListener("keydown", PayKeydownHandler);

But the first code, returns 'not_exist' as a result

PS: The function checkEvent(), i call it in onclick of ENTER keydown.

Any help please? Thank's in advance.

Body:
try this

jQuery._data( window, "events" );

it work in jquery 1.8 . Read this jQuery blog post.


问:
node is not recognized as an internal or external command but is in PATH
Although I've follow suggestions from:

'node' is not recognized as an internal or an external command, operable program or batch file while using phonegap/cordova

Node.js doesn't recognize system path?

‘ant’ is not recognized as an internal or external command...

I'm having an strange issue: Resume, although node path is list in Path, it doesn't find node.

Workflow:

```<code>Microsoft Windows [Version 6.3.9600]    //Running CMD on windows 8.1
(c) 2013 Microsoft Corporation. All rights reserved.
</code>```

I followed suggestions in SO, adding variable to Environment Variables, and it's display Ok in Path:

```<code>C:\Users\myUser>path
PATH=c:\Program Files (x86)\nodejs ; (...omitted...) //So folder is there
</code>```

Next line will fail

```<code>C:\Users\myUser>call jasmine-node spec
'node' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\myUser>cd "c:\Program Files (x86)\nodejs" //So I move to the folder list before...
</code>```

But if I move to folder list in Path, then it works OK.

```<code>c:\Program Files (x86)\nodejs>call jasmine-node spec
>  (...omitted...) //Exec OK.

c:\Program Files (x86)\nodejs>node
>   //Exec OK. Waiting...
</code>```

It seems contradictory.

答:
I faced this issue even after adding node.exe to PATH. I wasn't able to run node command at random locations without running command prompt as administrator.

Solution to this issue is, you have to give full access permissions to this node.exe file for different user types. open the properties of node.exe, go to security tabs, check all the security options to the user on your local machine.

after doing this you should be able to access the node.exe file from any location.

Body:
Although I've follow suggestions from:

'node' is not recognized as an internal or an external command, operable program or batch file while using phonegap/cordova

Node.js doesn't recognize system path?

‘ant’ is not recognized as an internal or external command...

I'm having an strange issue: Resume, although node path is list in Path, it doesn't find node.

Workflow:

Microsoft Windows [Version 6.3.9600]    //Running CMD on windows 8.1
(c) 2013 Microsoft Corporation. All rights reserved.

I followed suggestions in SO, adding variable to Environment Variables, and it's display Ok in Path:

C:\Users\myUser>path
PATH=c:\Program Files (x86)\nodejs ; (...omitted...) //So folder is there

Next line will fail

C:\Users\myUser>call jasmine-node spec
'node' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\myUser>cd "c:\Program Files (x86)\nodejs" //So I move to the folder list before...

But if I move to folder list in Path, then it works OK.

c:\Program Files (x86)\nodejs>call jasmine-node spec
>  (...omitted...) //Exec OK.

c:\Program Files (x86)\nodejs>node
>   //Exec OK. Waiting...

It seems contradictory.


问:
Plot frequency of contact id in channel for a Pandas DF
This is my Pandas DF structure:

```<code>    Id                  channel
0   0140268216898719    RIA
2   022427195461267     Wire
3   023552004060340     Ind
</code>```

With more columns that are not important, and more data.

I am looking to plot a histogram using seaborn to show frequency of contactId for each channel, however I am failing miserably not matter what I try.

The way I see it, I can either group Id by channel and have a bar plot (attempted as follows):

```<code>df=df['channel'].groupby(['Id']).count() #count occurrences of Id for each channel
</code>```

Results in:

```<code>channel
Ind            174
RIA             60
Wire            77
</code>```

And

```<code>tips = sns.load_dataset("df")
ax = sns.barplot(x="channel", y="Id", data=tips)
</code>```

HTTPError: HTTP Error 404: Not Found

or a histogram of channel vs. frequency of Id, something like the below:

```<code>sns.distplot(df, kde=False, rug=True)
</code>```

Here I get a plot with Id on x axis and frequency between 0 to 2 on y axis.

In other words neither of these options provide the output I need.

Can anyone give me a hand to properly plot the initially given data? Thank you!

答:
I was doing tips = sns.load_dataset("df") as per the documentation, but this is nothing more than a Seaborn way of pulling data from csv on their server.
Simply stating data=df inside barplot() extracts data from my DF.. The apply function I added is for unique counts instead of just count.

```<code>df=df.groupby(['channel'])['Id'].apply(lambda x:len(x.unique())).reset_index()
print(df)
sns.set(style='darkgrid')
sns.barplot(x='channel', y='Id', data=df, palette='Set2')
plt.show()
</code>```

--Edit
to order by count desc, I suggest doing something like this:

```<code>result = df.sort_values('Id',ascending=False)
sns.barplot(x='channel', y='id', data=result, palette='Set2')
</code>```

Body:
This is my Pandas DF structure:

    Id                  channel
0   0140268216898719    RIA
2   022427195461267     Wire
3   023552004060340     Ind

With more columns that are not important, and more data.

I am looking to plot a histogram using seaborn to show frequency of contactId for each channel, however I am failing miserably not matter what I try.

The way I see it, I can either group Id by channel and have a bar plot (attempted as follows):

df=df['channel'].groupby(['Id']).count() #count occurrences of Id for each channel

Results in:

channel
Ind            174
RIA             60
Wire            77

And

tips = sns.load_dataset("df")
ax = sns.barplot(x="channel", y="Id", data=tips)

HTTPError: HTTP Error 404: Not Found

or a histogram of channel vs. frequency of Id, something like the below:

sns.distplot(df, kde=False, rug=True)

Here I get a plot with Id on x axis and frequency between 0 to 2 on y axis.

In other words neither of these options provide the output I need.

Can anyone give me a hand to properly plot the initially given data? Thank you!

Body:
I was doing tips = sns.load_dataset("df") as per the documentation, but this is nothing more than a Seaborn way of pulling data from csv on their server.
Simply stating data=df inside barplot() extracts data from my DF.. The apply function I added is for unique counts instead of just count.

df=df.groupby(['channel'])['Id'].apply(lambda x:len(x.unique())).reset_index()
print(df)
sns.set(style='darkgrid')
sns.barplot(x='channel', y='Id', data=df, palette='Set2')
plt.show()

--Edit
to order by count desc, I suggest doing something like this:

result = df.sort_values('Id',ascending=False)
sns.barplot(x='channel', y='id', data=result, palette='Set2')


问:
undefined method `empty?' for nil:NilClass how to avoid it
Hi Together I've got this code:

```<code> @coursesFound = @user.available_courses
@courses = []

for course in @coursesFound do
  @courseInGroups = course.user_groups
  for group in @courseInGroups do
    @group = UserGroup.find group.id
    if @group.users.map { |u| u.id }.include? @user.id
      @courses << course
      break
    end
  end
end

# Wenn ein Kurs keiner Gruppe hinzugefügt wurde
if @courseInGroups.empty?
  @courses << course
end
</code>```

on my debian vm it works fine but on my live system I got this error:

```<code>undefined method `empty?' for nil:NilClass
</code>```

How can I avoid this?

答:
And don't forget blank? when using rails. Here you find a good overview of all methods with or without rails.

I did not analyze your code, it's just for you, me and others that do not use this methods often, mix them up and then come here - just to remember: empty? is not blank?.

Body:
Hi Together I've got this code:

 @coursesFound = @user.available_courses
@courses = []

for course in @coursesFound do
  @courseInGroups = course.user_groups
  for group in @courseInGroups do
    @group = UserGroup.find group.id
    if @group.users.map { |u| u.id }.include? @user.id
      @courses << course
      break
    end
  end
end

# Wenn ein Kurs keiner Gruppe hinzugefügt wurde
if @courseInGroups.empty?
  @courses << course
end

on my debian vm it works fine but on my live system I got this error:

undefined method `empty?' for nil:NilClass

How can I avoid this?


问:
Creating a minimal sandbox for running binary programs in Python3
I am trying to build a Python sandbox for running student's code in a minimal and safe environment. I intend to run it into a container and to limit its access to the resources of that container. So, I am currently designing the part of the sandbox that is supposed to run into the container and handle the access to the resources.

For now, my specification is to limit the amount of time and memory used by the process. I also need to be able to communicate with the process through the stdin and to catch the retcode, stdout and stderr at the end of the execution.

Moreover, the program may enter in an infinite loop and fill-up the memory through the stdout or stderr (I had one student's program that crashed my container because of that). So, I want also to be able to limit the size of the recovered stdout and stderr (after a certain limit is reached I can just kill the process and ignore the rest of the output. I do not care about these extra data as it is most likely a buggy program and it should be discarded).

For now, my sandbox is catching almost everything, meaning that I can:

Set a timeout as I want;

Set a limit to the memory used in the process;

Feed the process through a stdin (for now a given string);

Get the final retcode, stdout and stderr.

Here is my current code (I tried to keep it small for the example):

MEMORY_LIMIT  = 64 * 1024 * 1024
TIMEOUT_LIMIT = 5 * 60

__NR_FILE_NOT_FOUND = -1
__NR_TIMEOUT        = -2
__NR_MEMORY_OUT     = -3

def limit_memory(memory):
    import resource
    return lambda :resource.setrlimit(resource.RLIMIT_AS, (memory, memory))

def run_program(cmd, sinput='', timeout=TIMEOUT_LIMIT, memory=MEMORY_LIMIT):
    """Run the command line and output (ret, sout, serr)."""
    from subprocess import Popen, PIPE
    try:
        proc =  Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE,
                      preexec_fn=limit_memory(memory))
    except FileNotFoundError:
        return (__NR_FILE_NOT_FOUND, "", "")

    sout, serr = "".encode("utf-8"), "".encode("utf-8")
    try:
        sout, serr = proc.communicate(sinput.encode("utf-8"), timeout=timeout)
        ret = proc.wait()
    except subprocess.TimeoutExpired:
        ret = __NR_TIMEOUT
    except MemoryError:
        ret = __NR_MEMORY_OUT
    return (ret, sout.decode("utf-8"), serr.decode("utf-8"))

if __name__ == "__main__":
    ret, out, err = run_program(['./example.sh'], timeout=8)
    print("return code: %i\n" % ret)
    print("stdout:\n%s" % out)
    print("stderr:\n%s" % err)
```

The missing features are:

Set a limitation on the size of stdout and stderr. I looked on the Web and saw several attempts, but none is really working.

Attach a function to stdin better than just a static string. The function should connect to the pipes stdout and stderr and return bytes to stdin.

Does anyone has an idea about that ?

PS: I already looked at:

Non blocking reading from a subprocess output stream in Python;

Python subprocess with timeout and large output (>64K)

答:
As I was saying, you can create your own buffers and write the STDOUT/STDERR to them, checking the size along the way. For convenience, you can write a small io.BytesIO wrapper to do the check for you, e.g.:

```<code>from io import BytesIO

# lets first create a size-controlled BytesIO buffer for convenience
class MeasuredStream(BytesIO):

    def __init__(self, maxsize=1024):  # lets use a 1 KB as a default
        super(MeasuredStream, self).__init__()
        self.maxsize = maxsize
        self.length = 0

    def write(self, b):
        if self.length + len(b) > self.maxsize:  # o-oh, max size exceeded
            # write only up to maxsize, truncate the rest
            super(MeasuredStream, self).write(b[:self.maxsize - self.length])
            raise ValueError("Max size reached, excess data is truncated")
        # plenty of space left, write the bytes and increase the length
        self.length += super(MeasuredStream, self).write(b)
        return len(b)  # convention: return the written number of bytes
</code>```

Mind you, if you intend to do truncation / seek & replace you'll have to account for those in your length but this is enough for our purposes.

Anyway, now all you need to do is to handle your own streams and account for the possible ValueError from the MeasuredStream, instead of using Popen.communicate(). This, unfortunately, also means that you'll have to handle the timeout yourself. Something like:

```<code>from subprocess import Popen, PIPE, STDOUT, TimeoutExpired
import sys
import time

MEMORY_LIMIT  = 64 * 1024 * 1024
TIMEOUT_LIMIT = 5 * 60
STDOUT_LIMIT  = 1024 * 1024  # let's use 1 MB as a STDOUT limit

__NR_FILE_NOT_FOUND      = -1
__NR_TIMEOUT             = -2
__NR_MEMORY_OUT          = -3
__NR_MAX_STDOUT_EXCEEDED = -4  # let's add a new return code

# a cross-platform precision clock
get_timer = time.clock if sys.platform == "win32" else time.time

def limit_memory(memory):
    import resource
    return lambda :resource.setrlimit(resource.RLIMIT_AS, (memory, memory))

def run_program(cmd, sinput='', timeout=TIMEOUT_LIMIT, memory=MEMORY_LIMIT):
    """Run the command line and output (ret, sout, serr)."""
    from subprocess import Popen, PIPE, STDOUT
    try:
        proc =  Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT,
                      preexec_fn=limit_memory(memory), timeout=timeout)
    except FileNotFoundError:
        return (__NR_FILE_NOT_FOUND, "", "")
    sout = MeasuredStream(STDOUT_LIMIT)  # store STDOUT in a measured stream
    start_time = get_timer()  # store a reference timer for our custom timeout
    try:
        proc.stdin.write(sinput.encode("utf-8"))  # write the input to STDIN
        proc.stdin.flush()  # flush the STDOUT buffer
        while True:  # our main listener loop
            line = proc.stdout.readline()  # read a line from the STDOUT
            # use proc.stdout.read(buf_size) instead to handle your own buffer
            if line != b"":  # content collected...
                sout.write(line)  # write it to our stream
            elif proc.poll() is not None:  # process finished, nothing to do
                break
            # finally, check the current time progress...
            if get_timer() >= start_time + TIMEOUT_LIMIT:
                raise TimeoutExpired(proc.args, TIMEOUT_LIMIT)
        ret = proc.poll()  # get the return code
    except TimeoutExpired:
        proc.kill()  # we're no longer interested in the process, kill it
        ret = __NR_TIMEOUT
    except MemoryError:
        ret = __NR_MEMORY_OUT
    except ValueError:  # max buffer reached
        proc.kill()  # we're no longer interested in the process, kill it
        ret = __NR_MAX_STDOUT_EXCEEDED
    sout.seek(0)  # rewind the buffer
    return ret, sout.read().decode("utf-8")  # send the results back

if __name__ == "__main__":
    ret, out, err = run_program(['./example.sh'], timeout=8)
    print("return code: %i\n" % ret)
    print("stdout:\n%s" % out)
    print("stderr:\n%s" % err)
</code>```

There are two 'issues' with this, tho, the first one being quite obvious - I'm piping the subprocesses STDERR to STDOUT so the result would be a mix in. Since reading from STDOUT and STDERR streams is a blocking operation, if you want to read them both separately you'll have to spawn two threads (and separately handle their ValueError exceptions when a stream size is exceeded). The second issue is that the subprocesses STDOUT can lock out the timeout check as it depends on STDOUT actually flushing some data. This can also be solved by a separate timer thread that will forcefully kill the process if the timeout is exceeded. In fact, that's exactly what Popen.communicate() does.

The principle of operation would essentially be the same, you'll just have to outsource the checks to separate threads and join everything back in the end. That's an exercise I'll leave to you ;)

As for your second missing feature, could you elaborate a bit more what you have in mind?

Body:
I am trying to build a Python sandbox for running student's code in a minimal and safe environment. I intend to run it into a container and to limit its access to the resources of that container. So, I am currently designing the part of the sandbox that is supposed to run into the container and handle the access to the resources.

For now, my specification is to limit the amount of time and memory used by the process. I also need to be able to communicate with the process through the stdin and to catch the retcode, stdout and stderr at the end of the execution.

Moreover, the program may enter in an infinite loop and fill-up the memory through the stdout or stderr (I had one student's program that crashed my container because of that). So, I want also to be able to limit the size of the recovered stdout and stderr (after a certain limit is reached I can just kill the process and ignore the rest of the output. I do not care about these extra data as it is most likely a buggy program and it should be discarded).

For now, my sandbox is catching almost everything, meaning that I can:

Set a timeout as I want;

Set a limit to the memory used in the process;

Feed the process through a stdin (for now a given string);

Get the final retcode, stdout and stderr.

Here is my current code (I tried to keep it small for the example):

MEMORY_LIMIT  = 64 * 1024 * 1024
TIMEOUT_LIMIT = 5 * 60

__NR_FILE_NOT_FOUND = -1
__NR_TIMEOUT        = -2
__NR_MEMORY_OUT     = -3

def limit_memory(memory):
    import resource
    return lambda :resource.setrlimit(resource.RLIMIT_AS, (memory, memory))

def run_program(cmd, sinput='', timeout=TIMEOUT_LIMIT, memory=MEMORY_LIMIT):
    """Run the command line and output (ret, sout, serr)."""
    from subprocess import Popen, PIPE
    try:
        proc =  Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE,
                      preexec_fn=limit_memory(memory))
    except FileNotFoundError:
        return (__NR_FILE_NOT_FOUND, "", "")

    sout, serr = "".encode("utf-8"), "".encode("utf-8")
    try:
        sout, serr = proc.communicate(sinput.encode("utf-8"), timeout=timeout)
        ret = proc.wait()
    except subprocess.TimeoutExpired:
        ret = __NR_TIMEOUT
    except MemoryError:
        ret = __NR_MEMORY_OUT
    return (ret, sout.decode("utf-8"), serr.decode("utf-8"))

if __name__ == "__main__":
    ret, out, err = run_program(['./example.sh'], timeout=8)
    print("return code: %i\n" % ret)
    print("stdout:\n%s" % out)
    print("stderr:\n%s" % err)

The missing features are:

Set a limitation on the size of stdout and stderr. I looked on the Web and saw several attempts, but none is really working.

Attach a function to stdin better than just a static string. The function should connect to the pipes stdout and stderr and return bytes to stdin.

Does anyone has an idea about that ?

PS: I already looked at:

Non blocking reading from a subprocess output stream in Python;

Python subprocess with timeout and large output (>64K)

Body:
As I was saying, you can create your own buffers and write the STDOUT/STDERR to them, checking the size along the way. For convenience, you can write a small io.BytesIO wrapper to do the check for you, e.g.:

from io import BytesIO

# lets first create a size-controlled BytesIO buffer for convenience
class MeasuredStream(BytesIO):

    def __init__(self, maxsize=1024):  # lets use a 1 KB as a default
        super(MeasuredStream, self).__init__()
        self.maxsize = maxsize
        self.length = 0

    def write(self, b):
        if self.length + len(b) > self.maxsize:  # o-oh, max size exceeded
            # write only up to maxsize, truncate the rest
            super(MeasuredStream, self).write(b[:self.maxsize - self.length])
            raise ValueError("Max size reached, excess data is truncated")
        # plenty of space left, write the bytes and increase the length
        self.length += super(MeasuredStream, self).write(b)
        return len(b)  # convention: return the written number of bytes

Mind you, if you intend to do truncation / seek & replace you'll have to account for those in your length but this is enough for our purposes.

Anyway, now all you need to do is to handle your own streams and account for the possible ValueError from the MeasuredStream, instead of using Popen.communicate(). This, unfortunately, also means that you'll have to handle the timeout yourself. Something like:

from subprocess import Popen, PIPE, STDOUT, TimeoutExpired
import sys
import time

MEMORY_LIMIT  = 64 * 1024 * 1024
TIMEOUT_LIMIT = 5 * 60
STDOUT_LIMIT  = 1024 * 1024  # let's use 1 MB as a STDOUT limit

__NR_FILE_NOT_FOUND      = -1
__NR_TIMEOUT             = -2
__NR_MEMORY_OUT          = -3
__NR_MAX_STDOUT_EXCEEDED = -4  # let's add a new return code

# a cross-platform precision clock
get_timer = time.clock if sys.platform == "win32" else time.time

def limit_memory(memory):
    import resource
    return lambda :resource.setrlimit(resource.RLIMIT_AS, (memory, memory))

def run_program(cmd, sinput='', timeout=TIMEOUT_LIMIT, memory=MEMORY_LIMIT):
    """Run the command line and output (ret, sout, serr)."""
    from subprocess import Popen, PIPE, STDOUT
    try:
        proc =  Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT,
                      preexec_fn=limit_memory(memory), timeout=timeout)
    except FileNotFoundError:
        return (__NR_FILE_NOT_FOUND, "", "")
    sout = MeasuredStream(STDOUT_LIMIT)  # store STDOUT in a measured stream
    start_time = get_timer()  # store a reference timer for our custom timeout
    try:
        proc.stdin.write(sinput.encode("utf-8"))  # write the input to STDIN
        proc.stdin.flush()  # flush the STDOUT buffer
        while True:  # our main listener loop
            line = proc.stdout.readline()  # read a line from the STDOUT
            # use proc.stdout.read(buf_size) instead to handle your own buffer
            if line != b"":  # content collected...
                sout.write(line)  # write it to our stream
            elif proc.poll() is not None:  # process finished, nothing to do
                break
            # finally, check the current time progress...
            if get_timer() >= start_time + TIMEOUT_LIMIT:
                raise TimeoutExpired(proc.args, TIMEOUT_LIMIT)
        ret = proc.poll()  # get the return code
    except TimeoutExpired:
        proc.kill()  # we're no longer interested in the process, kill it
        ret = __NR_TIMEOUT
    except MemoryError:
        ret = __NR_MEMORY_OUT
    except ValueError:  # max buffer reached
        proc.kill()  # we're no longer interested in the process, kill it
        ret = __NR_MAX_STDOUT_EXCEEDED
    sout.seek(0)  # rewind the buffer
    return ret, sout.read().decode("utf-8")  # send the results back

if __name__ == "__main__":
    ret, out, err = run_program(['./example.sh'], timeout=8)
    print("return code: %i\n" % ret)
    print("stdout:\n%s" % out)
    print("stderr:\n%s" % err)

There are two 'issues' with this, tho, the first one being quite obvious - I'm piping the subprocesses STDERR to STDOUT so the result would be a mix in. Since reading from STDOUT and STDERR streams is a blocking operation, if you want to read them both separately you'll have to spawn two threads (and separately handle their ValueError exceptions when a stream size is exceeded). The second issue is that the subprocesses STDOUT can lock out the timeout check as it depends on STDOUT actually flushing some data. This can also be solved by a separate timer thread that will forcefully kill the process if the timeout is exceeded. In fact, that's exactly what Popen.communicate() does.

The principle of operation would essentially be the same, you'll just have to outsource the checks to separate threads and join everything back in the end. That's an exercise I'll leave to you ;)

As for your second missing feature, could you elaborate a bit more what you have in mind?


问:
Redirect user on login
I've been trying to figure this out for hours but everything I try fails. I'm trying login a user and on success get route the user to the correct url based on the user's role. In the example below, I login successfully, and the user is successfully identified however when I try to redirect or push.history it doesn't let me. There are no errors, it just stays on the login url.

I'm using:
React router 4, Meteorjs

```<code>handleSubmit(event) {
  event.preventDefault();

  Meteor.loginWithPassword(email, password, (error, result) => {
    if (error) {
      this.setState({ loginError: 'Incorrect username or password.' });
    } else {
      if (!!Roles.userIsInRole(Meteor.userId(), 'isAdmin')) {
        <Redirect to="/admin/dashboard" push />
      }
    }
  });
}
</code>```

答:
A react component is something that is rendered, it's not just a function that you can call from anywhere.

Use history.push('/admin/dashboard")

If the router is being passed into your component as a prop you might also find yourself doing

```<code>this.props.history.push('/admin/dashboard")
</code>```

Title: Redirect user on login

Body:
I've been trying to figure this out for hours but everything I try fails. I'm trying login a user and on success get route the user to the correct url based on the user's role. In the example below, I login successfully, and the user is successfully identified however when I try to redirect or push.history it doesn't let me. There are no errors, it just stays on the login url.

I'm using:
React router 4, Meteorjs

handleSubmit(event) {
  event.preventDefault();

  Meteor.loginWithPassword(email, password, (error, result) => {
    if (error) {
      this.setState({ loginError: 'Incorrect username or password.' });
    } else {
      if (!!Roles.userIsInRole(Meteor.userId(), 'isAdmin')) {
        <Redirect to="/admin/dashboard" push />
      }
    }
  });
}

Body:
A react component is something that is rendered, it's not just a function that you can call from anywhere.

Use history.push('/admin/dashboard")

If the router is being passed into your component as a prop you might also find yourself doing

this.props.history.push('/admin/dashboard")


答:
I believe this will get your local time from the string.

var x = '2017-11-29T10:27:15.2327188Z'
var d = new Date(x);
var time = d.getHours() + ':' +  d.getMinutes() +  ':' +  d.getSeconds()
console.log(time)```

Title: How to get time by this string in javascript 2017-11-29T10:27:15.2327188Z

Body: I have this string 2017-11-29T10:27:15.2327188Z I just need to get time in javascript any idea how ?


问:
Axios 400 error request call then instead of catch
I have this function:

```<code>add(App, Params, Callback){
    var self = this;

    var Data = self.process_fields(Params)

    self.$http.post(
        paths.api + '/app/' + App.Permalink,
        new URLSearchParams(Data)
    ).then(function (error, response) {
        console.log("then");
        if (typeof (Callback) == "function") {
            Callback(true, response.data.data);
        }
    }).catch(function(error){
        console.log("catch");
        if(typeof error.response !== "undefined"){
            errors.render(error.response.data.error)
        }

        if (typeof (Callback) == "function") {
            Callback(false, null);
        }
    });
}
</code>```

When i call request and recieve a 400 error, it calls then instead of catch:

答:
I found the solution

Problem caused by dont return promise in axios interceptors:

```<code>axios.interceptors.response.use((response) => {
    return response;
}, (error) => {
    if (!error.response) {
        alert('NETWORK ERROR')
    } else {
        const code = error.response.status
        const response = error.response.data
        const originalRequest = error.config;

        if (code === 401 && !originalRequest._retry) {
            originalRequest._retry = true

            auth.commit('logout');
            window.location.href = "/login";
        }

        return Promise.reject(error)
    }
});
</code>```

adding return Promise.reject(error) works like a charm

Body:
I have this function:

add(App, Params, Callback){
    var self = this;

    var Data = self.process_fields(Params)

    self.$http.post(
        paths.api + '/app/' + App.Permalink,
        new URLSearchParams(Data)
    ).then(function (error, response) {
        console.log("then");
        if (typeof (Callback) == "function") {
            Callback(true, response.data.data);
        }
    }).catch(function(error){
        console.log("catch");
        if(typeof error.response !== "undefined"){
            errors.render(error.response.data.error)
        }

        if (typeof (Callback) == "function") {
            Callback(false, null);
        }
    });
}

When i call request and recieve a 400 error, it calls then instead of catch:

Body:
I found the solution

Problem caused by dont return promise in axios interceptors:

axios.interceptors.response.use((response) => {
    return response;
}, (error) => {
    if (!error.response) {
        alert('NETWORK ERROR')
    } else {
        const code = error.response.status
        const response = error.response.data
        const originalRequest = error.config;

        if (code === 401 && !originalRequest._retry) {
            originalRequest._retry = true

            auth.commit('logout');
            window.location.href = "/login";
        }

        return Promise.reject(error)
    }
});

adding return Promise.reject(error) works like a charm


问:
Python- including a variable within the text part of parameters
So in Pygame have a function that displays messages to users:

```<code>def message_to_user(msg, color, X_displacement, Y_displacement):
    # creating function to display messages to the user
    message=font.render(msg,True,color)
    msgcenter=200+X_displacement,200+Y_displacement
    Game_display.blit(message,msgcenter)
</code>```

now there is a message I need to display with another variable showing aswell:

```<code>        message_to_user("You managed to complete",levelcounter,"levels",green,0,40)
</code>```

here is the error:

```<code>TypeError: message_to_user() takes exactly 4 arguments (6 given)
</code>```

I understand why I am getting this error, just can't figure a way around it

答:
You need to build the string before passing it to the function</p>

```<code>mess = "You managed to complete {} levels".format(levelcounter)
message_to_user(mess, green, 0, 40)
</code>```

Body:
So in Pygame have a function that displays messages to users:

def message_to_user(msg, color, X_displacement, Y_displacement):
    # creating function to display messages to the user
    message=font.render(msg,True,color)
    msgcenter=200+X_displacement,200+Y_displacement
    Game_display.blit(message,msgcenter)

now there is a message I need to display with another variable showing aswell:

        message_to_user("You managed to complete",levelcounter,"levels",green,0,40)

here is the error:

TypeError: message_to_user() takes exactly 4 arguments (6 given)

I understand why I am getting this error, just can't figure a way around it

Body:
You need to build the string before passing it to the function

mess = "You managed to complete {} levels".format(levelcounter)
message_to_user(mess, green, 0, 40)


问:
Overriding Original image using pillow in python
I'm trying to edit an image using pillow. I see we have only options to save the edited image in new file.

Is there a way to override the original image while saving the edited image in pillow? just to know.

答:
You can specify any path for a new file. If you want to replace original file - just use original file path as a new path:</p>

```<code>from PIL import Image

size = (128, 128)
original_file_path = 'folder/file.jpg'

try:
    im = Image.open(original_file_path)
    im.thumbnail(size)
    im.save(original_file_path)
except IOError:
    print("cannot create thumbnail for", original_file_path)
</code>```

Body:
You can specify any path for a new file. If you want to replace original file - just use original file path as a new path:

from PIL import Image

size = (128, 128)
original_file_path = 'folder/file.jpg'

try:
    im = Image.open(original_file_path)
    im.thumbnail(size)
    im.save(original_file_path)
except IOError:
    print("cannot create thumbnail for", original_file_path)


问:
Initializing array inside struct
I'm trying to initialize an array inside a struct, Like this.

I want the array to have the size of row*col.

Here is part of the code:

```<code>struct tbl{
    int col;
    int row;
    char** elem [col*row];
};

int main(int argc, char** argv){

    int i, row, col;
    col = row = 0;
    bool loop = true;
    char c;
    col = col/row;

    table tab;
    tab.row = row;
    tab.col = col;

    return 0;
}
</code>```

答:
You can't declare a struct in that manner.  One thing people have done is to set their array to the end of the struct and then use malloc to leave extra space for the array in the struct.  Something like this:</p>

```<code>typedef struct {
    int row;
    int col;
    char **elem[];
} table;

void some_func() {
    int row = 5;
    int col = 5;
    table *tab = malloc(sizeof(table) + ((row * col) * sizeof(char **)));
    tab->row = row;
    tab->col = col;
    // now do whatever you need to with your new struct
    // that holds an array of 25 char ** elements
}
</code>```

Title: Initializing array inside struct

Body:
I'm trying to initialize an array inside a struct, Like this.

I want the array to have the size of row*col.

Here is part of the code:

struct tbl{
    int col;
    int row;
    char** elem [col*row];
};

int main(int argc, char** argv){

    int i, row, col;
    col = row = 0;
    bool loop = true;
    char c;
    col = col/row;

    table tab;
    tab.row = row;
    tab.col = col;

    return 0;
}

Body:
You can't declare a struct in that manner.  One thing people have done is to set their array to the end of the struct and then use malloc to leave extra space for the array in the struct.  Something like this:

typedef struct {
    int row;
    int col;
    char **elem[];
} table;

void some_func() {
    int row = 5;
    int col = 5;
    table *tab = malloc(sizeof(table) + ((row * col) * sizeof(char **)));
    tab->row = row;
    tab->col = col;
    // now do whatever you need to with your new struct
    // that holds an array of 25 char ** elements
}


问:
How to use scipy.sparse vstack python
I have a vstack which consists of two different matrices.

```<code>im = imread('input.jpg')
dxy = spnabla(im.shape[0], im.shape[1])
def spnabla(M, N):
    dx = spnabla_x(M, N)
    dy = spnabla_y(M, N)
    dxy = sp.vstack((dx, dy))
    return dxy

def spnabla_x(M, N):
    a = np.append(np.ones(N-1), 0)
    dx = sp.diags([np.tile(-a, M), np.tile(a, M)], [0, 1], (M*N, M*N))
    return dx.tocsr()

def spnabla_y(M, N):
    b = np.append(np.tile(np.ones(N), M-1), np.zeros(N))
    dy = sp.diags([-b, b], [0, N], (M*N,M*N))
    return dy.tocsr()
</code>```

How can I access dx and dy within the dxy vstack? I would like to display dx and dy as an image. Is that possible?

Thanks for the help.

答:
sp.vstack concatenates the matrices vertically, just as np.vstack does (except it works with the coo attributes of the componenets).

```<code>In [93]: dx = spnabla_x(10,10)
In [94]: dy = spnabla_y(10,10)
In [95]: dx
Out[95]:
<100x100 sparse matrix of type '<class 'numpy.float64'>'
    with 180 stored elements in Compressed Sparse Row format>
In [96]: dy
Out[96]:
<100x100 sparse matrix of type '<class 'numpy.float64'>'
    with 180 stored elements in Compressed Sparse Row format>
In [97]: dx.A
Out[97]:
array([[-1.,  1.,  0., ...,  0.,  0.,  0.],
       [ 0., -1.,  1., ...,  0.,  0.,  0.],
       [ 0.,  0., -1., ...,  0.,  0.,  0.],
       ...,
       [ 0.,  0.,  0., ..., -1.,  1.,  0.],
       [ 0.,  0.,  0., ...,  0., -1.,  1.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.]])
In [98]: dy.A
Out[98]:
array([[-1.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0., -1.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0., -1., ...,  0.,  0.,  0.],
       ...,
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.]])
In [99]: dxy = sp.vstack((dx,dy))
In [100]: dxy
Out[100]:
<200x100 sparse matrix of type '<class 'numpy.float64'>'
    with 360 stored elements in Compressed Sparse Row format>

In [101]: dxy
Out[101]:
<200x100 sparse matrix of type '<class 'numpy.float64'>'
    with 360 stored elements in Compressed Sparse Row format>
In [102]: np.allclose(dxy[:100,:].A,dx.A)
</code>```

So the first N rows of dxy are the same as the dx, etc.  I should warn that indexing of sparse matrices is much slower than for regular numpy arrays.  And it does not create a view; it's a new matrix with its own data.  Unless you need to do some calculation with the whole dxy, there isn't much point in stacking dx and dy.

Title: How to use scipy.sparse vstack python

Body:
I have a vstack which consists of two different matrices.

im = imread('input.jpg')
dxy = spnabla(im.shape[0], im.shape[1])
def spnabla(M, N):
    dx = spnabla_x(M, N)
    dy = spnabla_y(M, N)
    dxy = sp.vstack((dx, dy))
    return dxy

def spnabla_x(M, N):
    a = np.append(np.ones(N-1), 0)
    dx = sp.diags([np.tile(-a, M), np.tile(a, M)], [0, 1], (M*N, M*N))
    return dx.tocsr()

def spnabla_y(M, N):
    b = np.append(np.tile(np.ones(N), M-1), np.zeros(N))
    dy = sp.diags([-b, b], [0, N], (M*N,M*N))
    return dy.tocsr()

How can I access dx and dy within the dxy vstack? I would like to display dx and dy as an image. Is that possible?

Thanks for the help.

Body:
sp.vstack concatenates the matrices vertically, just as np.vstack does (except it works with the coo attributes of the componenets).

In [93]: dx = spnabla_x(10,10)
In [94]: dy = spnabla_y(10,10)
In [95]: dx
Out[95]:
<100x100 sparse matrix of type '<class 'numpy.float64'>'
    with 180 stored elements in Compressed Sparse Row format>
In [96]: dy
Out[96]:
<100x100 sparse matrix of type '<class 'numpy.float64'>'
    with 180 stored elements in Compressed Sparse Row format>
In [97]: dx.A
Out[97]:
array([[-1.,  1.,  0., ...,  0.,  0.,  0.],
       [ 0., -1.,  1., ...,  0.,  0.,  0.],
       [ 0.,  0., -1., ...,  0.,  0.,  0.],
       ...,
       [ 0.,  0.,  0., ..., -1.,  1.,  0.],
       [ 0.,  0.,  0., ...,  0., -1.,  1.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.]])
In [98]: dy.A
Out[98]:
array([[-1.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0., -1.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0., -1., ...,  0.,  0.,  0.],
       ...,
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.]])
In [99]: dxy = sp.vstack((dx,dy))
In [100]: dxy
Out[100]:
<200x100 sparse matrix of type '<class 'numpy.float64'>'
    with 360 stored elements in Compressed Sparse Row format>

In [101]: dxy
Out[101]:
<200x100 sparse matrix of type '<class 'numpy.float64'>'
    with 360 stored elements in Compressed Sparse Row format>
In [102]: np.allclose(dxy[:100,:].A,dx.A)

So the first N rows of dxy are the same as the dx, etc.  I should warn that indexing of sparse matrices is much slower than for regular numpy arrays.  And it does not create a view; it's a new matrix with its own data.  Unless you need to do some calculation with the whole dxy, there isn't much point in stacking dx and dy.


问:
How do you display a Toast from a background thread on Android?
How can I display Toast messages from a thread? </p>

答:
I made this approach based on mjaggard answer:

```<code>public static void toastAnywhere(final String text) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        public void run() {
            Toast.makeText(SuperApplication.getInstance().getApplicationContext(), text,
                    Toast.LENGTH_LONG).show();
        }
    });
}
</code>```

Worked well for me.

ContentLicense: CC BY-SA 4.0

Body:
I made this approach based on mjaggard answer:

public static void toastAnywhere(final String text) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        public void run() {
            Toast.makeText(SuperApplication.getInstance().getApplicationContext(), text,
                    Toast.LENGTH_LONG).show();
        }
    });
}

Worked well for me.


问:
What Font and Font size is used in iPhone SMS Application?
Does anyone know what Font Type (e.g. Arial, Courier new, etc) and Font Size (e.g. 9 pt, etc) is used in SMS Application of iPhone.

I need this info to create iPhone app which uses SMS API.

答:
I believe it uses the system font and it's around 17.

```<code>UIFont *font = [UIFont systemFontOfSize:17.0];
</code>```

Just increase or decrease the font size and compare to Messages.app.

Body:
I believe it uses the system font and it's around 17.

UIFont *font = [UIFont systemFontOfSize:17.0];

Just increase or decrease the font size and compare to Messages.app.


问:
Java remote debugging - how can I keep debugger listening?
I'm using IntelliJ IDEA to remote debug a Java CLI program with the debugger listening for connections.

This works fine for the first invocation, but the debugger stops listening after the CLI program disconnects. I want the debugger to keep listening since multiple CLI invocations will be made (in sequence, not in parallel) and only one of these will trigger the breakpoint I've set.

Here's my client debug config:

```<code>-agentlib:jdwp=transport=dt_socket,server=n,address=5005,suspend=y
</code>```

Is it possible to keep the debugger listening?

答:
It depends also what you are trying to achieve.
If you want to check what parameters are passed to your CLI you can just log them to the file or save any information that you need in DB (or file as well).</p>

Body:
I'm using IntelliJ IDEA to remote debug a Java CLI program with the debugger listening for connections.

This works fine for the first invocation, but the debugger stops listening after the CLI program disconnects. I want the debugger to keep listening since multiple CLI invocations will be made (in sequence, not in parallel) and only one of these will trigger the breakpoint I've set.

Here's my client debug config:

-agentlib:jdwp=transport=dt_socket,server=n,address=5005,suspend=y

Is it possible to keep the debugger listening?


问:
PhpStorm configuration to see more rows?
How to configure PhpStorm to show me more rows .. Examples:

So same code in Atom (and other editors):

Same code, but other editors show me more code (rows) PhpStorm - 14, Atom - 23. How to fix it ?

答: Goto settings ->Editor ->Colours and Fonts-> Font tab there is line spacing option decrease that to 1 or <1 then you can see more rows on screen .</p>


问:
jquery use a var with focus()
when I write:

$('#telPro').focus(); //telPro is the id of an input

focus is given to the telPro input.

But if I construct a var like this :

b = "$"+"("+"'"+"#"+"telPro"+"'"+")";

who gives $('#telPro') and write

b.focus();

I get the error : TypeError: b.focus is not a function

Can someone explain me what and btw how can I do.

Thanks for answer

答:
Because .focus() is not a function on a string.  And b is a string:

```<code>b = "$"+"("+"'"+"#"+"telPro"+"'"+")";
</code>```

If you want b to be a jQuery object, don't wrap your code in quotes.  Only wrap your strings in quotes:

```<code>b = $("#"+"telPro");
</code>```

Which, of course, is identical to:

```<code>b = $("#telPro");
</code>```

Strings which contain text which happens to be code are not themselves code.  They're just strings.

(Side note: You might be looking for eval().  But you probably really shouldn't be.)

Title: jquery use a var with focus()

Body:
Because .focus() is not a function on a string.  And b is a string:

b = "$"+"("+"'"+"#"+"telPro"+"'"+")";

If you want b to be a jQuery object, don't wrap your code in quotes.  Only wrap your strings in quotes:

b = $("#"+"telPro");

Which, of course, is identical to:

b = $("#telPro");

Strings which contain text which happens to be code are not themselves code.  They're just strings.

(Side note: You might be looking for eval().  But you probably really shouldn't be.)


问:
Too many fields defined
I've a weird issue with MS access 2007.
If I run the following query:

```<code>SELECT QUERY_LNK_ORDERS_ITEMS.*, QUERY_LNK_ERASALES_ERACOND.*
FROM QUERY_LNK_ORDERS_ITEMS
INNER JOIN QUERY_LNK_ERASALES_ERACOND
ON QUERY_LNK_ORDERS_ITEMS.concat = QUERY_LNK_ERASALES_ERACOND.concat
</code>```

It works, no troubles, then I want to include missing records with left/right join so I run:

```<code>SELECT QUERY_LNK_ORDERS_ITEMS.*, QUERY_LNK_ERASALES_ERACOND.*
FROM QUERY_LNK_ORDERS_ITEMS
INNER JOIN QUERY_LNK_ERASALES_ERACOND
ON QUERY_LNK_ORDERS_ITEMS.concat = QUERY_LNK_ERASALES_ERACOND.concat
UNION ALL
SELECT QUERY_LNK_ORDERS_ITEMS.*, QUERY_LNK_ERASALES_ERACOND.*
FROM QUERY_LNK_ORDERS_ITEMS
LEFT JOIN QUERY_LNK_ERASALES_ERACOND
ON QUERY_LNK_ORDERS_ITEMS.concat = QUERY_LNK_ERASALES_ERACOND.concat
WHERE QUERY_LNK_ORDERS_ITEMS.concat IS NULL
UNION ALL
SELECT QUERY_LNK_ORDERS_ITEMS.*, QUERY_LNK_ERASALES_ERACOND.*
FROM QUERY_LNK_ORDERS_ITEMS
RIGHT JOIN QUERY_LNK_ERASALES_ERACOND
ON QUERY_LNK_ORDERS_ITEMS.concat = QUERY_LNK_ERASALES_ERACOND.concat
WHERE QUERY_LNK_ERASALES_ERACOND.concat IS NULL
</code>```

And I get: too many fields defined

I don't understand... I'm selecting the exact amount of fields, where is this error coming from guys?

Thanks in advance
Cheers

答:
Did you get an answer to this one other way might lie in separating these and combining in a recordset.</p>

```<code>Set rs = db.OpenRecordset(SQL1)
Set rs1 = db.OpenRecordset(SQL2)
Set rs2 = db.OpenRecordset(SQL3)
 .......
</code>```

Title: Too many fields defined

Body:
I've a weird issue with MS access 2007.
If I run the following query:

SELECT QUERY_LNK_ORDERS_ITEMS.*, QUERY_LNK_ERASALES_ERACOND.*
FROM QUERY_LNK_ORDERS_ITEMS
INNER JOIN QUERY_LNK_ERASALES_ERACOND
ON QUERY_LNK_ORDERS_ITEMS.concat = QUERY_LNK_ERASALES_ERACOND.concat

It works, no troubles, then I want to include missing records with left/right join so I run:

SELECT QUERY_LNK_ORDERS_ITEMS.*, QUERY_LNK_ERASALES_ERACOND.*
FROM QUERY_LNK_ORDERS_ITEMS
INNER JOIN QUERY_LNK_ERASALES_ERACOND
ON QUERY_LNK_ORDERS_ITEMS.concat = QUERY_LNK_ERASALES_ERACOND.concat
UNION ALL
SELECT QUERY_LNK_ORDERS_ITEMS.*, QUERY_LNK_ERASALES_ERACOND.*
FROM QUERY_LNK_ORDERS_ITEMS
LEFT JOIN QUERY_LNK_ERASALES_ERACOND
ON QUERY_LNK_ORDERS_ITEMS.concat = QUERY_LNK_ERASALES_ERACOND.concat
WHERE QUERY_LNK_ORDERS_ITEMS.concat IS NULL
UNION ALL
SELECT QUERY_LNK_ORDERS_ITEMS.*, QUERY_LNK_ERASALES_ERACOND.*
FROM QUERY_LNK_ORDERS_ITEMS
RIGHT JOIN QUERY_LNK_ERASALES_ERACOND
ON QUERY_LNK_ORDERS_ITEMS.concat = QUERY_LNK_ERASALES_ERACOND.concat
WHERE QUERY_LNK_ERASALES_ERACOND.concat IS NULL

And I get: too many fields defined

I don't understand... I'm selecting the exact amount of fields, where is this error coming from guys?

Thanks in advance
Cheers

Body:
Did you get an answer to this one other way might lie in separating these and combining in a recordset.

Set rs = db.OpenRecordset(SQL1)
Set rs1 = db.OpenRecordset(SQL2)
Set rs2 = db.OpenRecordset(SQL3)
 .......


问:
Session, cookies and ids
It was suggested to me to use sessions for cross page storage, and maintain the session ID by storing it in a GET parameter or cookie.

What's the safest way to save data into a session and make it last forever (like login informations)?

答:
Imagine a community, users post links and external images.

To keep the session alive the page makes use of GET instead of cookies.

So: a user watches an external image or clicks on a external link.
The owner of the external ressource will now be able to read the REFERER, and by this he can see the session-ID and hijack the session.

That's why most communities and similar pages put a proxy between the page and the external ressource, they strip the SESSION-ID if it is stored via GET.<edited/>

Title: Session, cookies and ids


问:
Why can't I call my function in a SQL statement?
I create a package that executes my function in a SELECT statement right inside that same page:

```<code>CREATE OR REPLACE PACKAGE p
   AUTHID DEFINER
IS
   FUNCTION f
      RETURN NUMBER;
END;
/

CREATE OR REPLACE PACKAGE BODY p
IS
   FUNCTION ff RETURN NUMBER
   IS
   BEGIN
      RETURN 73;
   END;

   FUNCTION f RETURN NUMBER
   IS
      l_number   NUMBER;
   BEGIN
      SELECT 42 INTO l_number
        FROM DUAL
       WHERE ff () = 73;

      RETURN l_number;
   END;
END;
/

BEGIN
   DBMS_OUTPUT.put_line (p.f);
END;
/
</code>```

But when I try to execute that function, I get the PLS-00231 compile error:

```<code>BEGIN
   dbms_output.put_line (P.F);
END;
/

PLS-00231: function 'FF' may not be used in SQL
</code>```

The function is declared right there. It doesn't execute any non-query DML. It doesn't have any PL/SQL-specific datatypes in the header.

Why can't SQL use/see it?

答:
Here's the bottom line:

If you want to call a function from within a SQL statement, then it must declared at the schema level (CREATE FUNCTION) or be defined in the specification of a package. This is true even if your SQL statement is inside a subprogram in the same package as the function called.

So if I change the package specification as follows, exposing the the formerly-private function, all is well:

```<code>CREATE OR REPLACE PACKAGE p AUTHID DEFINER
IS
   FUNCTION f RETURN NUMBER;
   FUNCTION ff RETURN NUMBER;
END;
/
</code>```

And notice, interestingly, that you do not have to qualify the name of the function with the package name, inside the static SQL statement. The PL/SQL compiler sorts that out before passing the statement over to the SQL engine.

If you execute the SQL dynamically, however, the package name will be needed, as in:

```<code>FUNCTION f RETURN NUMBER
IS
   l_number NUMBER;
BEGIN
   EXECUTE IMMEDIATE
      'SELECT 42 FROM DUAL WHERE p.ff () = 73'
      INTO l_number;

   RETURN l_number;
END;
</code>```

Body:
I create a package that executes my function in a SELECT statement right inside that same page:

CREATE OR REPLACE PACKAGE p
   AUTHID DEFINER
IS
   FUNCTION f
      RETURN NUMBER;
END;
/

CREATE OR REPLACE PACKAGE BODY p
IS
   FUNCTION ff RETURN NUMBER
   IS
   BEGIN
      RETURN 73;
   END;

   FUNCTION f RETURN NUMBER
   IS
      l_number   NUMBER;
   BEGIN
      SELECT 42 INTO l_number
        FROM DUAL
       WHERE ff () = 73;

      RETURN l_number;
   END;
END;
/

BEGIN
   DBMS_OUTPUT.put_line (p.f);
END;
/

But when I try to execute that function, I get the PLS-00231 compile error:

BEGIN
   dbms_output.put_line (P.F);
END;
/

PLS-00231: function 'FF' may not be used in SQL

The function is declared right there. It doesn't execute any non-query DML. It doesn't have any PL/SQL-specific datatypes in the header.

Why can't SQL use/see it?

Body:
Here's the bottom line:

If you want to call a function from within a SQL statement, then it must declared at the schema level (CREATE FUNCTION) or be defined in the specification of a package. This is true even if your SQL statement is inside a subprogram in the same package as the function called.

So if I change the package specification as follows, exposing the the formerly-private function, all is well:

CREATE OR REPLACE PACKAGE p AUTHID DEFINER
IS
   FUNCTION f RETURN NUMBER;
   FUNCTION ff RETURN NUMBER;
END;
/

And notice, interestingly, that you do not have to qualify the name of the function with the package name, inside the static SQL statement. The PL/SQL compiler sorts that out before passing the statement over to the SQL engine.

If you execute the SQL dynamically, however, the package name will be needed, as in:

FUNCTION f RETURN NUMBER
IS
   l_number NUMBER;
BEGIN
   EXECUTE IMMEDIATE
      'SELECT 42 FROM DUAL WHERE p.ff () = 73'
      INTO l_number;

   RETURN l_number;
END;


问:
Using Css to prevent wrapping of text with previous text?
Is there a CSS way to prevent a text element from wrapping from a previous text element?

i.e.
My Table Header  shows as

My

Table

Header

MySearchIcon

But I want it to display like this:

My

Table

Header MySearchIcon

The actual code is a combination of Razor and Html

```<code>  <th>
   @Html.DisplayNameFor(m => m.Projects.FirstOrDefault().Name) <i class="fa fa-search smaller fa-fade"></i>
  </th>
</code>```

This is in a header of a table and depending on the header length I do want wrapping but I want a space and the icon to be stuck to the last word in the header and not wrap.

Because of the Razor piece of the code I can't place the non-breaking space up against the output directly,

答:
I believe you can use white-space:nowrap; in your css.

You can also examine this question:
HTML+CSS: How to force div contents to stay in one line?

Body:
Is there a CSS way to prevent a text element from wrapping from a previous text element?

i.e.
My Table Header  shows as

My

Table

Header

MySearchIcon

But I want it to display like this:

My

Table

Header MySearchIcon

The actual code is a combination of Razor and Html

   @Html.DisplayNameFor(m => m.Projects.FirstOrDefault().Name)

This is in a header of a table and depending on the header length I do want wrapping but I want a space and the icon to be stuck to the last word in the header and not wrap.

Because of the Razor piece of the code I can't place the non-breaking space up against the output directly,


问:
How to format and query a PostgreSQL JSON into n column rows in sql
I would like to use a json and be able to display it into three column rows as follow.

```<code>scores median sigma
------ ------ -----
BF2D   0.5    0.67
BF2DSL 0.6    0.89
</code>```

First, I have a hard time to format it.
Second, what would be the format suitable so that I can display it into three column rows. Have a feeling that I should use array representation?
The json_to_record(json) function seems interesting for my usecase, but i need help.

```<code>SELECT * from json_to_record('{"version": "1.0", "BF2D": [{"median": 0.5}, {"sigma": 0.67}], "BF2DSL": [{"median": 0.6}, {"sigma": 0.89}]}'::JSON) as x(median FLOAT, sigma FLOAT);

 median | sigma
--------+--------
 (NULL) | (NULL)

Not what i am looking for
</code>```

I tried to use nested arrays, but unable to format it into a json

```<code>SELECT '{"version": "1.0", "scores": [{ "BF2D": [{"median": 0.5}, {"sigma": 0.67}] }, { "BF2DSL": [{"median": 0.6}, {"sigma": 0.89}] }]'::JSON;
</code>```

答:
Got it!

We can retreive the base level keys as follow:

```<code>SELECT * FROM json_object_keys('{"version": "1.0", "BF2D": {"avg": 0.5, "max": 99}, "BF2DSL": {"avg": 0.9, "max": 67}}'::JSON) scores WHERE scores<>'version';
 scores
--------
 BF2D
 BF2DSL
</code>```

We can get the key/values for a specific base level key, e.g., for BF2D as follow

```<code>SELECT * FROM json_each('{"version": "1.0", "BF2D": {"avg": 0.5, "max": 99}, "BF2DSL": {"avg": 0.9, "max": 67}}'::JSON->'BF2D');
 KEY | value
-----+-------
 avg | 0.5
 max | 99
</code>```

But, cannot use the above two queries to get 3 column rows

```<code>SELECT scores, json_each('{"version": "1.0", "BF2D": {"avg": 0.5, "max": 99}, "BF2DSL": {"avg": 0.9, "max": 67}}'::JSON->scores)
FROM (SELECT * FROM json_object_keys('{"version": "1.0", "BF2D": {"avg": 0.5, "max": 99}, "BF2DSL": {"avg": 0.9, "max": 67}}'::JSON) scores WHERE scores<>'version') t;
 scores | json_each
--------+-----------
 BF2D   | (avg,0.5)
 BF2D   | (max,99)
 BF2DSL | (avg,0.9)
 BF2DSL | (max,67)
</code>```

Finally, we can display the result into separate columns as follow

```<code>WITH p AS
  (SELECT '{"version": "1.0", "BF2D": {"avg": 0.5, "max": 99, "sigma": 0.1}, "BF2DSL": {"avg": 0.9, "max": 67}}'::JSON AS jval),
t AS
  (SELECT jval,json_object_keys(jval) cod FROM p),
scores AS
  (SELECT * FROM t WHERE cod<>'version')
SELECT cod,t.* FROM scores,json_each(jval->cod) t;

  cod   |  key  | value
--------+-------+-------
 BF2D   | avg   | 0.5
 BF2D   | max   | 99
 BF2D   | sigma | 0.1
 BF2DSL | avg   | 0.9
 BF2DSL | max   | 67
</code>```

Body:
I would like to use a json and be able to display it into three column rows as follow.

scores median sigma
------ ------ -----
BF2D   0.5    0.67
BF2DSL 0.6    0.89

First, I have a hard time to format it.
Second, what would be the format suitable so that I can display it into three column rows. Have a feeling that I should use array representation?
The json_to_record(json) function seems interesting for my usecase, but i need help.

SELECT * from json_to_record('{"version": "1.0", "BF2D": [{"median": 0.5}, {"sigma": 0.67}], "BF2DSL": [{"median": 0.6}, {"sigma": 0.89}]}'::JSON) as x(median FLOAT, sigma FLOAT);

 median | sigma
--------+--------
 (NULL) | (NULL)

Not what i am looking for

I tried to use nested arrays, but unable to format it into a json

SELECT '{"version": "1.0", "scores": [{ "BF2D": [{"median": 0.5}, {"sigma": 0.67}] }, { "BF2DSL": [{"median": 0.6}, {"sigma": 0.89}] }]'::JSON;

Body:
Got it!

We can retreive the base level keys as follow:

SELECT * FROM json_object_keys('{"version": "1.0", "BF2D": {"avg": 0.5, "max": 99}, "BF2DSL": {"avg": 0.9, "max": 67}}'::JSON) scores WHERE scores<>'version';
 scores
--------
 BF2D
 BF2DSL

We can get the key/values for a specific base level key, e.g., for BF2D as follow

SELECT * FROM json_each('{"version": "1.0", "BF2D": {"avg": 0.5, "max": 99}, "BF2DSL": {"avg": 0.9, "max": 67}}'::JSON->'BF2D');
 KEY | value
-----+-------
 avg | 0.5
 max | 99

But, cannot use the above two queries to get 3 column rows

SELECT scores, json_each('{"version": "1.0", "BF2D": {"avg": 0.5, "max": 99}, "BF2DSL": {"avg": 0.9, "max": 67}}'::JSON->scores)
FROM (SELECT * FROM json_object_keys('{"version": "1.0", "BF2D": {"avg": 0.5, "max": 99}, "BF2DSL": {"avg": 0.9, "max": 67}}'::JSON) scores WHERE scores<>'version') t;
 scores | json_each
--------+-----------
 BF2D   | (avg,0.5)
 BF2D   | (max,99)
 BF2DSL | (avg,0.9)
 BF2DSL | (max,67)

Finally, we can display the result into separate columns as follow

WITH p AS
  (SELECT '{"version": "1.0", "BF2D": {"avg": 0.5, "max": 99, "sigma": 0.1}, "BF2DSL": {"avg": 0.9, "max": 67}}'::JSON AS jval),
t AS
  (SELECT jval,json_object_keys(jval) cod FROM p),
scores AS
  (SELECT * FROM t WHERE cod<>'version')
SELECT cod,t.* FROM scores,json_each(jval->cod) t;

  cod   |  key  | value
--------+-------+-------
 BF2D   | avg   | 0.5
 BF2D   | max   | 99
 BF2D   | sigma | 0.1
 BF2DSL | avg   | 0.9
 BF2DSL | max   | 67