问:
UIGestureRecognizer in Swift Playgrounds
I am trying to integrate UIGestureRecognizer into my swift playground so that wherever I tap in my playground, my sprite goes to that point. I've tried everything! Watching countless youtube videos, and going on stack overflow for answers but everyone starts with making a class called view that is a UIView and in their code they keep referring to "self". I instead made a variable named "view" that was a SKView. I try to get parts of their code, put it in mine, and change it, but it just doesn't work. Here's the work that I got so far.

```<code>view.addGestureRecognizer(UIGestureRecognizer(target: view, action:  #selector(handleTap(sender:))))

func handleTap(sender: UITapGestureRecognizer) {
        player.position = sender.location(in: view)
}
</code>```

My playground keeps telling me that i'm using an unresolved identifier 'handleTap(sender:)'

答:
I think you need to add the @objc mark in front of the function declaration, so that handleTap will be visible to #selector.

```<code>@objc func handleTap(sender: UITapGestureRecognizer) {
    player.position = sender.location(in: view)
}
</code>```

Body:
I am trying to integrate UIGestureRecognizer into my swift playground so that wherever I tap in my playground, my sprite goes to that point. I've tried everything! Watching countless youtube videos, and going on stack overflow for answers but everyone starts with making a class called view that is a UIView and in their code they keep referring to "self". I instead made a variable named "view" that was a SKView. I try to get parts of their code, put it in mine, and change it, but it just doesn't work. Here's the work that I got so far.

view.addGestureRecognizer(UIGestureRecognizer(target: view, action:  #selector(handleTap(sender:))))

func handleTap(sender: UITapGestureRecognizer) {
        player.position = sender.location(in: view)
}

My playground keeps telling me that i'm using an unresolved identifier 'handleTap(sender:)'

Body:
I think you need to add the @objc mark in front of the function declaration, so that handleTap will be visible to #selector.

@objc func handleTap(sender: UITapGestureRecognizer) {
    player.position = sender.location(in: view)
}


来源: stackexchange

问:
Ionic 2 input text autocomplete
I am using ionic 2.

I have an array value.

I need input text with autocomplete.

答:
Autocomplete is not support by input component.

but instead you can use:

select component. check this link.

Searchbar component. check this link

also check this ionic2-autocomplete

ContentLicense: CC BY-SA 4.0

Title: Ionic 2 input text autocomplete

ContentLicense: CC BY-SA 3.0


问:
Laravel Image Upload using ajax 500 Internal Server Error
I am trying to upload image using ajax in laravel 5.2.but still i am getting error 500 Internal Server Error in route.
when i am trying to  upload  image using ajax request the browser shown correct route path but still i am not getting reason why it still showing error to me.

HTML

```<code><!-- CHANGE AVATAR TAB -->
                        <div class="tab-pane" id="tab_1_2">

                            <div class="uploadimagediv"></div>
                                {{ Form::open(array('url' => 'admin/avatar','method'=>'post','files'=>'true','id'=>'updateprofileimage'))  }}

                                <div class="form-group">
                                    <div class="fileinput fileinput-new" data-provides="fileinput">
                                        <div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
                                            <img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image" alt=""/>
                                        </div>
                                        <div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;">
                                        </div>
                                        <div>
                                            <span class="btn default btn-file">
                                            <span class="fileinput-new">
                                            Select image </span>
                                            <span class="fileinput-exists">
                                            Change </span>
                                            <p class="text-danger" id="error_image"></p>
                                            <input type="file" id="picture" name="picture"/>
                                            {{--{{ Form::file('picture') }}--}}
                                            </span>
                                            <span class="error alert-danger">{{ $errors->first('picture') }}</span>
                                            <a href="javascript:;" class="btn default fileinput-exists" data-dismiss="fileinput">
                                            Remove </a>
                                        </div>
                                    </div>
                                    <div class="clearfix margin-top-10">

                                    </div>
                                </div>
                                <div class="margin-top-10">
                                    {{Form::hidden('id', 2, ["id"=>"id"])}}
                                    {{ Form::button('Upload',['id'=> 'updatepicture','class'=>'btn green-haze']) }}

                                    {{--{{ Form::submit('Submit',['class' => 'btn green-haze','name'=>'changeImage']) }}--}}
                                    <a href="javascript:;" class="btn default">
                                    Cancel </a>
                                </div>
                            {{ Form::close() }}
                        </div>
                        <!-- END CHANGE AVATAR TAB -->
</code>```

Route

```<code>Route::group(['prefix' => 'admin'], function ()
{
    Route::controller('/','DashboardController');
});
</code>```

Ajax

```<code>$(document).on('click', '#updatepicture', function($e)
{
    $e.preventDefault();
    // send an ajax request
    $("#error_image").empty();
    $.ajax(
    {

        url: 'avatar',
        processData: false,
        contentType: false,
        type: "post",//use for update
        data: new FormData($("#updateprofileimage")[0]),
        success: function(data)
        {
            if(data.status)
            {
                $("#uploadimagediv").html('<div class="alert alert-success"><button type="button" class="close">×</button>'+data.message+'</div>');
                window.setTimeout(function()
                {
                    $(".alert").fadeTo(500, 0).slideUp(500, function()
                    {
                        $(this).remove();
                    });
                }, 5000);
                $('.alert .close').on("click", function(e)
                {
                    $(this).parent().fadeTo(500, 0).slideUp(500);
                });
                //console.log(data);
                //$("#updateprofileimage")[0].reset();
                //window.location.href = "http://localhost/laravel/admin/profile";
            }
            else
            {
                errors = data.errors;

                for(error in errors)
                {
                    $("#error_"+error.title).html(error.message);
                }
            }
        },
        error: function(xhr)
        {
            if(xhr.status == 422)
            {
                errors = xhr.responseJSON;
                for(error in errors)
                {
                    $("#error_"+error).html(errors[error][0]);
                }
            }
        }
    });
});
</code>```

Error is :"NetworkError: 500 Internal Server Error - http://localhost/laravel/admin/avatar"

please suggest me where i am getting wrong.

Controller is

```<code>public function postAvatar(ImageUploadRequest $request)
{
  ---
}
</code>```

答:
```<code>Add the below line inside <head>
<meta name="csrf-token" content="{{ csrf_token() }}">

And add the below lines before your ajax call in javascript function
$.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
});

And don't forget to give permission to your storage folder
sudo chmod -R 777 storage
</code>```

Body:
I am trying to upload image using ajax in laravel 5.2.but still i am getting error 500 Internal Server Error in route.
when i am trying to  upload  image using ajax request the browser shown correct route path but still i am not getting reason why it still showing error to me.

HTML

                                {{ Form::open(array('url' => 'admin/avatar','method'=>'post','files'=>'true','id'=>'updateprofileimage'))  }}

                                            Select image

                                            Change

                                            <input type="file" id="picture" name="picture"/>
                                            {{--{{ Form::file('picture') }}--}}

                                            {{ $errors->first('picture') }}

                                            Remove

                                    {{Form::hidden('id', 2, ["id"=>"id"])}}
                                    {{ Form::button('Upload',['id'=> 'updatepicture','class'=>'btn green-haze']) }}

                                    {{--{{ Form::submit('Submit',['class' => 'btn green-haze','name'=>'changeImage']) }}--}}

                                    Cancel

                            {{ Form::close() }}

Route

Route::group(['prefix' => 'admin'], function ()
{
    Route::controller('/','DashboardController');
});

Ajax

$(document).on('click', '#updatepicture', function($e)
{
    $e.preventDefault();
    // send an ajax request
    $("#error_image").empty();
    $.ajax(
    {

        url: 'avatar',
        processData: false,
        contentType: false,
        type: "post",//use for update
        data: new FormData($("#updateprofileimage")[0]),
        success: function(data)
        {
            if(data.status)
            {
                $("#uploadimagediv").html('
<button type="button" class="close">×</button>'+data.message+'
');
                window.setTimeout(function()
                {
                    $(".alert").fadeTo(500, 0).slideUp(500, function()
                    {
                        $(this).remove();
                    });
                }, 5000);
                $('.alert .close').on("click", function(e)
                {
                    $(this).parent().fadeTo(500, 0).slideUp(500);
                });
                //console.log(data);
                //$("#updateprofileimage")[0].reset();
                //window.location.href = "http://localhost/laravel/admin/profile";
            }
            else
            {
                errors = data.errors;

                for(error in errors)
                {
                    $("#error_"+error.title).html(error.message);
                }
            }
        },
        error: function(xhr)
        {
            if(xhr.status == 422)
            {
                errors = xhr.responseJSON;
                for(error in errors)
                {
                    $("#error_"+error).html(errors[error][0]);
                }
            }
        }
    });
});

Error is :"NetworkError: 500 Internal Server Error - http://localhost/laravel/admin/avatar"

please suggest me where i am getting wrong.

Controller is

public function postAvatar(ImageUploadRequest $request)
{
  ---
}


问:
Run a command in a shell and keep running the command when you close the session
I am using Putty to connect to a remote server. What I want to know is if there is any way to write my commands and allow them to keep running after I close the session with Putty. The reason for this is that I do not want to keep the computer ON all the time. Is there any way to do this?.

Update with the solution

For my question as it is presented the best solution is use one of the commands provided such as nohup, because you do not have to install any additional software. But if you are in the same problem use screen, install it and use it. It is amazing.

I have selected the answer of Norman Ramsey as favourite because propose several solutions using commands and screen. But please check the other answers specially the one of PEZ, then you get an insight of what screen is able todo.

答: If you can't use screen (because, for instance, your SSH session is being programmatically driven), you can also use daemonize to run the program as a daemon.

OwnerDisplayName: Eduardo

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eduardo

OwnerDisplayName: Brian Clapper


问:
JQuery - Ajax call completes after next line of code
I have the following ajax function which dynamically adds options to a dropdown list.

```<code>var getData = function() {

    $.getJSON('api/someurl')
            .done(function (data) {

                console.log(data);

                var results = $("#Mydropdown")
                              .empty()
                              .append("<option value=''>Please select</option>");

               // loop data and build list
            })
            .fail(function (jqXHR, textStatus, err) {

            });
};
</code>```

If I already have a value selected which I hold in some input field, then on page load I want to recreate the list and set the selected option to what was previously selected.

The following doesn't work. In the console I can see the ajax data is being returned after this line executes $('#Mydropdown').val($("#SelectedVal").val()); so the value isn't getting selected?

```<code>if ($("#SelectedVal").val()) {
    getData(); // this function logs to console too
    $('#Mydropdown').val($("#SelectedVal").val());
    console.log('done');
}
</code>```

How do I fix?

* Note *
I call the getData function in other functions as well which is why I don't pass the selected value in the above scenario in the function.

答:
You need to set the selected value after updating the dropdown inside the success callback:

```<code>var selectedValue = $("#SelectedVal").val();
if (selectedValue) {
    getData(selectedValue);
}
</code>```

and then:

```<code>var getData = function(selectedValue) {
    $.getJSON('api/someurl').done(function (data) {
        var results = $("#Mydropdown")
            .empty()
            .append("<option value=''>Please select</option>");

        // loop data and build list

        // after you have built the new list set the selected value
        // to what it previously was
        $('#Mydropdown').val(selectedValue);
    })
    .fail(function (jqXHR, textStatus, err) {
    });
};
</code>```

Alternatively if you don't want to set the selected value inside the getData function, you could use a callback:

```<code>var selectedValue = $("#SelectedVal").val();
if (selectedValue) {
    getData(function() {
        $("#SelectedVal").val(selectedValue);
    });
}
</code>```

and your getData function might look like this:

```<code>var getData = function(callback) {
    $.getJSON('api/someurl').done(function (data) {
        var results = $("#Mydropdown")
            .empty()
            .append("<option value=''>Please select</option>");

        // loop data and build list

        // after you have built the new list invoke the callback
        callback();
    })
    .fail(function (jqXHR, textStatus, err) {
    });
};
</code>```

Body:
I have the following ajax function which dynamically adds options to a dropdown list.

var getData = function() {

    $.getJSON('api/someurl')
            .done(function (data) {

                console.log(data);

                var results = $("#Mydropdown")
                              .empty()
                              .append("<option value=''>Please select</option>");

               // loop data and build list
            })
            .fail(function (jqXHR, textStatus, err) {

            });
};

If I already have a value selected which I hold in some input field, then on page load I want to recreate the list and set the selected option to what was previously selected.

The following doesn't work. In the console I can see the ajax data is being returned after this line executes $('#Mydropdown').val($("#SelectedVal").val()); so the value isn't getting selected?

if ($("#SelectedVal").val()) {
    getData(); // this function logs to console too
    $('#Mydropdown').val($("#SelectedVal").val());
    console.log('done');
}

How do I fix?

* Note *
I call the getData function in other functions as well which is why I don't pass the selected value in the above scenario in the function.

Body:
You need to set the selected value after updating the dropdown inside the success callback:

var selectedValue = $("#SelectedVal").val();
if (selectedValue) {
    getData(selectedValue);
}

and then:

var getData = function(selectedValue) {
    $.getJSON('api/someurl').done(function (data) {
        var results = $("#Mydropdown")
            .empty()
            .append("<option value=''>Please select</option>");

        // loop data and build list

        // after you have built the new list set the selected value
        // to what it previously was
        $('#Mydropdown').val(selectedValue);
    })
    .fail(function (jqXHR, textStatus, err) {
    });
};

Alternatively if you don't want to set the selected value inside the getData function, you could use a callback:

var selectedValue = $("#SelectedVal").val();
if (selectedValue) {
    getData(function() {
        $("#SelectedVal").val(selectedValue);
    });
}

and your getData function might look like this:

var getData = function(callback) {
    $.getJSON('api/someurl').done(function (data) {
        var results = $("#Mydropdown")
            .empty()
            .append("<option value=''>Please select</option>");

        // loop data and build list

        // after you have built the new list invoke the callback
        callback();
    })
    .fail(function (jqXHR, textStatus, err) {
    });
};


问:
How to select multiple checkbox in for loop in angular2?
I have tried angular 2 to list categories list with checkbox and user can select any category. I tried with below code. The issue is if I selected any one checkbox all the checkbox are selected and I cannot get the form values on save function. Food.category is dynamic. How can I fix this?</p>

```<code><form #f="ngForm" novalidate>
    <div class="checkbox checkbox-primary" *ngFor="let categoryname of Food.category;">
        <label for="categoryname">
            <input type = "checkbox" name="categoryname[]" [(ngModel)]="Catcheckbox" (click)="onClick(categoryname)" value="{{categoryname}}"/>
            {{categoryname}}
        </label>
    </div>
    <button type="submit" (click)="save(f.value, f.valid)" class="btn btn-default">Submit</button>
</form>

export class ExploreListComponent implements OnInit {
    Catcheckbox:true ;

    onClick(categoryname) {
        alert(categoryname + ' was clicked!');
    }

    save(isValid: boolean, f: User) {
        if (!isValid) return;
        console.log(f);
    }
}
</code>```

答:
I would recommend using ReactiveFormsModule. In this case you are assigning the array to all input name attributes. Try to assign only current index like name="{{i}}" which is set in *ngFor directive</p>

```<code><form #f="ngForm" novalidate>
    <div class="checkbox checkbox-primary" *ngFor="let categoryname of Food.category; let i = index">
        <label for="categoryname">
         <input type = "checkbox" name="{{i}}" [(ngModel)]="Catcheckbox" (click)="onClick(categoryname)" value="{{categoryname}}"/>
        {{categoryname}}
        </label>
    </div>
     <button type="submit" (click)="save(f.value, f.valid)" class="btn btn-default">Submit</button>
</form>
</code>```

Body:
I have tried angular 2 to list categories list with checkbox and user can select any category. I tried with below code. The issue is if I selected any one checkbox all the checkbox are selected and I cannot get the form values on save function. Food.category is dynamic. How can I fix this?

<form #f="ngForm" novalidate>

            <input type = "checkbox" name="categoryname[]" [(ngModel)]="Catcheckbox" (click)="onClick(categoryname)" value="{{categoryname}}"/>
            {{categoryname}}

    <button type="submit" (click)="save(f.value, f.valid)" class="btn btn-default">Submit</button>
</form>

export class ExploreListComponent implements OnInit {
    Catcheckbox:true ;

    onClick(categoryname) {
        alert(categoryname + ' was clicked!');
    }

    save(isValid: boolean, f: User) {
        if (!isValid) return;
        console.log(f);
    }
}

Body:
I would recommend using ReactiveFormsModule. In this case you are assigning the array to all input name attributes. Try to assign only current index like name="{{i}}" which is set in *ngFor directive

<form #f="ngForm" novalidate>
    <div class="checkbox checkbox-primary" *ngFor="let categoryname of Food.category; let i = index">
        <label for="categoryname">
         <input type = "checkbox" name="{{i}}" [(ngModel)]="Catcheckbox" (click)="onClick(categoryname)" value="{{categoryname}}"/>
        {{categoryname}}
        </label>
    </div>
     <button type="submit" (click)="save(f.value, f.valid)" class="btn btn-default">Submit</button>
</form>


问:
How do center an image within another image and have it responsive to mobile landscape?
I have a play image which needs centering over another image. I'm using percentages, to try to have it working on all devices, but the percentages are not acting like they should. I have taken screenshots of the mobile site in portrait and landscape, you can find them here http://imgur.com/a/gN53f

The desktop site has an entirely different row which is hidden on small devices, the code below is visible exclusively on the mobile site.

Here's the css:

```<code>.parent {
  position: relative;
  top: 0;
  left: 0;
}
.image1 {
  position: relative;
  top: 0;
  left: 0;
  z-index: 1;
}
.image2 {
  position: absolute;
  top: 30%;
  left: 43%;
  z-index: 2;
}
</code>```

working, sort of. The HTML:

```<code><div class="parent">
<img class="image1" src="https://placehold.it/1"/ alt="1">
<img class="image2" src="https://placehold.it/2"/ alt="2">
</div>
</code>```

答:
You’ve set .image1 to be relative, but this won’t have an impact on .image2 since it is not a child of .image1. Also it is unclear what sizes the images will have.

If the second image should always scale up and down with the first one, keeping it’s position, it could be done like so:

```<code>.parent {
    margin: 0 auto;
    max-width: 960px; /* i. e. never exceed 960px in width = max-width of .image1 */
    position: relative;
}

.image1 {
    display: block;
    width: 100%;
}

.image2 {
    left: 25%;
    position: absolute;
    top: 25%;
    width: 50%;
}
</code>```

.image2 would have a 25% distance of .image1’s height/width to top, left and right.

Body:
I have a play image which needs centering over another image. I'm using percentages, to try to have it working on all devices, but the percentages are not acting like they should. I have taken screenshots of the mobile site in portrait and landscape, you can find them here http://imgur.com/a/gN53f

The desktop site has an entirely different row which is hidden on small devices, the code below is visible exclusively on the mobile site.

Here's the css:

.parent {
  position: relative;
  top: 0;
  left: 0;
}
.image1 {
  position: relative;
  top: 0;
  left: 0;
  z-index: 1;
}
.image2 {
  position: absolute;
  top: 30%;
  left: 43%;
  z-index: 2;
}

working, sort of. The HTML:

Body:
You’ve set .image1 to be relative, but this won’t have an impact on .image2 since it is not a child of .image1. Also it is unclear what sizes the images will have.

If the second image should always scale up and down with the first one, keeping it’s position, it could be done like so:

.parent {
    margin: 0 auto;
    max-width: 960px; /* i. e. never exceed 960px in width = max-width of .image1 */
    position: relative;
}

.image1 {
    display: block;
    width: 100%;
}

.image2 {
    left: 25%;
    position: absolute;
    top: 25%;
    width: 50%;
}

.image2 would have a 25% distance of .image1’s height/width to top, left and right.


答:
Changed size of image to demonstrate properly

Gave width to parent div to absolute position

.parent {
  position: relative;
  top: 0;
  left: 0;
  width: 300px;
}
.image1 {
  position: relative;
  top: 0;
  left: 0;
  z-index: 1;
}
.image2 {
  position: absolute;
   top: 32%;
   left: 32%;
   z-index: 2;
   border: 1px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
 <head>

 </head>
  <body>
    <div class="parent">
      <img class="image1" src="https://placehold.it/300x300"/ alt="1">
      <img class="image2" src="https://placehold.it/100x100"/ alt="2">
    </div>
  </body>
</html></code>```

Title: How do center an image within another image and have it responsive to mobile landscape?

Body:
Changed size of image to demonstrate properly

Gave width to parent div to absolute position

.parent {
  position: relative;
  top: 0;
  left: 0;
  width: 300px;
}
.image1 {
  position: relative;
  top: 0;
  left: 0;
  z-index: 1;
}
.image2 {
  position: absolute;
   top: 32%;
   left: 32%;
   z-index: 2;
   border: 1px solid;
}

<!DOCTYPE html>
<html>
 <head>

 </head>
  <body>
    <div class="parent">
      <img class="image1" src="https://placehold.it/300x300"/ alt="1">
      <img class="image2" src="https://placehold.it/100x100"/ alt="2">
    </div>
  </body>
</html>


问:
Disable automatic layout change on Android
I've made an app, I've tested it and it was fine on my phone. But... when I gave the .apk to someone else whose phone language is RTL the whole layout broke and it messed up everything.    </p>

<p>My question is - How can I force my app to use only LTR and disable the auto layout change which breaks my whole app design?  </p>

答:
In your manifest file and inside the application tag add these two lines. </p>

```<code><manifest>
    <application
        .
        .
        .
        android:supportsRtl="false"
        tools:replace="android:supportsRtl" //(replace libraries' Rtl support with ours)
        >
    </application>
</manifest>
</code>```

<p>Note: (about second line)
Some libraries have support Rtl in their manifest file so if you want to use those libraries you must replace their manifest line of code with yours. </p>

Body:
I've made an app, I've tested it and it was fine on my phone. But... when I gave the .apk to someone else whose phone language is RTL the whole layout broke and it messed up everything.

My question is - How can I force my app to use only LTR and disable the auto layout change which breaks my whole app design?

Body:
In your manifest file and inside the application tag add these two lines.

<manifest>
    <application
        .
        .
        .
        android:supportsRtl="false"
        tools:replace="android:supportsRtl" //(replace libraries' Rtl support with ours)
        >
    </application>
</manifest>

Note: (about second line)
Some libraries have support Rtl in their manifest file so if you want to use those libraries you must replace their manifest line of code with yours.


问:
Replacing argument 'props' with variable names doesn't work in Reactjs functional syntax with webpack 1
I'm following a tutorial from Lynda for ReactJs which is based on Webpack 1.

If I replace this:

```<code>import 'path/to/style.scss'

export const MyValues = (props) => (
  <div className="values">
    <div className="value-one">
      <span>{props.one}</span>
    </div>
    <div className="value-two">
      <span>{props.two}</span>
    </div>
  </div>
)
</code>```

to this:

```<code>import 'path/to/style.scss'

export const MyValues = (one, two) => (
  <div className="values">
    <div className="value-one">
      <span>{one}</span>
    </div>
    <div className="value-two">
      <span>{two}</span>
    </div>
  </div>
)
</code>```

(changing argument 'props' to arguments 'one' and 'two' and calling the variables directly later)

it compiles but the screen is blank. I don't know what the problem really is. Is it a problem with the syntax, or is it Webpack 1 problem?

答:
you have to do it this way because props is an object</p>

```<code> import 'path/to/style.scss'

export const MyValues = ({one, two}) => (
  <div className="values">
    <div className="value-one">
      <span>{one}</span>
    </div>
    <div className="value-two">
      <span>{two}</span>
    </div>
  </div>
)
</code>```

Body:
I'm following a tutorial from Lynda for ReactJs which is based on Webpack 1.

If I replace this:

import 'path/to/style.scss'

export const MyValues = (props) => (

      {props.one}

      {props.two}

)

to this:

import 'path/to/style.scss'

export const MyValues = (one, two) => (

      {one}

      {two}

)

(changing argument 'props' to arguments 'one' and 'two' and calling the variables directly later)

it compiles but the screen is blank. I don't know what the problem really is. Is it a problem with the syntax, or is it Webpack 1 problem?

Body:
you have to do it this way because props is an object

 import 'path/to/style.scss'

export const MyValues = ({one, two}) => (
  <div className="values">
    <div className="value-one">
      <span>{one}</span>
    </div>
    <div className="value-two">
      <span>{two}</span>
    </div>
  </div>
)


问:
Getting CORS error When Using Spotify Open APIs
I'm getting CORS error while trying to get some data through Spotify's Open APIs such as API/v1/search?type=album&q=... and API/v1/albums/{id} in a Simple Angular 4 Application that searches for albums with a Query then tries to show that specific album Information.

I assume that these two APIs are open and don't need any kind of authorization. So How can I get data from these two when there's no JSONP method available without getting CORS error and without Authorization?

Passing client_id doesn't help I'm afraid.

答: As no one posted a proper answer, I ended up writing and using a simple wrapper over Spotify's API. Everything's working now! No more darn CORS errors or anything! :)</p>


问:
SQL Server PHP Code Igniter show one to many relationship
i want to show data from table_one,where tableone_id is included on table_two..which is one to many relationship..here is the example.

```<code>table_one                table_two
id  | name               id  | name |tableone_id
1   |   A                1   |   C  |     1
2   |   B                2   |   D  |     1
                         3   |   E  |     2
                         4   |   F  |     2
</code>```

The result i was expecting on my PHP is..

```<code>Number  | Name | Linked Item |
  1     |  A   |    C        |
        |      |    D        |
  2     |  B   |    E        |
        |      |    F        |
</code>```

i already tried some code like

```<code>**Controller.php**
$head = $this->db->query("SELECT * from table_one)->result_array();

foreach($head as $key => $value)
{
   $head[$key]['items'] = $this->db->query("SELECT
   a.id,
   b.id,
   b.name as tabletwo_name,
   FROM table_one a
   JOIN table_two b on a.id = b.id
   where b.id =".$value['id'])->result_array();
}
</code>```

the code i make ,fails.how did i do the right code for that case ?

Thank you

答:
try this, hmmm i have not test this but you can </p>

```<code>   $this->db->select('table_one.name AS t1,table_two.name AS t2');
            $this->db->join('table_two', 'table_two.tableone_id=table_one.id');
            $rs = $this->db->get('table_one');

            $count = 1;
            $data  = array();
            foreach ($rs->result() as $key => $value)
            {
                    $data[] = array(
                        'number'      => $count ++,
                        'name'        => $value['t1'],
                        'linked_item' => $value['t2']
                    );
            }

            print_r($data);
</code>```

Body:
i want to show data from table_one,where tableone_id is included on table_two..which is one to many relationship..here is the example.

table_one                table_two
id  | name               id  | name |tableone_id
1   |   A                1   |   C  |     1
2   |   B                2   |   D  |     1
                         3   |   E  |     2
                         4   |   F  |     2

The result i was expecting on my PHP is..

Number  | Name | Linked Item |
  1     |  A   |    C        |
        |      |    D        |
  2     |  B   |    E        |
        |      |    F        |

i already tried some code like

**Controller.php**
$head = $this->db->query("SELECT * from table_one)->result_array();

foreach($head as $key => $value)
{
   $head[$key]['items'] = $this->db->query("SELECT
   a.id,
   b.id,
   b.name as tabletwo_name,
   FROM table_one a
   JOIN table_two b on a.id = b.id
   where b.id =".$value['id'])->result_array();
}

the code i make ,fails.how did i do the right code for that case ?

Thank you

Body:
try this, hmmm i have not test this but you can

   $this->db->select('table_one.name AS t1,table_two.name AS t2');
            $this->db->join('table_two', 'table_two.tableone_id=table_one.id');
            $rs = $this->db->get('table_one');

            $count = 1;
            $data  = array();
            foreach ($rs->result() as $key => $value)
            {
                    $data[] = array(
                        'number'      => $count ++,
                        'name'        => $value['t1'],
                        'linked_item' => $value['t2']
                    );
            }

            print_r($data);


问:
How to use Snap.svg with Angular v4.0
I don't know how to use snap.svg with Angular (created with angular-cli). I've tried to call Snap.svg in the index.html with CDN, import it in the component by adding : import 'snapsvg' but I always get this message :

Uncaught TypeError: Cannot read property 'on' of undefined

Any idea ?

EDIT

Import :

```<code>import 'snapsvg'
</code>```

Template :

```<code><svg id="test" width="100%" height="100%" viewBox="0 0 300 300" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:1.5;">
  <path d="M84.403,145.423c65.672,64.179 136.318,0 136.318,0" />
</svg>
</code>```

In Component :

```<code>  ngOnInit() {
    let s = Snap('#test')
    this.path = s.path(this.start)
    this.path.animate({
      d: this.end
    }, 1000, mina.bounce)
  }
</code>```

答:
Currently there seems to be a bug with using SnapSVG with WebPack (which angular-cli uses). So far the only way I've got this to work is by including the snapsvg.js file as a script in angular-cli.json . Add this to the scripts array as below: </p>

```<code>"scripts": [ "node_modules/snapsvg/dist/snap.svg.js"],
</code>```

Title: How to use Snap.svg with Angular v4.0

Body:
I don't know how to use snap.svg with Angular (created with angular-cli). I've tried to call Snap.svg in the index.html with CDN, import it in the component by adding : import 'snapsvg' but I always get this message :

Uncaught TypeError: Cannot read property 'on' of undefined

Any idea ?

EDIT

Import :

import 'snapsvg'

Template :

<svg id="test" width="100%" height="100%" viewBox="0 0 300 300" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:1.5;">
  <path d="M84.403,145.423c65.672,64.179 136.318,0 136.318,0" />
</svg>

In Component :

  ngOnInit() {
    let s = Snap('#test')
    this.path = s.path(this.start)
    this.path.animate({
      d: this.end
    }, 1000, mina.bounce)
  }

Body:
Currently there seems to be a bug with using SnapSVG with WebPack (which angular-cli uses). So far the only way I've got this to work is by including the snapsvg.js file as a script in angular-cli.json . Add this to the scripts array as below:

"scripts": [ "node_modules/snapsvg/dist/snap.svg.js"],


答:
you should select value in the callback of getdata success here: see attached code here:

```<code>       $.getJSON('api/someurl')
        .done(function (data) {

            var results = $("#Mydropdown")
                          .empty()
                          .append("<option value=''>Please select</option>");

           // loop data and build list
           //After List Build is Completed Select Drop Down Here

            $('#Mydropdown').val($("#SelectedVal").val());

            console.log('done');

        })
        .fail(function (jqXHR, textStatus, err) {

        });
</code>```

Title: JQuery - Ajax call completes after next line of code

Body:
you should select value in the callback of getdata success here: see attached code here:

       $.getJSON('api/someurl')
        .done(function (data) {

            var results = $("#Mydropdown")
                          .empty()
                          .append("<option value=''>Please select</option>");

           // loop data and build list
           //After List Build is Completed Select Drop Down Here

            $('#Mydropdown').val($("#SelectedVal").val());

            console.log('done');

        })
        .fail(function (jqXHR, textStatus, err) {

        });


问:
Capitalizing words in a string using C#
I need to take a string, and capitalize words in it. Certain words ("in", "at", etc.), are not capitalized and are changed to lower case if encountered. The first word should always be capitalized. Last names like "McFly" are not in the current scope, so the same rule will apply to them - only first letter capitalized.

For example: "of mice and men By CNN" should be changed to "Of Mice and Men by CNN". (Therefore ToTitleString won't work here.)

What would be the best way to do that?

I thought of splitting the string by spaces, and go over each word, changing it if necessary, and concatenating it to the previous word, and so on.
It seems pretty naive and I was wondering if there's a better way to do it. I am using .NET 3.5.

答:
Depending on how often you plan on doing the capitalization I'd go with the naive approach.  You could possibly do it with a regular expression, but the fact that you don't want certain words capitalized makes that a little trickier.

You can do it with two passes using regular expressions:

```<code>var result = Regex.Replace("of mice and men isn't By CNN", @"\b(\w)", m => m.Value.ToUpper());
result = Regex.Replace(result, @"(\s(of|in|by|and)|\'[st])\b", m => m.Value.ToLower(), RegexOptions.IgnoreCase);
</code>```

This outputs Of Mice and Men Isn't by CNN.

The first expression capitalizes every letter on a word boundary and the second one downcases any words matching the list that are surrounded by white space.

The downsides to this approach is that you're using regexs (now you have two problems) and you'll need to keep that list of excluded words up to date.  My regex-fu isn't good enough to be able to do it in one expression, but it might be possible.

Title: Capitalizing words in a string using C#

Body:
Depending on how often you plan on doing the capitalization I'd go with the naive approach.  You could possibly do it with a regular expression, but the fact that you don't want certain words capitalized makes that a little trickier.

You can do it with two passes using regular expressions:

var result = Regex.Replace("of mice and men isn't By CNN", @"\b(\w)", m => m.Value.ToUpper());
result = Regex.Replace(result, @"(\s(of|in|by|and)|\'[st])\b", m => m.Value.ToLower(), RegexOptions.IgnoreCase);

This outputs Of Mice and Men Isn't by CNN.

The first expression capitalizes every letter on a word boundary and the second one downcases any words matching the list that are surrounded by white space.

The downsides to this approach is that you're using regexs (now you have two problems) and you'll need to keep that list of excluded words up to date.  My regex-fu isn't good enough to be able to do it in one expression, but it might be possible.


问:
The bundle at 'my_app.app/ResearchKit/ResearchKit/Info.plist' does not contain a bundle executable
Update
XCode Version: 8.2
iOS Target: 9

Hopefully some can point out to me that this is not a bug. Very simply I pulled the latest stable version of researckKit, and I dropped the .xcodeproj file into my new iOS project, added the embedded binary. I created a couple steps that look fine in the simulator. My app builds fine and even the archive validates OK. Upload to app store is fine, but then I am receiving emails from the app store with 6 entries all look about the same, for 6 different Info.plist files inside the ReserachKit framework:

Unexpected CFBundleExecutable Key - The bundle at
  'my_app.app/ResearchKit/ResearchKit/Info.plist' does not contain a
  bundle executable. If this bundle intentionally does not contain an
  executable, consider removing the CFBundleExecutable key from its
  Info.plist and using a CFBundlePackageType of BNDL. If this bundle is
  part of a third-party framework, consider contacting the developer of
  the framework for an update to address this issue.

I have found quite a few answers on Stack Overflow, many people agreeing to do what was suggested in the error message: simply remove the CFBundleExecutable Key from the .plist files. I tried that, but then my archive will not even validate with the following error:

iTunes Store operation failed. Invalid Bundle Structure - The binary
  file 'my_app.app/Frameworks/ResearchKit.framework/ResearchKit' is not
  permitted. Your app can’t contain standalone executables or libraries,
  other than the CFBundleExecutable of supported bundles. Refer to the
  Bundle Programming Guide at
  https://developer.apple.com/go/?id=bundle-structure for information on
  the iOS app bundle structure.

** UPDATE **

Granted I pulled a fresh version of the ResearchKit framework from github for this project.  So instead I just tried a copy of a version of ResearchKit from another Xcode Project that I have successfully deployed on the app store recently, i figure if it worked for that app it should go through for this app.  But Alas, I am getting the same email error from the App Store about the Unexpected CFBundleExecutable Key.

Again this is an apple-supported free framework.  There are simple instructions for how to use it on the github page, which I followed.  I have used it before and submitted an app with this framework recently, which had no problems and is currently active in Test Flight Beta Testing.  I also filed an issue on the GitHub project page.

答:
I met this problem like yours,and I fixed it by:

Remove Executable file in ResearchKit

Find info.plist in ResearchKit,do:

delete info.plist in ResearchKit.
Or you can add Bundle version,Bundle identifier,Bundle versions in this info.plist,they should be same as your parameters in your own info.plist

check Target - Info - URL Types,check if there is illegal identifier


问:
Can´t validate app project after archiveing it.
Hi i´m having a problem trying to upload my app to the appstore and it feels like i´v looked everywhere. Asking this question was not my fist choice but I can´t se any other solution. My problem is that the validate button is grayed out aswell as the upload to appstore button. I have done every step with appids and certificates very carefully and precise. what can I do?enter image description here</p>

答:
I may hace found an answer and it reads: If you select an archive in the Archives window and the Validate, Export, or “Upload to App Store” buttons are disabled, verify that the archive contains a single top-level app.

But what I don´t understand is what single top-level app is. Can someone explain?

https://developer.apple.com/library/content/documentation/IDEs/Conceptual/AppDistributionGuide/Troubleshooting/Troubleshooting.html


问:
TFS 2015 visual studio build task does not support VS 2017
We have a build definition in TFS 2015 that have worked fine with Visual Studio 2015 projects and solutions. We have now decided to upgrade to Visual Studio 2017 and thus we would like to target Visual Studio 2017 in the Visual Studio build task. We have installed Visual Studio 2017 on the build agent. Unfortunately the only options available int the Visual Studio build task are 2012, 2013, 2015 and Latest. We have tried latest but it does not find Visual Studio 2017 on the build agent. It won't work with the msbuild task either.</p>

答:
we are facing a similar issue and it is not possible for us to update ourselves as it is maintained on a company level where we cannot take that much influence.
However our team wanted to switch to VS2017 and make use of the C# 7 features. That's why we tried it as well with replacing the build steps from Visual Studio Build to MSBuild. Sadly this did not work as expected (we got some errors during the build).

As our main objective is to use the C# 7 features we looked for a way how to still achieve that at the time with Visual Studio 2015 remaining on the Build Server. We ended up using the nuget package Microsoft.Net.Compilers that, when used in a project, will use that compiler instead of the installed one.
More on this can be found in this Thread.


问:
Set option selected with rails symbol
I've this select in my form:

```<code><%= select_tag :x, options_from_collection_for_select(@dmj, :id, :name, :selected), {class: "form-control"} %>
</code>```

but when I load the page, the option whose value is set in db is not selected.

The symbol :selected comes from a SQL query in the controller and if I try to replace the :name with :selected in the options_from_collection_for_select, I can see that its value is correct.

Also, if I manually set the integer in the options_from_collection_for_select the corresponding option is selected.

Why do I not succeed in selecting the option with the symbol?

EDIT:

My query is making a join to retrieve the selected from a Join table. Here's the query:
@dmj = DiscoveryModeInjury.find_by_sql("SELECT D.name, D.id,   L.discovery_mode_injury_id AS selected

FROM

discovery_mode_injuries D

 LEFT OUTER JOIN

link_dismodeinj_hospitalizations L

ON

D.id = L.discovery_mode_injury_id

 WHERE

flag = 'disc'

 ORDER BY

D.name")

If I have understood correctly Akash Srivastava's suggestion, the query should return the DiscoveryModeInjury id field? How..? thanks.

答: Make sure your query for :selected returns an :id field. Basically, the selected option in options_from_collection_for_select() should be of the same field as the value field of the same, which is :id in your case. Many of us make this mistake of keeping the result of selected as an object of the collection.

Title: Set option selected with rails symbol

Body:
I've this select in my form:

<%= select_tag :x, options_from_collection_for_select(@dmj, :id, :name, :selected), {class: "form-control"} %>

but when I load the page, the option whose value is set in db is not selected.

The symbol :selected comes from a SQL query in the controller and if I try to replace the :name with :selected in the options_from_collection_for_select, I can see that its value is correct.

Also, if I manually set the integer in the options_from_collection_for_select the corresponding option is selected.

Why do I not succeed in selecting the option with the symbol?

EDIT:

My query is making a join to retrieve the selected from a Join table. Here's the query:
@dmj = DiscoveryModeInjury.find_by_sql("SELECT D.name, D.id,   L.discovery_mode_injury_id AS selected

FROM

discovery_mode_injuries D

 LEFT OUTER JOIN

link_dismodeinj_hospitalizations L

ON

D.id = L.discovery_mode_injury_id

 WHERE

flag = 'disc'

 ORDER BY

D.name")

If I have understood correctly Akash Srivastava's suggestion, the query should return the DiscoveryModeInjury id field? How..? thanks.


问:
Load environment variables from file in Groovy
I have an external file with variables that I would like to access in my groovy script.

myfile.conf:

```<code>variable1=Value1
export variable2=Value2
</code>```

I want to do something like the following in my groovy script:

```<code>System.getenv("variable1")
System.getenv("variable2")
</code>```

I have tried running "source myfile.conf".execute().waitFor() but I am unable to access these variables.

答:
As others have said, strictly speaking you cannot alter environment variables of the running processs.

However, assuming you want to "do something like getenv" in order to get the values of certain variables following execution of your script, you can do something like this:

```<code>def map = [:]
def envAsText = ['sh', '-c', 'source myfile.conf 2>&1 >/dev/null && env'].execute().text
envAsText.eachLine { (key,value) = it.split('=', 2); map[key] = value }
</code>```

This creates an empty map, then executes child process to "source" your file, filter out all output while sourcing, then print environment with "env" command. (also assuming unix-like system, which is implied from your "myfile.conf"). Finally, output is collected and stored to "map".

After this, "map" contains all environment of your child process (now finished), including "variable2":

```<code>map['variable2'] // this contains "Value2"
</code>```

Body:
I have an external file with variables that I would like to access in my groovy script.

myfile.conf:

variable1=Value1
export variable2=Value2

I want to do something like the following in my groovy script:

System.getenv("variable1")
System.getenv("variable2")

I have tried running "source myfile.conf".execute().waitFor() but I am unable to access these variables.

Body:
As others have said, strictly speaking you cannot alter environment variables of the running processs.

However, assuming you want to "do something like getenv" in order to get the values of certain variables following execution of your script, you can do something like this:

def map = [:]
def envAsText = ['sh', '-c', 'source myfile.conf 2>&1 >/dev/null && env'].execute().text
envAsText.eachLine { (key,value) = it.split('=', 2); map[key] = value }

This creates an empty map, then executes child process to "source" your file, filter out all output while sourcing, then print environment with "env" command. (also assuming unix-like system, which is implied from your "myfile.conf"). Finally, output is collected and stored to "map".

After this, "map" contains all environment of your child process (now finished), including "variable2":

map['variable2'] // this contains "Value2"


答:
Maybe use doneCallback function for example;

Use callback

```<code>var getData = function(doneCallback) {

    $.getJSON('api/someurl')
            .done(function (data) {

                console.log(data);

                var results = $("#Mydropdown")
                              .empty()
                              .append("<option value=''>Please select</option>");

               // loop data and build list
               if(doneCallback)
                doneCallback();
            })
            .fail(function (jqXHR, textStatus, err) {

            });
};
</code>```

Define callback

```<code>if ($("#SelectedVal").val()) {
    getData(function(){
        $('#Mydropdown').val($("#SelectedVal").val());
    });
    console.log('done');
}
</code>```

Body:
I have the following ajax function which dynamically adds options to a dropdown list.

var getData = function() {

    $.getJSON('api/someurl')
            .done(function (data) {

                console.log(data);

                var results = $("#Mydropdown")
                              .empty()
                              .append("<option value=''>Please select</option>");

               // loop data and build list
            })
            .fail(function (jqXHR, textStatus, err) {

            });
};

If I already have a value selected which I hold in some input field, then on page load I want to recreate the list and set the selected option to what was previously selected.

The following doesn't work. In the console I can see the ajax data is being returned after this line executes $('#Mydropdown').val($("#SelectedVal").val()); so the value isn't getting selected?

if ($("#SelectedVal").val()) {
    getData(); // this function logs to console too
    $('#Mydropdown').val($("#SelectedVal").val());
    console.log('done');
}

How do I fix?

* Note *
I call the getData function in other functions as well which is why I don't pass the selected value in the above scenario in the function.

Body:
Maybe use doneCallback function for example;

Use callback

var getData = function(doneCallback) {

    $.getJSON('api/someurl')
            .done(function (data) {

                console.log(data);

                var results = $("#Mydropdown")
                              .empty()
                              .append("<option value=''>Please select</option>");

               // loop data and build list
               if(doneCallback)
                doneCallback();
            })
            .fail(function (jqXHR, textStatus, err) {

            });
};

Define callback

if ($("#SelectedVal").val()) {
    getData(function(){
        $('#Mydropdown').val($("#SelectedVal").val());
    });
    console.log('done');
}


问:
Enter on mac safari takes two chars but shows only one char is used
I am using this jquery

http://www.javascriptkit.com/script/script2/enforceform.shtml

It shows me wrong char count on mac safari when i hit enter key.Its like enter takes two chars but shows only one in displaying the text

Thanks

答:
This discrepancy is because of different line endings name \r or \n or \r\n. From my past experience I believe the following is the behaviour you should expect from browsers.

```<code>Chrome (Windows and OS X) counts enter as 2 distinct characters
Firefox (Windows and OS X) counts enter as 1 single character
IE (Windows) counts enter as 1 single character
Safari (OS X) counts enter as 2 distinct characters
</code>```

To fix this, you can either replace \r\n with \n whenever it changes.

```<code>$("#comment").val($("#comment").val().replace(/\n\r/g, '\n'))
</code>```

Or use some other jquery scripts that already does it for you.

e.g.: http://pioul.fr/jquery-maxlength

Body:
This discrepancy is because of different line endings name \r or \n or \r\n. From my past experience I believe the following is the behaviour you should expect from browsers.

Chrome (Windows and OS X) counts enter as 2 distinct characters
Firefox (Windows and OS X) counts enter as 1 single character
IE (Windows) counts enter as 1 single character
Safari (OS X) counts enter as 2 distinct characters

To fix this, you can either replace \r\n with \n whenever it changes.

$("#comment").val($("#comment").val().replace(/\n\r/g, '\n'))

Or use some other jquery scripts that already does it for you.

e.g.: http://pioul.fr/jquery-maxlength


问:
String.format() Bug?
The following gives different results in J2SE and Android for the de_DE locale:

```<code>Locale locale = new Locale("de","DE");
log(String.format(locale,"%.1f", 0.45));
</code>```

In JRE 1.6.0_22, I get "0,5" as expected.

With the Android Platform 2.2 I get "0,4"

Thanks, Roland

答:
I wouldn't call it a bug, unless you point me to a specification that says, which rounding mode the String.format method should be using. It seems that the 1.6 JRE uses UP or HALF_UP as a RoundingMode. In Android however, HALF_EVEN mode is used, which also seems the default mode for DecimalFormat. This is the code I've used with JRE to test the above:

```<code>import java.util.Locale;
import java.text.DecimalFormat;
import java.math.RoundingMode;

public class Test {

    public static void main(String [] args) {
        Locale locale = new Locale("de","DE");
        String str = String.format(locale,"%.1f", 0.45);
        System.out.println(str);
        System.out.println(String.format("%.1f", 0.45));

        DecimalFormat df = new DecimalFormat("#.#");
        System.out.println(df.format(0.45));
        System.out.println(df.getRoundingMode());
        df.setRoundingMode(RoundingMode.HALF_UP);
        System.out.println(df.format(0.45));
    }
}
</code>```

It seems that the locale has nothing to do with the rounding mode. Unfortunately, in Android DecimalFormat doesn't seem to support Rounding Modes, so you can't run the same code as is.

I would also be interested in running the same code in JRE 1.5 (which doesn't support the setting of Rounding Mode), but I don't have a suitable environment in my machine.

Title: String.format() Bug?

Body:
The following gives different results in J2SE and Android for the de_DE locale:

Locale locale = new Locale("de","DE");
log(String.format(locale,"%.1f", 0.45));

In JRE 1.6.0_22, I get "0,5" as expected.

With the Android Platform 2.2 I get "0,4"

Thanks, Roland

Body:
I wouldn't call it a bug, unless you point me to a specification that says, which rounding mode the String.format method should be using. It seems that the 1.6 JRE uses UP or HALF_UP as a RoundingMode. In Android however, HALF_EVEN mode is used, which also seems the default mode for DecimalFormat. This is the code I've used with JRE to test the above:

import java.util.Locale;
import java.text.DecimalFormat;
import java.math.RoundingMode;

public class Test {

    public static void main(String [] args) {
        Locale locale = new Locale("de","DE");
        String str = String.format(locale,"%.1f", 0.45);
        System.out.println(str);
        System.out.println(String.format("%.1f", 0.45));

        DecimalFormat df = new DecimalFormat("#.#");
        System.out.println(df.format(0.45));
        System.out.println(df.getRoundingMode());
        df.setRoundingMode(RoundingMode.HALF_UP);
        System.out.println(df.format(0.45));
    }
}

It seems that the locale has nothing to do with the rounding mode. Unfortunately, in Android DecimalFormat doesn't seem to support Rounding Modes, so you can't run the same code as is.

I would also be interested in running the same code in JRE 1.5 (which doesn't support the setting of Rounding Mode), but I don't have a suitable environment in my machine.


问:
How can I get the data fields from subclass not superclass?
I have a super class named TestSuper

```<code>public class TestSuper {
  int a = 0;
}
</code>```

and I have 2 sub classes named TestSub and TestSub2 that extend TestSuper

```<code>public class TestSub extends TestSuper{
   int a=1;
}

public class TestSub2 extends TestSuper{
   int a=2;
}
</code>```

in my main class i created a method that takes in a type TestSuper and returns the a value of it and in the main i display it on the console

```<code>public class Main {
public static void main(String[] args){

    System.out.println(test(new TestSub())+" "+test(new TestSub2()));
}
public static int test(TestSuper b){
    return b.a;
}
}
</code>```

but the output is "0 0" instead of "1 2", what do I do?

答:
You need to cast the reference so say which one you want.

```<code>public static int test(TestSuper b){
    return b instanceof TestSub ? ((TestSub) b).a :
           b instanceof TestSub2 ? ((TestSub2) b).a :
           b.a;
}
</code>```

If this seems needlessly complicated, it is. You should use polymorphism instead.

```<code>public class TestSuper {
    int a = 0;
    public int getA() { return a; }
}

public class TestSub extends TestSuper {
    int a = 1;
    public int getA() { return a; }
}

public class TestSub2 extends TestSuper {
    int a = 2;
    public int getA() { return a; }
}

public static int test(TestSuper b) {
    return b.getA();
}
</code>```

Body:
I have a super class named TestSuper

public class TestSuper {
  int a = 0;
}

and I have 2 sub classes named TestSub and TestSub2 that extend TestSuper

public class TestSub extends TestSuper{
   int a=1;
}

public class TestSub2 extends TestSuper{
   int a=2;
}

in my main class i created a method that takes in a type TestSuper and returns the a value of it and in the main i display it on the console

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

    System.out.println(test(new TestSub())+" "+test(new TestSub2()));
}
public static int test(TestSuper b){
    return b.a;
}
}

but the output is "0 0" instead of "1 2", what do I do?

Body:
You need to cast the reference so say which one you want.

public static int test(TestSuper b){
    return b instanceof TestSub ? ((TestSub) b).a :
           b instanceof TestSub2 ? ((TestSub2) b).a :
           b.a;
}

If this seems needlessly complicated, it is. You should use polymorphism instead.

public class TestSuper {
    int a = 0;
    public int getA() { return a; }
}

public class TestSub extends TestSuper {
    int a = 1;
    public int getA() { return a; }
}

public class TestSub2 extends TestSuper {
    int a = 2;
    public int getA() { return a; }
}

public static int test(TestSuper b) {
    return b.getA();
}


问:
how to change/remove new relic license key once it has been added
I have already added a license key to one of my servers but now I realize that I should add different key instead. so I just want to remove it and add another one

Thanks,

答:
What server are you running, or what kind of installation procedure have you followed?

In case you have installed it on Tomcat it suffices to change your license key in the newrelic.yml config file


问:
ANTLR String Tokens giving Implicit Definition Warning
So I'm getting the "Implicit definition of token 'x' in parser rule." warning in parser rules with this format: rule: 'x' Subrule; even though all 'x' values I'm using have been included in a lexer rule. For example, '+', '-', '*', etc. are defined as Operator tokens. Defining them in a lexer rule with no alternatives (ex: Add: '+';) seems to fix the problem. Could someone explain what's going on and if there's a simpler solution?

答: Obviously you still have literals in your parser rules. It is good practice to only define lexer tokens in lexer rules. Follow that rule and these warnings will be gone.</p>


问:
use linqtoexcel in windows services
I am using LinqtoExcel in my windows Service as shown below, but my issue that throw windows services it is not working and stuck in this method while using it in a consul it is working fine. Please any help??</p>

```<code>public string[] OpenExcelFileLinq(string exldir, int phone)
        {
            string sheetName = "Autoline";
            var excelFile = new ExcelQueryFactory(exldir);
            var artistAlbums = from p in excelFile.Worksheet(sheetName)
                where p["Phone"] == phone.ToString()
                select p;

            foreach (var a in artistAlbums)
            {
                string cm = a[1];
                string cn = a[2];

                if (a.Any())
                {
                    string[] cust = {cm, cn};
                    return cust;
                }
            }
            string[] notvalid = {"Not Valid", "Not Valid"};
            return notvalid;
</code>```

答:
Actually after a lot of changes and debugging in my code I found that the linqtoexcel can read an excel file with extension .xlsx through console application but it cannot do that through windows service, so I had to extract the excel from other program in .xls extension and managed to solve the issue.

thanks.

Title: use linqtoexcel in windows services

Body:
I am using LinqtoExcel in my windows Service as shown below, but my issue that throw windows services it is not working and stuck in this method while using it in a consul it is working fine. Please any help??

public string[] OpenExcelFileLinq(string exldir, int phone)
        {
            string sheetName = "Autoline";
            var excelFile = new ExcelQueryFactory(exldir);
            var artistAlbums = from p in excelFile.Worksheet(sheetName)
                where p["Phone"] == phone.ToString()
                select p;

            foreach (var a in artistAlbums)
            {
                string cm = a[1];
                string cn = a[2];

                if (a.Any())
                {
                    string[] cust = {cm, cn};
                    return cust;
                }
            }
            string[] notvalid = {"Not Valid", "Not Valid"};
            return notvalid;


答: You should create your own function like you're describing.</p>

Title: Capitalizing words in a string using C#

Body:
I need to take a string, and capitalize words in it. Certain words ("in", "at", etc.), are not capitalized and are changed to lower case if encountered. The first word should always be capitalized. Last names like "McFly" are not in the current scope, so the same rule will apply to them - only first letter capitalized.

For example: "of mice and men By CNN" should be changed to "Of Mice and Men by CNN". (Therefore ToTitleString won't work here.)

What would be the best way to do that?

I thought of splitting the string by spaces, and go over each word, changing it if necessary, and concatenating it to the previous word, and so on.
It seems pretty naive and I was wondering if there's a better way to do it. I am using .NET 3.5.


问:
Responsive HTML5 Video - Sizing in iOS
we are having trouble displaying Responsive HTML5 video and getting the scale right;

On desktop browsers, the scale is fine - with the video and its poster image scaling perfectly. However on iPhone Safari, the video does not full the width, leaving a black 'border/padding' around.

The CSS;

```<code>.hero-video {
    /* The Container */
height: 338px;
width: 66.6%;
}
.hero-video video {
height: auto;
width: 100%;
}
</code>```

The HTML

```<code><div class="hero-video">
    <video id="intro-video" controls preload="auto" poster="img/trigger-intro.png" width="auto" height="auto">
    <source src="media/intro.mp4" type='video/mp4' />
    <source src="media/intro.webm" type='video/webm' />
        Your browser does not support this video.
    </video>
</div>
</code>```

答:
THIS WORKS FOR ME.

I am pretty sure you can further change and clean the HTML Markup and CSS Rules but so far this works on iPhone, Android and Kindle Fire Devices.

For the Video HTML Markup I am using this.

```<code><video autoplay="autoplay" id="background" loop="loop" muted="" poster="solar.jpg" data-autoplay="" playsinline="" height="750" width="1600">
<source src="solar5.mp4" type="video/mp4">
</video>
</code>```

For the CSS I am using this.

```<code>#background {
position: relative;
min-width: 100%;
min-height: 100%;
width: 100%;
height: 100%;
z-index: -100;
-webkit-transform: translateX(0%) translateY(-20%);
transform: translateX(0%) translateY(-20%);
background: url("solar.jpg") no-repeat;
background-size: cover;
opacity: 1;
}
.video {
position:relative;
padding-bottom:44.25%;
padding-top:30px;
height:0;
overflow:hidden;
}
</code>```

Title: Responsive HTML5 Video - Sizing in iOS

Body:
we are having trouble displaying Responsive HTML5 video and getting the scale right;

On desktop browsers, the scale is fine - with the video and its poster image scaling perfectly. However on iPhone Safari, the video does not full the width, leaving a black 'border/padding' around.

The CSS;

.hero-video {
    /* The Container */
height: 338px;
width: 66.6%;
}
.hero-video video {
height: auto;
width: 100%;
}

The HTML

    <video id="intro-video" controls preload="auto" poster="img/trigger-intro.png" width="auto" height="auto">
    <source src="media/intro.mp4" type='video/mp4' />
    <source src="media/intro.webm" type='video/webm' />
        Your browser does not support this video.
    </video>

Body:
THIS WORKS FOR ME.

I am pretty sure you can further change and clean the HTML Markup and CSS Rules but so far this works on iPhone, Android and Kindle Fire Devices.

For the Video HTML Markup I am using this.

<video autoplay="autoplay" id="background" loop="loop" muted="" poster="solar.jpg" data-autoplay="" playsinline="" height="750" width="1600">
<source src="solar5.mp4" type="video/mp4">
</video>

For the CSS I am using this.

#background {
position: relative;
min-width: 100%;
min-height: 100%;
width: 100%;
height: 100%;
z-index: -100;
-webkit-transform: translateX(0%) translateY(-20%);
transform: translateX(0%) translateY(-20%);
background: url("solar.jpg") no-repeat;
background-size: cover;
opacity: 1;
}
.video {
position:relative;
padding-bottom:44.25%;
padding-top:30px;
height:0;
overflow:hidden;
}


问:
Replacing argument 'props' with variable names doesn't work in Reactjs functional syntax with webpack 1
I'm following a tutorial from Lynda for ReactJs which is based on Webpack 1.

If I replace this:

```<code>import 'path/to/style.scss'

export const MyValues = (props) => (
  <div className="values">
    <div className="value-one">
      <span>{props.one}</span>
    </div>
    <div className="value-two">
      <span>{props.two}</span>
    </div>
  </div>
)
</code>```

to this:

```<code>import 'path/to/style.scss'

export const MyValues = (one, two) => (
  <div className="values">
    <div className="value-one">
      <span>{one}</span>
    </div>
    <div className="value-two">
      <span>{two}</span>
    </div>
  </div>
)
</code>```

(changing argument 'props' to arguments 'one' and 'two' and calling the variables directly later)

it compiles but the screen is blank. I don't know what the problem really is. Is it a problem with the syntax, or is it Webpack 1 problem?

答:
You need to destructre you props to extract one and two arguments from them

Enclose them within {} like

```<code>import 'path/to/style.scss'

export const MyValues = ({one, two}) => (
  <div className="values">
    <div className="value-one">
      <span>{one}</span>
    </div>
    <div className="value-two">
      <span>{two}</span>
    </div>
  </div>
)
</code>```

So what actually happens with  the above method if that if you are passing props like

```<code><MyValues one="1" two="2" three="3" four="4"/>
</code>```

And if you only want to use props one, two then {one, two} will make them available from props and you can use it like {one} and {two}

Body:
I'm following a tutorial from Lynda for ReactJs which is based on Webpack 1.

If I replace this:

import 'path/to/style.scss'

export const MyValues = (props) => (

      {props.one}

      {props.two}

)

to this:

import 'path/to/style.scss'

export const MyValues = (one, two) => (

      {one}

      {two}

)

(changing argument 'props' to arguments 'one' and 'two' and calling the variables directly later)

it compiles but the screen is blank. I don't know what the problem really is. Is it a problem with the syntax, or is it Webpack 1 problem?

Body:
You need to destructre you props to extract one and two arguments from them

Enclose them within {} like

import 'path/to/style.scss'

export const MyValues = ({one, two}) => (
  <div className="values">
    <div className="value-one">
      <span>{one}</span>
    </div>
    <div className="value-two">
      <span>{two}</span>
    </div>
  </div>
)

So what actually happens with  the above method if that if you are passing props like

<MyValues one="1" two="2" three="3" four="4"/>

And if you only want to use props one, two then {one, two} will make them available from props and you can use it like {one} and {two}


问:
From (not a square) adjacency matrix to visual graph in R
We have an non square adjacency matrix p (197x190)matrix without weights (only 1 if the 2 telephone numbers have called with each other and 0 otherwise). We tried to visualize this with a graph using this simple code and the igraph package:

p<-as.matrix(dcast(SNA_data, A_NUMBER~B_NUMBER, value.var="W", fill=0))[,]
  graph<-graph.adjacency(p, mode="undirected", weighted=NULL)
  plot(graph)

The result is a very small graph in plot that is totally unreadable graph anybody knows how to solve this?

Thanks in advance.

答:
Try to use x11() to plot your graph in an external window :

```<code>library(igraph)
adjm1<-matrix(sample(0:1,1000,replace=TRUE,prob=c(0.9,01)),nc=10)
g1<-graph.adjacency(adjm1)
x11()
plot(g1)
</code>```

Reference for the simulation : using graph.adjacency() in R

Body:
Try to use x11() to plot your graph in an external window :

library(igraph)
adjm1<-matrix(sample(0:1,1000,replace=TRUE,prob=c(0.9,01)),nc=10)
g1<-graph.adjacency(adjm1)
x11()
plot(g1)

Reference for the simulation : using graph.adjacency() in R


问:
webpack html-loader：  tag not triggering url-loader
When using html-loader, the  tag in the index.html did not trigger url-loader. Here's my webpack configs & html:

webpack config

```<code>// webpack config
module.exports = {
  entry: {
    "index": path.join(__dirname, "./src/js/app.js"),
    "guide_index": path.join(__dirname, './src/js/guide_app.js')
  },
  output: {
    path: path.join(__dirname, '/dist'),
    publicPath: '/',
    filename: '[name].[hash].js'
  },
  // loaders
  module: {
    rules: [
      {
        test: /\.(gif|jpe?g|png|svg|mp3|ttf)$/i,
        loader: "url-loader",
        include: [
          "/Users/chrishu/Projects/Wind/guideios/Travel/Travel/Resource/assets/image",
          path.resolve(__dirname, "/src/image"),
          path.resolve(__dirname, "/../Travel/Resource/assets/image"),
          path.resolve(__dirname, "/../Travel/Resource/assets")
        ],
        query: {
          limit: 5000,
          name: '[name].[hash:16].[ext]'
          //name: "./assets/[name].[hash:16].[ext]"
        }
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"]
      },
      {
        test: /\.(js|jsx)$/,
        loader: "babel-loader",
        // exclude: /node_modules/,
        query: { cacheDirectory: true }
      },
      {
        test: /\.html$/,
        use: [ {
          loader: 'html-loader',
          options: {
            minimize: false,
            removeComments: false,
            removeCommentsFromCDATA: false,
            removeCDATASectionsFromCDATA: false,
            collapseWhitespace: false,
            conservativeCollapse: false,
            // removeAttributeQuotes: false,
            // useShortDoctype: false,
            // keepClosingSlash: false,
            minifyJS: false,
            minifyCSS: false,
            // removeScriptTypeAttributes: false,
            // removeStyleTypeAttributes: false
          }
        }]
      }
    ]
  },
  // Plugins
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'guide_index.html',
      template: path.join(__dirname, './src/html/guide_index.html'),
      inject: true,
      chunks: ["guide_index"],
      minify: false,
      chunksSortMode: 'dependency'
    }),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: path.join(__dirname, './src/html/index.html'),
      inject: true,
      chunks: ["index"],
      minify: false,
      chunksSortMode: 'dependency'
    }),
    new webpack.LoaderOptionsPlugin({
      debug: true
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': "'development'"
    })
  ],
  resolve: {
    extensions: [ '.web.js', '.js', '.jsx' ]
  }
}
</code>```

index.html:

```<code><div class="button" ng-click="$backHistory()" ng-if="navbarType == 'backHistory'">
  <img src="back.png">
</div>
</code>```

error logs:

```<code>Module not found: Error: Can't resolve './back.png' in '/Users/chrishu/Projects/Wind/guideios/Travel/Travel/Resource/assets/html':
Error: Can't resolve './back.png' in '/Users/chrishu/Projects/Wind/guideios/Travel/Travel/Resource/assets/html'

  - compiler.js:76
    [Travel]/[.2.28.0@html-webpack-plugin]/lib/compiler.js:76:16

  - Compiler.js:291 Compiler.<anonymous>
    [Travel]/[.2.3.2@webpack]/lib/Compiler.js:291:10

  - Compiler.js:494
    [Travel]/[.2.3.2@webpack]/lib/Compiler.js:494:13

  - Tapable.js:138 next
    [Travel]/[.0.2.6@tapable]/lib/Tapable.js:138:11

  - CachePlugin.js:62 Compiler.<anonymous>
    [Travel]/[.2.3.2@webpack]/lib/CachePlugin.js:62:5

  - Tapable.js:142 Compiler.applyPluginsAsyncSeries
    [Travel]/[.0.2.6@tapable]/lib/Tapable.js:142:13

  - Compiler.js:491
    [Travel]/[.2.3.2@webpack]/lib/Compiler.js:491:10

  - Tapable.js:131 Compilation.applyPluginsAsyncSeries
    [Travel]/[.0.2.6@tapable]/lib/Tapable.js:131:46

  - Compilation.js:645 self.applyPluginsAsync.err
    [Travel]/[.2.3.2@webpack]/lib/Compilation.js:645:19

  - Tapable.js:131 Compilation.applyPluginsAsyncSeries
    [Travel]/[.0.2.6@tapable]/lib/Tapable.js:131:46

  - Compilation.js:636 self.applyPluginsAsync.err
    [Travel]/[.2.3.2@webpack]/lib/Compilation.js:636:11

  - Tapable.js:131 Compilation.applyPluginsAsyncSeries
    [Travel]/[.0.2.6@tapable]/lib/Tapable.js:131:46

  - Compilation.js:631 self.applyPluginsAsync.err
    [Travel]/[.2.3.2@webpack]/lib/Compilation.js:631:10

  - Tapable.js:131 Compilation.applyPluginsAsyncSeries
    [Travel]/[.0.2.6@tapable]/lib/Tapable.js:131:46

  - Compilation.js:627 sealPart2
    [Travel]/[.2.3.2@webpack]/lib/Compilation.js:627:9

  - Tapable.js:131 Compilation.applyPluginsAsyncSeries
    [Travel]/[.0.2.6@tapable]/lib/Tapable.js:131:46

 ......

Child html-webpack-plugin for "index.html":
         Asset     Size  Chunks  Chunk Names
    index.html  7.51 kB       0

ERROR in ./~/.2.28.0@html-webpack-plugin/lib/loader.js!./Travel/Resource/assets/html/index.html
Module not found: Error: Can't resolve './back.png' in '/Users/chrishu/Projects/Wind/guideios/Travel/Travel/Resource/assets/html'
  @ ./~/.2.28.0@html-webpack-plugin/lib/loader.js!./Travel/Resource/assets/html/index.html 1:2182-2203 1:2367-2388
</code>```

答:
You should add it to the extension list:</p>

```<code>// extensions: [ '.web.js', '.js', '.jsx' ]
extensions: [ '.web.js', '.js', '.jsx', '.png' ]
</code>```

Title: webpack html-loader： <img> tag not triggering url-loader

Body:
When using html-loader, the  tag in the index.html did not trigger url-loader. Here's my webpack configs & html:

webpack config

// webpack config
module.exports = {
  entry: {
    "index": path.join(__dirname, "./src/js/app.js"),
    "guide_index": path.join(__dirname, './src/js/guide_app.js')
  },
  output: {
    path: path.join(__dirname, '/dist'),
    publicPath: '/',
    filename: '[name].[hash].js'
  },
  // loaders
  module: {
    rules: [
      {
        test: /\.(gif|jpe?g|png|svg|mp3|ttf)$/i,
        loader: "url-loader",
        include: [
          "/Users/chrishu/Projects/Wind/guideios/Travel/Travel/Resource/assets/image",
          path.resolve(__dirname, "/src/image"),
          path.resolve(__dirname, "/../Travel/Resource/assets/image"),
          path.resolve(__dirname, "/../Travel/Resource/assets")
        ],
        query: {
          limit: 5000,
          name: '[name].[hash:16].[ext]'
          //name: "./assets/[name].[hash:16].[ext]"
        }
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"]
      },
      {
        test: /\.(js|jsx)$/,
        loader: "babel-loader",
        // exclude: /node_modules/,
        query: { cacheDirectory: true }
      },
      {
        test: /\.html$/,
        use: [ {
          loader: 'html-loader',
          options: {
            minimize: false,
            removeComments: false,
            removeCommentsFromCDATA: false,
            removeCDATASectionsFromCDATA: false,
            collapseWhitespace: false,
            conservativeCollapse: false,
            // removeAttributeQuotes: false,
            // useShortDoctype: false,
            // keepClosingSlash: false,
            minifyJS: false,
            minifyCSS: false,
            // removeScriptTypeAttributes: false,
            // removeStyleTypeAttributes: false
          }
        }]
      }
    ]
  },
  // Plugins
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'guide_index.html',
      template: path.join(__dirname, './src/html/guide_index.html'),
      inject: true,
      chunks: ["guide_index"],
      minify: false,
      chunksSortMode: 'dependency'
    }),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: path.join(__dirname, './src/html/index.html'),
      inject: true,
      chunks: ["index"],
      minify: false,
      chunksSortMode: 'dependency'
    }),
    new webpack.LoaderOptionsPlugin({
      debug: true
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': "'development'"
    })
  ],
  resolve: {
    extensions: [ '.web.js', '.js', '.jsx' ]
  }
}

index.html:

error logs:

Module not found: Error: Can't resolve './back.png' in '/Users/chrishu/Projects/Wind/guideios/Travel/Travel/Resource/assets/html':
Error: Can't resolve './back.png' in '/Users/chrishu/Projects/Wind/guideios/Travel/Travel/Resource/assets/html'

  - compiler.js:76
    [Travel]/[.2.28.0@html-webpack-plugin]/lib/compiler.js:76:16

  - Compiler.js:291 Compiler.<anonymous>
    [Travel]/[.2.3.2@webpack]/lib/Compiler.js:291:10

  - Compiler.js:494
    [Travel]/[.2.3.2@webpack]/lib/Compiler.js:494:13

  - Tapable.js:138 next
    [Travel]/[.0.2.6@tapable]/lib/Tapable.js:138:11

  - CachePlugin.js:62 Compiler.<anonymous>
    [Travel]/[.2.3.2@webpack]/lib/CachePlugin.js:62:5

  - Tapable.js:142 Compiler.applyPluginsAsyncSeries
    [Travel]/[.0.2.6@tapable]/lib/Tapable.js:142:13

  - Compiler.js:491
    [Travel]/[.2.3.2@webpack]/lib/Compiler.js:491:10

  - Tapable.js:131 Compilation.applyPluginsAsyncSeries
    [Travel]/[.0.2.6@tapable]/lib/Tapable.js:131:46

  - Compilation.js:645 self.applyPluginsAsync.err
    [Travel]/[.2.3.2@webpack]/lib/Compilation.js:645:19

  - Tapable.js:131 Compilation.applyPluginsAsyncSeries
    [Travel]/[.0.2.6@tapable]/lib/Tapable.js:131:46

  - Compilation.js:636 self.applyPluginsAsync.err
    [Travel]/[.2.3.2@webpack]/lib/Compilation.js:636:11

  - Tapable.js:131 Compilation.applyPluginsAsyncSeries
    [Travel]/[.0.2.6@tapable]/lib/Tapable.js:131:46

  - Compilation.js:631 self.applyPluginsAsync.err
    [Travel]/[.2.3.2@webpack]/lib/Compilation.js:631:10

  - Tapable.js:131 Compilation.applyPluginsAsyncSeries
    [Travel]/[.0.2.6@tapable]/lib/Tapable.js:131:46

  - Compilation.js:627 sealPart2
    [Travel]/[.2.3.2@webpack]/lib/Compilation.js:627:9

  - Tapable.js:131 Compilation.applyPluginsAsyncSeries
    [Travel]/[.0.2.6@tapable]/lib/Tapable.js:131:46

 ......

Child html-webpack-plugin for "index.html":
         Asset     Size  Chunks  Chunk Names
    index.html  7.51 kB       0

ERROR in ./~/.2.28.0@html-webpack-plugin/lib/loader.js!./Travel/Resource/assets/html/index.html
Module not found: Error: Can't resolve './back.png' in '/Users/chrishu/Projects/Wind/guideios/Travel/Travel/Resource/assets/html'
  @ ./~/.2.28.0@html-webpack-plugin/lib/loader.js!./Travel/Resource/assets/html/index.html 1:2182-2203 1:2367-2388

Body:
You should add it to the extension list:

// extensions: [ '.web.js', '.js', '.jsx' ]
extensions: [ '.web.js', '.js', '.jsx', '.png' ]


问:
Map strings of letters and numbers based on if there's a valid date
I have 5 strings:

```<code>MO170915C00075000

GILD1514H117

9ZZZFD898

AHMIQ

894990415
</code>```

The first two have valid dates between between the first set of numbers and then then the next single letter (ex: C).

If I may ask, how would pick out the first two strings due to the date that's in them (need to identify that they contain a date after the first set of letters and before a single character) and then correctly format the dates?

For the first one, I can get the date using the GSub below:

```<code>("20" + @ticker.gsub(/(\w+?)(\d{6})([a-z])\d+/i,'\2')).to_date
</code>```

答:
You could use Date._parse to see which information could be found by Date.parse.

Without any specification, you'll be basically shooting in the dark. Since the logic is so fuzzy, it cannot work magically with any weird string as input :

```<code>require 'date'
weird_dates = %w(MO170915C00075000 MA20172115C00075000 GILD1514H117 9ZZZFD898 AHMIQ 894990415)

weird_dates.each do |date_str|
  date_hash = Date._parse(date_str)
  puts date_str
  puts "  #{date_hash}"
  if date_hash[:year] && date_hash[:mon] && date_hash[:mday]
    print "  It looks like a date"
    begin
      date = Date.parse(date_str)
      puts " : #{date}"
    rescue ArgumentError
      puts " but it's not a valid one!"
    end
  else
    puts "  Sorry, not enough information"
  end
  puts
end
</code>```

It outputs :

```<code>MO170915C00075000
  {:year=>2017, :mon=>9, :mday=>15}
  It looks like a date : 2017-09-15

MA20172115C00075000
  {:year=>2017, :mon=>21, :mday=>15}
  It looks like a date but it's not a valid one!

GILD1514H117
  {:hour=>1514, :min=>117}
  Sorry, not enough information

9ZZZFD898
  {:yday=>898}
  Sorry, not enough information

AHMIQ
  {}
  Sorry, not enough information

894990415
  {}
  Sorry, not enough information
</code>```

If you know the exact input format, you should use Date.strptime.

Body:
I have 5 strings:

MO170915C00075000

GILD1514H117

9ZZZFD898

AHMIQ

894990415

The first two have valid dates between between the first set of numbers and then then the next single letter (ex: C).

If I may ask, how would pick out the first two strings due to the date that's in them (need to identify that they contain a date after the first set of letters and before a single character) and then correctly format the dates?

For the first one, I can get the date using the GSub below:

("20" + @ticker.gsub(/(\w+?)(\d{6})([a-z])\d+/i,'\2')).to_date

Body:
You could use Date._parse to see which information could be found by Date.parse.

Without any specification, you'll be basically shooting in the dark. Since the logic is so fuzzy, it cannot work magically with any weird string as input :

require 'date'
weird_dates = %w(MO170915C00075000 MA20172115C00075000 GILD1514H117 9ZZZFD898 AHMIQ 894990415)

weird_dates.each do |date_str|
  date_hash = Date._parse(date_str)
  puts date_str
  puts "  #{date_hash}"
  if date_hash[:year] && date_hash[:mon] && date_hash[:mday]
    print "  It looks like a date"
    begin
      date = Date.parse(date_str)
      puts " : #{date}"
    rescue ArgumentError
      puts " but it's not a valid one!"
    end
  else
    puts "  Sorry, not enough information"
  end
  puts
end

It outputs :

MO170915C00075000
  {:year=>2017, :mon=>9, :mday=>15}
  It looks like a date : 2017-09-15

MA20172115C00075000
  {:year=>2017, :mon=>21, :mday=>15}
  It looks like a date but it's not a valid one!

GILD1514H117
  {:hour=>1514, :min=>117}
  Sorry, not enough information

9ZZZFD898
  {:yday=>898}
  Sorry, not enough information

AHMIQ
  {}
  Sorry, not enough information

894990415
  {}
  Sorry, not enough information

If you know the exact input format, you should use Date.strptime.


问:
Can I call APIs in componentWillMount in React?
I'm working on react for last 1 year. The convention which we follow is make an API call in componentDidMount, fetch the data and setState after the data has come. This will ensure that the component has mounted and setting state will cause a re-render the component but I want to know why we can't setState in componentWillMount or constructor

The official documentation says that :

componentWillMount() is invoked immediately before mounting occurs. It
  is called before render(), therefore setting state in this method will
  not trigger a re-rendering. Avoid introducing any side-effects or
  subscriptions in this method.

it says setting state in this method will not trigger a re-rendering, which I don't want while making an API call. If I'm able to get the data and able to set in the state (assuming API calls are really fast) in componentWillMount or in constructor and data is present in the first render, why would I want a re-render at all?

and if the API call is slow, then setState will be async and componentWillMount has already returned then I'll be able to setState and a re-render should occur.

As a whole, I'm pretty much confused why we shouldn't make API calls in constructor or componentWillMount. Can somebody really help me understand how react works in such case?

答:
1. componentWillMount and re-rendering

Compare this two componentWillMount methods.

One causes additional re-render, one does not

```<code>componentWillMount () {
  // This will not cause additional re-render
  this.setState({ name: 'Andrej '});
}

componentWillMount () {
  fetch('http://whatever/profile').then(() => {
    // This in the other hand will cause additional rerender,
    // since fetch is async and state is set after request completes.
    this.setState({ name: 'Andrej '});
  })
}
</code>```

.

.

.

2. Where to invoke API calls?

```<code>componentWillMount () {
  // Is triggered on server and on client as well.
  // Server won't wait for completion though, nor will be able to trigger re-render
  // for client.
  fetch('...')
}

componentDidMount () {
  // Is triggered on client, but never on server.
  // This is a good place to invoke API calls.
  fetch('...')
}
</code>```

If you are rendering on server and your component does need data for rendering, you should fetch (and wait for completion) outside of component and pass data thru props and render component to string afterwards.

Body:
1. componentWillMount and re-rendering

Compare this two componentWillMount methods.

One causes additional re-render, one does not

componentWillMount () {
  // This will not cause additional re-render
  this.setState({ name: 'Andrej '});
}

componentWillMount () {
  fetch('http://whatever/profile').then(() => {
    // This in the other hand will cause additional rerender,
    // since fetch is async and state is set after request completes.
    this.setState({ name: 'Andrej '});
  })
}

.

.

.

2. Where to invoke API calls?

componentWillMount () {
  // Is triggered on server and on client as well.
  // Server won't wait for completion though, nor will be able to trigger re-render
  // for client.
  fetch('...')
}

componentDidMount () {
  // Is triggered on client, but never on server.
  // This is a good place to invoke API calls.
  fetch('...')
}

If you are rendering on server and your component does need data for rendering, you should fetch (and wait for completion) outside of component and pass data thru props and render component to string afterwards.


问:
Elements from xml using php
so I can access an xml file and all its elements using

```<code>$xml = simplexml_load_file('file.xml');
</code>```

Inside there are items and some of them have images, some more than others. I, of course, receive this file from another server. These images live inside an element called 'images' and the xml file looks like this:

```<code><images>
    <image id="1" time_modif="1490197696">
        *** url here   ***
    </image >
    <image id="2" time_modif="1490197699">
        *** url here   ***
    </ image >
    <image id="3" time_modif="1490197702">
        *** url here   ***
    </image >
</images >
</code>```

I am in desperate need to loop through these images and get their Url. For that I've tried:

```<code>$element = $xml->element;
$i = 0;

foreach ($element->images as $img)
{
    echo $img->image[$i] . '<br>';
    $i++
}
</code>```

but the 'foreach' loop only returns the first url, and not the others.

Does anyone have any thoughts?

Thanks in advance !

答:
@martin, can you give full structure on one of the image elements within the , as I believe you're trying to load directly from the XML file.

In the meantime, I suggest you read the following for help

https://www.w3schools.com/php/func_simplexml_load_file.asp

http://blog.teamtreehouse.com/how-to-parse-xml-with-php5

This shows you how to access required item(s) inform of array.

Hope this helps

Title: Elements from xml using php

Body:
so I can access an xml file and all its elements using

$xml = simplexml_load_file('file.xml');

Inside there are items and some of them have images, some more than others. I, of course, receive this file from another server. These images live inside an element called 'images' and the xml file looks like this:

<images>
    <image id="1" time_modif="1490197696">
        *** url here   ***
    </image >
    <image id="2" time_modif="1490197699">
        *** url here   ***
    </ image >
    <image id="3" time_modif="1490197702">
        *** url here   ***
    </image >
</images >

I am in desperate need to loop through these images and get their Url. For that I've tried:

$element = $xml->element;
$i = 0;

foreach ($element->images as $img)
{
    echo $img->image[$i] . '
';
    $i++
}

but the 'foreach' loop only returns the first url, and not the others.

Does anyone have any thoughts?

Thanks in advance !


问:
Why can't I retrieve the data I expect from sqlite database?
I created a database on my phone and put some data in it. When I executed the following command:

```<code>`select * from DailyAffairEntry;`
</code>```

I got all items in the table whose name is DailyAffairEntry.

1491033937313|1491033941293|1491033968286|0.5h|0h0m|gsdfsdgsdgqqqqqqqqqqqqqqqqqqqqqqq|Finished|Daily|no_data
1491034484096|1491034484096|1491034484096|0.5h|0|xvcxc|Ongoing|Daily|no_data
1491034492043|1491034509143|1491034492043|0.5h|0|xcvd|Ongoing|Daily|no_data
1491034495083|1491034499634|1491034517595|0.5h|0h0m|cxvxds|Finished|Daily|no_data
1491041080956|1491041080956|1491041080956|0.5h|0|dddddfsd|Waiting|Daily|no_data

The first column's name is StartTime

But when I execute the following command:

select * from DailyAffairEntry where StartTime between '10000000000000' and '1500000000000';

I only got two of them, which are
1491034484096|1491034484096|1491034484096|0.5h|0|xvcxc|Ongoing|Daily|no_data
1491041080956|1491041080956|1491041080956|0.5h|0|dddddfsd|Waiting|Daily|no_data

Whereas I expected to get all of them.

Is there any problem with my command? Why can't I get what I want? Please help me.

答:
Supplying the table specification would have made it simpler to reproduce the issue.

I created the table CREATE TABLEDailyAffairTable(StartTimeINTEGER,Field2INTEGER,Field3INTEGER,Field4INTEGER,Field5INTEGER,Field6INTEGER,Field7INTEGER,Field8INTEGER,Field9INTEGER )

Using the query:
select * from DailyAffairTable
where startTime between 1000000000000 and 15000000000000

And I see all five rows (the DB Browser doesn't copy null fields):
'"1491033937313"    "1491033941293" "1491033968286"

"1491034484096" "141034484096"  "141034484096"

"1491034492043" "1491034509143" "1491034492043"

"1491034495083" "1491034499634" "1491034517595"

"1491033937313" "1491041080956" "1491041080956"
'

So it works for me...

Body:
I created a database on my phone and put some data in it. When I executed the following command:

`select * from DailyAffairEntry;`

I got all items in the table whose name is DailyAffairEntry.

1491033937313|1491033941293|1491033968286|0.5h|0h0m|gsdfsdgsdgqqqqqqqqqqqqqqqqqqqqqqq|Finished|Daily|no_data
1491034484096|1491034484096|1491034484096|0.5h|0|xvcxc|Ongoing|Daily|no_data
1491034492043|1491034509143|1491034492043|0.5h|0|xcvd|Ongoing|Daily|no_data
1491034495083|1491034499634|1491034517595|0.5h|0h0m|cxvxds|Finished|Daily|no_data
1491041080956|1491041080956|1491041080956|0.5h|0|dddddfsd|Waiting|Daily|no_data

The first column's name is StartTime

But when I execute the following command:

select * from DailyAffairEntry where StartTime between '10000000000000' and '1500000000000';

I only got two of them, which are
1491034484096|1491034484096|1491034484096|0.5h|0|xvcxc|Ongoing|Daily|no_data
1491041080956|1491041080956|1491041080956|0.5h|0|dddddfsd|Waiting|Daily|no_data

Whereas I expected to get all of them.

Is there any problem with my command? Why can't I get what I want? Please help me.


答:
You can look into the theory behind this, and then do the only reasonable thing -forget about writing such kind of code.

In good OOP you consider your fields to be part of your "secret" internal implementation. You don't use fields of sub classes in the super class context. Period.

You are even very conservative about making a field protected in the superclass and to use that in subclasses.

Title: How can I get the data fields from subclass not superclass?


问:
Capitalizing words in a string using C#
I need to take a string, and capitalize words in it. Certain words ("in", "at", etc.), are not capitalized and are changed to lower case if encountered. The first word should always be capitalized. Last names like "McFly" are not in the current scope, so the same rule will apply to them - only first letter capitalized.

For example: "of mice and men By CNN" should be changed to "Of Mice and Men by CNN". (Therefore ToTitleString won't work here.)

What would be the best way to do that?

I thought of splitting the string by spaces, and go over each word, changing it if necessary, and concatenating it to the previous word, and so on.
It seems pretty naive and I was wondering if there's a better way to do it. I am using .NET 3.5.

答:
The easiest obvious solution (for English sentences) would be to:

"sentence".Split(" ") the sentence on space characters

Loop through each item

Capitalize the first letter of each item - item[i][0].ToUpper(),

Remerge back into a string joined on a space.

Repeat this process with "." and "," using that new string.

Title: Capitalizing words in a string using C#


问:
Wildfy add ManagedExecutorService
I want to add new ManagedExecutorService resource to WildFly 10.

I edit standalone.xml, and add line to <managed-executor-services>:

```<code><managed-executor-service
    name="test"
    jndi-name="java:jboss/ee/concurrency/executor/test"
    context-service="test"
    long-running-tasks="true"
/>
</code>```

After restarting wildfy I can't find - java:jboss/ee/concurrency/executor/test - in my JNDI view, and of course can't find this resource by InitialContext.

What I did wrong? Thanks.

答:
After doing  a lot of experiments I delete property context-service in <managed-executor-service> and it works!

After it I can see java:jboss/ee/concurrency/executor/test in JNDI view.

Now my <managed-executor-services> see like that:

```<code><managed-executor-service
    name="test"
    jndi-name="java:jboss/ee/concurrency/executor/test"
    long-running-tasks="true"
/>
</code>```

Title: Wildfy add ManagedExecutorService

Body:
I want to add new ManagedExecutorService resource to WildFly 10.

I edit standalone.xml, and add line to <managed-executor-services>:

<managed-executor-service
    name="test"
    jndi-name="java:jboss/ee/concurrency/executor/test"
    context-service="test"
    long-running-tasks="true"
/>

After restarting wildfy I can't find - java:jboss/ee/concurrency/executor/test - in my JNDI view, and of course can't find this resource by InitialContext.

What I did wrong? Thanks.

Body:
After doing  a lot of experiments I delete property context-service in <managed-executor-service> and it works!

After it I can see java:jboss/ee/concurrency/executor/test in JNDI view.

Now my <managed-executor-services> see like that:

<managed-executor-service
    name="test"
    jndi-name="java:jboss/ee/concurrency/executor/test"
    long-running-tasks="true"
/>