问:
seed images using carrierwave
I am trying to create a Angular 4 app that uses a rails API to display and upload images. to upload images using the rails API I have decided to use carrierwave. what I would like to know is how do I seed some initial images and store the url in the database? below is what I have done in my db.seed file

```<code>Pictures.create!(
    image: Rails.root.join("C:/Ciaran/admin/src/assets/images/test_img1.jpg").open,
)
</code>```

However where is the image stored in my rails app folder? I do not see it anywhere.

And when I inspect the pictures table in MySQL for the image column the whole url is not displayed only test_img1.jpg? How do I make it show the full url?

So basically if someone who knows more about rails and carrierwave could please explain to me:

For the code snippet that I have shown above does that create a copy of the image into my rails app? because I do not see it in any of the apps folders once I have seeded the database?

why is the full url not displayed in the database table for pictures and how do I get it to display the full url so I can access it from my angular front end?

Thank you for your help

答:
1 - in your app folder there should be a file called image_uploader.rb. And it should have a def store_dir which indicates where is your files are stored.

2 - because full url is generated based on the above image_uploader.rb configuration file. You can simply get the url for example if your model instance variable is @picture

```<code>@picture = Picture.first
@picture.image.thumb.url
</code>```

Title: seed images using carrierwave

Body:
I am trying to create a Angular 4 app that uses a rails API to display and upload images. to upload images using the rails API I have decided to use carrierwave. what I would like to know is how do I seed some initial images and store the url in the database? below is what I have done in my db.seed file

Pictures.create!(
    image: Rails.root.join("C:/Ciaran/admin/src/assets/images/test_img1.jpg").open,
)

However where is the image stored in my rails app folder? I do not see it anywhere.

And when I inspect the pictures table in MySQL for the image column the whole url is not displayed only test_img1.jpg? How do I make it show the full url?

So basically if someone who knows more about rails and carrierwave could please explain to me:

For the code snippet that I have shown above does that create a copy of the image into my rails app? because I do not see it in any of the apps folders once I have seeded the database?

why is the full url not displayed in the database table for pictures and how do I get it to display the full url so I can access it from my angular front end?

Thank you for your help

Body:
1 - in your app folder there should be a file called image_uploader.rb. And it should have a def store_dir which indicates where is your files are stored.

2 - because full url is generated based on the above image_uploader.rb configuration file. You can simply get the url for example if your model instance variable is @picture

@picture = Picture.first
@picture.image.thumb.url


来源: stackexchange

问:
loading xml field in a fixture xml file (phpunit)
I am working with phpunit and loading data through fixtures, now in one scenario I have a column in my table which accepts only xml data but I am unable to pass any xml data via field in fixtures file.

What I have tried:

```<code><?xml version="1.0"?>
<mysqldump xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<database name="phpunit">
    <table_data name="testtable">
        <row>
            <field name="name">My Test</field>
            <field name="active">1</field>
            <field name="xml_order">
                <Attributes>
                    <Attribute>
                        <Option Value="A">A1</Option>
                        <Option Value="B">B1</Option>
                        <Option Value="C">C1</Option>
                    </Attribute>
                </Attributes>
            </field>
        </row>
    </table_data>
</database>
</code>```

I am unable to load field "xml_order" data into dB. Tried looking out for solutions but was unable to. Can anyone help me out with this ? I want to load it in this xml only not in the my test file

答:
Since <Attributes/> is a regular xml in the xml fixture file, when dbunit reads it it does

```<code>// a bit simplified
// please visit https://github.com/sebastianbergmann/dbunit/blob/master/src/DataSet/MysqlXmlDataSet.php to get more details
$column = $rowElement->xpath('./field[@name="' . $columnName . '"]');
$columnValue = (string) $column;
</code>```

and it's textual value is a string of empty space characters. Actually this is just normal for xml by nature. To overcome this you can wrap in CDATA all xml stuff that you want to be treated as string during value extraction:

```<code><field name="xml_order">
    <![CDATA[
        <Attributes>
            <Attribute>
                <Option Value="A">A1</Option>
                <Option Value="B">B1</Option>
                <Option Value="C">C1</Option>
            </Attribute>
        </Attributes>
    ]]>
</field>
</code>```

Please also note that actual string will still have quite a bunch of spaces and newlines before and after the actual xml string. I this is not wanted for some reasons you might do:

```<code><field name="xml_order"><![CDATA[<Attributes>
    <Attribute>
        <Option Value="A">A1</Option>
        <Option Value="B">B1</Option>
        <Option Value="C">C1</Option>
    </Attribute>
</Attributes>]]></field>
</code>```

does not look nice, though, but will give you no spaces before or after.

As an alternative you might consider using array based dataset:

```<code>// or it could be \PHPUnit_Extensions_Database_DataSet_ArrayDataSet
// depending on the dbunit version you use
return new PHPUnit\DbUnit\DataSet\ArrayDataSet([
    'testtable' => [
        ["name" => "MyTest", "active" => 1, "xml_order" => '<what><ever>xml</ever></what>'],
    ]
]);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am working with phpunit and loading data through fixtures, now in one scenario I have a column in my table which accepts only xml data but I am unable to pass any xml data via field in fixtures file.

What I have tried:

<?xml version="1.0"?>
<mysqldump xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<database name="phpunit">
    <table_data name="testtable">
        <row>
            <field name="name">My Test</field>
            <field name="active">1</field>
            <field name="xml_order">
                <Attributes>
                    <Attribute>
                        <Option Value="A">A1</Option>
                        <Option Value="B">B1</Option>
                        <Option Value="C">C1</Option>
                    </Attribute>
                </Attributes>
            </field>
        </row>
    </table_data>
</database>

I am unable to load field "xml_order" data into dB. Tried looking out for solutions but was unable to. Can anyone help me out with this ? I want to load it in this xml only not in the my test file

Body:
Since <Attributes/> is a regular xml in the xml fixture file, when dbunit reads it it does

// a bit simplified
// please visit https://github.com/sebastianbergmann/dbunit/blob/master/src/DataSet/MysqlXmlDataSet.php to get more details
$column = $rowElement->xpath('./field[@name="' . $columnName . '"]');
$columnValue = (string) $column;

and it's textual value is a string of empty space characters. Actually this is just normal for xml by nature. To overcome this you can wrap in CDATA all xml stuff that you want to be treated as string during value extraction:

<field name="xml_order">
    <![CDATA[
        <Attributes>
            <Attribute>
                <Option Value="A">A1</Option>
                <Option Value="B">B1</Option>
                <Option Value="C">C1</Option>
            </Attribute>
        </Attributes>
    ]]>
</field>

Please also note that actual string will still have quite a bunch of spaces and newlines before and after the actual xml string. I this is not wanted for some reasons you might do:

<field name="xml_order"><![CDATA[<Attributes>
    <Attribute>
        <Option Value="A">A1</Option>
        <Option Value="B">B1</Option>
        <Option Value="C">C1</Option>
    </Attribute>
</Attributes>]]></field>

does not look nice, though, but will give you no spaces before or after.

As an alternative you might consider using array based dataset:

// or it could be \PHPUnit_Extensions_Database_DataSet_ArrayDataSet
// depending on the dbunit version you use
return new PHPUnit\DbUnit\DataSet\ArrayDataSet([
    'testtable' => [
        ["name" => "MyTest", "active" => 1, "xml_order" => '<what><ever>xml</ever></what>'],
    ]
]);


问:
Does changing the value of an object in a subarray change the value of the object in the "main" array?

I am working with an array of object in p5.js. If some condition related to a value of the object is met, I create another array to hold those 'valid' objects.

I want to change the value of the object for both the 'valid objects' array and the 'main' array. If I change it from the 'valid obj' array, does it change it from the 'main' array too?

```<code>var objects[];
var validObjects[];

function setup() {
    createObj();
    myFunc2();
}

function object( name, condition ) {
    // Define a class called 'object'.
    this.name = name;
    this.condition = condition;
}

function createObj() {
    objects[0] = new object( 'obj0', true );
    objects[1] = new object( 'obj1', true );
    objects[2] = new object( 'obj2', false );
    objects[3] = new object( 'obj3', false );
}

function myFunc() {
    // Pick out the valid objects and put them into another array.
    for( var i = 0; i < objects.length; i++ ) {
        if( objects[i].condition == true )
            validObjects.push( objects[i] );
}

function myFunc2() {
    // Change a field of the objects from the new array.
    for( var i = 0; i < validObjects.length; i++ )
        objects[i].condition = !objects[i].condition;
}
</code>```

Does myFunc2() change the condition field of the objects forever? Or should I approach this differently?

EDITS: Fixed syntax.

答:
Yes in javascript all objects are assigned by reference and not value.  When you want to make a copy of an object you need to clone it.

```<code> var clone = Object.assign({}, cloneTarget);
</code>```

Also your syntax on:

```<code>objects[0] = new object( obj0, true );
</code>```

Seems to be off you should be changing these names to literals and not identifiers correct?

```<code>objects[0] = new object( 'obj0', true );
</code>```

Body:
I am working with an array of object in p5.js. If some condition related to a value of the object is met, I create another array to hold those 'valid' objects.

I want to change the value of the object for both the 'valid objects' array and the 'main' array. If I change it from the 'valid obj' array, does it change it from the 'main' array too?

var objects[];
var validObjects[];

function setup() {
    createObj();
    myFunc2();
}

function object( name, condition ) {
    // Define a class called 'object'.
    this.name = name;
    this.condition = condition;
}

function createObj() {
    objects[0] = new object( 'obj0', true );
    objects[1] = new object( 'obj1', true );
    objects[2] = new object( 'obj2', false );
    objects[3] = new object( 'obj3', false );
}

function myFunc() {
    // Pick out the valid objects and put them into another array.
    for( var i = 0; i < objects.length; i++ ) {
        if( objects[i].condition == true )
            validObjects.push( objects[i] );
}

function myFunc2() {
    // Change a field of the objects from the new array.
    for( var i = 0; i < validObjects.length; i++ )
        objects[i].condition = !objects[i].condition;
}

Does myFunc2() change the condition field of the objects forever? Or should I approach this differently?

EDITS: Fixed syntax.

Body:
Yes in javascript all objects are assigned by reference and not value.  When you want to make a copy of an object you need to clone it.

 var clone = Object.assign({}, cloneTarget);

Also your syntax on:

objects[0] = new object( obj0, true );

Seems to be off you should be changing these names to literals and not identifiers correct?

objects[0] = new object( 'obj0', true );


问:
Heroku custom domains on Cloudflare: Too many redirects
Objectives

Run https://rapid.essbap.org through Cloudflare.

This should map to https://ebcc-rrn.herokuapp.com (Rails app)

However, I get "too many redirects" pages, e.g.

Have done this successfully before on other Heroku apps, using steps below

What am I missing?

What I did

Purchased essbap.org through Godaddy.

Imported DNS to Cloudflare.

Inserted Cloudflare name servers at Godaddy.

Removed zone records from Godaddy.

Cloudflare:

Inserted CNAME record rapid to point to ebcc-rrn.herokuapp.com

On Heroku: added custom domain rapid.essbap.org to ebcc-rrn.herokuapp.com

Heroku:

```<code>heroku domains:add rapid.essbap.org

=== ebcc-rrn Heroku Domain
ebcc-rrn.herokuapp.com

=== ebcc-rrn Custom Domains
Domain Name       DNS Target
----------------  ----------------------
rapid.essbap.org  ebcc-rrn.herokuapp.com

$ host rapid.essbap.org
rapid.essbap.org has address 104.27.162.137
rapid.essbap.org has address 104.27.163.137
</code>```

Cloudflare settings

JUST ADDED:

Running curl

When I run curl against another Heroku custom domain app that I know works, it looks like:

```<code>$ curl -I some.custom_app.com
HTTP/1.1 301 Moved Permanently
Location: https://some.custom_app.com/

# since I'm using force_ssl on Rails, we expect to be directed to https://

$ curl -I https://some.custom_app.com/
HTTP/1.1 200 OK
</code>```

Similar behaviour for ebcc-rrn.herokuapp.com (the Herokuapp we want rapid.essbap.org to be an alias for). A 301 then 200.

But when I run curl against rapid.essbap.org, I get:

```<code>$ curl -I rapid.essbap.org
HTTP/1.1 301 Moved Permanently
Location: https://rapid.essbap.org/

# since I'm using force_ssl on Rails, we expect to be directed to https://

$ curl -I https://rapid.essbap.org
HTTP/1.1 301 Moved Permanently
Location: https://rapid.essbap.org/
</code>```

We get a 301 instead of a 200 in the second case. Am not sure why the 301 is being generated. Does not happen in dev or with ebcc-rrn.herokuapp.com.

What am I missing?

答: Im my case setting Crypto -> SSL Flexible to Full did the trick.

Body:
Objectives

Run https://rapid.essbap.org through Cloudflare.

This should map to https://ebcc-rrn.herokuapp.com (Rails app)

However, I get "too many redirects" pages, e.g.

Have done this successfully before on other Heroku apps, using steps below

What am I missing?

What I did

Purchased essbap.org through Godaddy.

Imported DNS to Cloudflare.

Inserted Cloudflare name servers at Godaddy.

Removed zone records from Godaddy.

Cloudflare:

Inserted CNAME record rapid to point to ebcc-rrn.herokuapp.com

On Heroku: added custom domain rapid.essbap.org to ebcc-rrn.herokuapp.com

Heroku:

heroku domains:add rapid.essbap.org

=== ebcc-rrn Heroku Domain
ebcc-rrn.herokuapp.com

=== ebcc-rrn Custom Domains
Domain Name       DNS Target
----------------  ----------------------
rapid.essbap.org  ebcc-rrn.herokuapp.com

$ host rapid.essbap.org
rapid.essbap.org has address 104.27.162.137
rapid.essbap.org has address 104.27.163.137

Cloudflare settings

JUST ADDED:

Running curl

When I run curl against another Heroku custom domain app that I know works, it looks like:

$ curl -I some.custom_app.com
HTTP/1.1 301 Moved Permanently
Location: https://some.custom_app.com/

# since I'm using force_ssl on Rails, we expect to be directed to https://

$ curl -I https://some.custom_app.com/
HTTP/1.1 200 OK

Similar behaviour for ebcc-rrn.herokuapp.com (the Herokuapp we want rapid.essbap.org to be an alias for). A 301 then 200.

But when I run curl against rapid.essbap.org, I get:

$ curl -I rapid.essbap.org
HTTP/1.1 301 Moved Permanently
Location: https://rapid.essbap.org/

# since I'm using force_ssl on Rails, we expect to be directed to https://

$ curl -I https://rapid.essbap.org
HTTP/1.1 301 Moved Permanently
Location: https://rapid.essbap.org/

We get a 301 instead of a 200 in the second case. Am not sure why the 301 is being generated. Does not happen in dev or with ebcc-rrn.herokuapp.com.

What am I missing?


问:
Android C++ Development with Visual Studio
I am trying to figure out how to setup android development with Visual Studio. I plan on using C++ (targeting 2.3 and above), but I see very little on the subject. Does anyone know how to do this?

I know that Android development suggests Java/Eclipse, however, I want to do C++/VS.

答: Take a look at this or this.</p>

ContentLicense: CC BY-SA 2.5

Body: Take a look at this or this.


问:
How to change the position of an element when I do a click action
So I'm designing an application that makes it easy to fetch result from wikipedia. Now What I want to do firstly is that when the search value has been entered into the search bar and I click on the search Icon, I want the search bar to move up and create space for the incoming result. Yes I have some codes but it's not working yet. Also The API call to wikipedia seems not to be working as well, I will also need help with that. Below is the Javascript code: </p>

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

  let searchValue = document.getElementById("#searchString").value;

  $(".sbutton").on("click", function() {
    // code to push the wrap div element and icon up the container
    $(".wrap").animate({
      marginTop: "5px"
    });

    let baseUrl = " https://en.wikipedia.org/w/api.php? ";
    let tailUrl =
      "action=opensearch&format=jsonfm&search=" + searchValue + "&limit=10";
    let wikiLink = baseUrl + tailUrl;

    $.ajax({
      url: wikiLink,
      type: "GET",
      dataType: "json",
      success: function getWikiData(data) {
        let dDiv = document.createElement("div");
        dDiv = "content";
        dDiv.className = "secondDiv";
document.getElementByClassName("container").append(dDiv);
        for (var i = 0; i < data.opensearch.search.length; i++) {
          $("#content").appendChild(
            "<p>" + data.opensearch.search[2].title + "</p>"
          );
        }
      },

      error: function(error) {
        console.log(error);
      }
    });
  });
});
</code>```

答:
```<code>$(".wrap").animate({ marginTop: "+=30px"}, 500 );
</code>```

will be more smooth

Body:
So I'm designing an application that makes it easy to fetch result from wikipedia. Now What I want to do firstly is that when the search value has been entered into the search bar and I click on the search Icon, I want the search bar to move up and create space for the incoming result. Yes I have some codes but it's not working yet. Also The API call to wikipedia seems not to be working as well, I will also need help with that. Below is the Javascript code:

$(document).ready(function() {

  let searchValue = document.getElementById("#searchString").value;

  $(".sbutton").on("click", function() {
    // code to push the wrap div element and icon up the container
    $(".wrap").animate({
      marginTop: "5px"
    });

    let baseUrl = " https://en.wikipedia.org/w/api.php? ";
    let tailUrl =
      "action=opensearch&format=jsonfm&search=" + searchValue + "&limit=10";
    let wikiLink = baseUrl + tailUrl;

    $.ajax({
      url: wikiLink,
      type: "GET",
      dataType: "json",
      success: function getWikiData(data) {
        let dDiv = document.createElement("div");
        dDiv = "content";
        dDiv.className = "secondDiv";
document.getElementByClassName("container").append(dDiv);
        for (var i = 0; i < data.opensearch.search.length; i++) {
          $("#content").appendChild(
            "
" + data.opensearch.search[2].title + "
"
          );
        }
      },

      error: function(error) {
        console.log(error);
      }
    });
  });
});

Body:
$(".wrap").animate({ marginTop: "+=30px"}, 500 );

will be more smooth


问:
Native SVG to Canvas or SVG to image conversion
I read this:Is there a way to convert SVG files to HTML5's canvas compatible commands? and tried google.

Is there a native (cross-browser) way? SVG document is on screen as pixels after browser has rendered it on screen and it would be the simplest task to give those pixels as an image to user.

答:
This is now possible native.

From MDN,

```<code>var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +
           '<foreignObject width="100%" height="100%">' +
           '<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +
             '<em>I</em> like ' +
             '<span style="color:white; text-shadow:0 0 2px blue;">' +
             'cheese</span>' +
           '</div>' +
           '</foreignObject>' +
           '</svg>';

var DOMURL = window.URL || window.webkitURL || window;

var img = new Image();
var svg = new Blob([data], {type: 'image/svg+xml'});
var url = DOMURL.createObjectURL(svg);

img.onload = function() {
  ctx.drawImage(img, 0, 0);
  DOMURL.revokeObjectURL(url);
}

img.src = url;
</code>```

Just replace the svg string with your own svg.

PS. The perf seems to be much much better by rendering on canvas vs rendering as normal DOM! Perf for render to canvas seems consistently around 50x faster than perf for normal dom (tested on Chrome, Safari, and mobile Chrome).

Body:
This is now possible native.

From MDN,

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +
           '<foreignObject width="100%" height="100%">' +
           '<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +
             '<em>I</em> like ' +
             '<span style="color:white; text-shadow:0 0 2px blue;">' +
             'cheese</span>' +
           '</div>' +
           '</foreignObject>' +
           '</svg>';

var DOMURL = window.URL || window.webkitURL || window;

var img = new Image();
var svg = new Blob([data], {type: 'image/svg+xml'});
var url = DOMURL.createObjectURL(svg);

img.onload = function() {
  ctx.drawImage(img, 0, 0);
  DOMURL.revokeObjectURL(url);
}

img.src = url;

Just replace the svg string with your own svg.

PS. The perf seems to be much much better by rendering on canvas vs rendering as normal DOM! Perf for render to canvas seems consistently around 50x faster than perf for normal dom (tested on Chrome, Safari, and mobile Chrome).


问:
Rails5 + jquery-fileupload-rails + carrierwave + Amazon S3, script issue
Hey everyone.

It is my first post here (and probably not the last one...)

I'm building a Rails application where the admin can create recipe. Each recipe is listed on a index and the admin can add things such as, the title, the ingredients, the time you have to spend on the recipe etc...

Now I would like to be able to upload picture for this recipe.

As I had no idea on how to achieve this I decided to start a new app from scratch where you have a user with a name and a picture.

I already achieved to upload picture for the users (avatar) sort of with a basic upload form :

```<code><%= f.file_field :image %>
</code>```

As mentionned in the title this upload goes on amazon S3. I use the 'fog-aws' gem trough carrierwave with the help of MiniMagick to display the image the way I want. Also 'figaro' gem to hide my ID for amazon s3.

I also tried to update multiple files using the same process.
That works fine. And you can find the tutorial I was following on this page : HERE

But the user has to wait and nothing is really going on on the screen meanwhile the picture is uploading. Maybe the user could think that something went wrong and just leave the page and eventually be frustrated or something.

This is why I had the idea to use jQuery File Upload for rails.

Problem is that all the tutorials are very outdated and I can't find anything working properly with all the things together (s3, carrierwave, jquery). The tutorials I found are from 2013 or so... Couldn't find anything revelant.

Except for this one. Even if (again) it is from 2014.

This script allows you to upload multiple file a the time and delete them etc... by simply paste the code in any view. I tried it but there are many problems and the first one is this :

```<code><%= javascript_include_tag 'jquery.iframe-transport.js' %>
<%= javascript_include_tag 'jquery.fileupload.js' %>
<%= javascript_include_tag 'jquery.fileupload-ui.js' %>
</code>```

When I try the code I get this error :

```<code>The asset "jquery.iframe-transport.js" is not present in the asset pipeline.
</code>```

I don't think it is necessary as you should be able to get it from the application.js file with this //= require jquery-fileupload, right ?

When I remove those lines the script is loading but it looks like this :

jquery

As you can see, you can select the file but it should show the picture below.

And only the cancel button is working and removes the hr
 which means the "pictures" I guess. But the upload and the delete wont work, same for the checkbox.

Anyone could help me to make this work somehow ?

The problem could come from s3 ? or is it a script problem ? I never coded java so I don't really see where it could be a error in there.

If anyone can help or at least show me the way I would appreciate it.

Thanks

答:
So... I tried for the last 6 hours to make this happen. I successfully installed Yarn and Webpack on my rails app. According to the installation instruction you can install everything via the gemfile without having to "rails new" again.

By default when I go on my browser I can see the message (javascript/application.js -> console.log('Hello World from Webpacker')).
Nevertheless I don't understand how everything is working even after reading this and this.
I tried the Refile Gem for my uploads. Everything works. I'd like (as my first post indicates) create a progress bar. I have a coffee script for that. I put my script in my_app/javascript/users.coffee and in application.js I wrote this :

```<code>require(users.coffee)
</code>```

I have a error.
Then I tried to write this :

```<code>//= require refile
//= require popper
//= require bootstrap
//= jquery
//= require_tree .
</code>```

And I have a error again.

Here is my coffee script :

```<code>jQuery ->
  $(document).on "upload:start", "form", (e) ->
    $(this).find("input[type=submit]").attr "disabled", true
    $("#progress-bar").slideDown('fast')

  $(document).on "upload:progress", "form", (e) ->
    detail          = e.originalEvent.detail
    percentComplete = Math.round(detail.loaded / detail.total * 100)
    $('.progress-bar').width("#{percentComplete}%");
    $("#progress-bar-text").text("#{percentComplete}% Complete")

  $(document).on "upload:success", "form", (e) ->
    $(this).find("input[type=submit]").removeAttr "disabled"  unless $(this).find("input.uploading").length
    $("#progress-bar").slideUp('fast')
</code>```

By the way I changed to this my application.html.erb

```<code><%= javascript_pack_tag 'application' %>
</code>```

I also bin/yarn add refile and rails webpacker:compile

The result of my package.json :

```<code>{
  "name": "UploadRefile",
  "private": true,
  "dependencies": {
    "@rails/webpacker": "^3.0.2",
    "coffeescript": "1.12.7",
    "jquery": "^3.2.1",
    "refile": "^0.2.11"
  },
  "devDependencies": {
    "webpack-dev-server": "^2.9.5"
  }
}
</code>```

Still not working.
I also tried to use decaffeinate to modify my coffee script. The result is this :

```<code>jQuery(function() {
  $(document).on("upload:start", "form", function(e) {
    $(this).find("input[type=submit]").attr("disabled", true);
    return $("#progress-bar").slideDown('fast');
  });

  $(document).on("upload:progress", "form", function(e) {
    const { detail }          = e.originalEvent;
    const percentComplete = Math.round((detail.loaded / detail.total) * 100);
    $('.progress-bar').width(`${percentComplete}%`);
    return $("#progress-bar-text").text(`${percentComplete}% Complete`);
  });

  return $(document).on("upload:success", "form", function(e) {
    if (!$(this).find("input.uploading").length) { $(this).find("input[type=submit]").removeAttr("disabled"); }
    return $("#progress-bar").slideUp('fast');
  });
});
</code>```

Error again.

Anybody could lead me towards something ? Because I can't move forward really. I'm a patient guy but I don't understand the webpack process. The explanation are very confusing even if they say the opposit. I simply want to get a progress bar working. With carrierwave or with refile. Doesn't really matter.

Thanks for you help

Body:
Hey everyone.

It is my first post here (and probably not the last one...)

I'm building a Rails application where the admin can create recipe. Each recipe is listed on a index and the admin can add things such as, the title, the ingredients, the time you have to spend on the recipe etc...

Now I would like to be able to upload picture for this recipe.

As I had no idea on how to achieve this I decided to start a new app from scratch where you have a user with a name and a picture.

I already achieved to upload picture for the users (avatar) sort of with a basic upload form :

<%= f.file_field :image %>

As mentionned in the title this upload goes on amazon S3. I use the 'fog-aws' gem trough carrierwave with the help of MiniMagick to display the image the way I want. Also 'figaro' gem to hide my ID for amazon s3.

I also tried to update multiple files using the same process.
That works fine. And you can find the tutorial I was following on this page : HERE

But the user has to wait and nothing is really going on on the screen meanwhile the picture is uploading. Maybe the user could think that something went wrong and just leave the page and eventually be frustrated or something.

This is why I had the idea to use jQuery File Upload for rails.

Problem is that all the tutorials are very outdated and I can't find anything working properly with all the things together (s3, carrierwave, jquery). The tutorials I found are from 2013 or so... Couldn't find anything revelant.

Except for this one. Even if (again) it is from 2014.

This script allows you to upload multiple file a the time and delete them etc... by simply paste the code in any view. I tried it but there are many problems and the first one is this :

<%= javascript_include_tag 'jquery.iframe-transport.js' %>
<%= javascript_include_tag 'jquery.fileupload.js' %>
<%= javascript_include_tag 'jquery.fileupload-ui.js' %>

When I try the code I get this error :

The asset "jquery.iframe-transport.js" is not present in the asset pipeline.

I don't think it is necessary as you should be able to get it from the application.js file with this //= require jquery-fileupload, right ?

When I remove those lines the script is loading but it looks like this :

jquery

As you can see, you can select the file but it should show the picture below.

And only the cancel button is working and removes the hr
 which means the "pictures" I guess. But the upload and the delete wont work, same for the checkbox.

Anyone could help me to make this work somehow ?

The problem could come from s3 ? or is it a script problem ? I never coded java so I don't really see where it could be a error in there.

If anyone can help or at least show me the way I would appreciate it.

Thanks

Body:
So... I tried for the last 6 hours to make this happen. I successfully installed Yarn and Webpack on my rails app. According to the installation instruction you can install everything via the gemfile without having to "rails new" again.

By default when I go on my browser I can see the message (javascript/application.js -> console.log('Hello World from Webpacker')).
Nevertheless I don't understand how everything is working even after reading this and this.
I tried the Refile Gem for my uploads. Everything works. I'd like (as my first post indicates) create a progress bar. I have a coffee script for that. I put my script in my_app/javascript/users.coffee and in application.js I wrote this :

require(users.coffee)

I have a error.
Then I tried to write this :

//= require refile
//= require popper
//= require bootstrap
//= jquery
//= require_tree .

And I have a error again.

Here is my coffee script :

jQuery ->
  $(document).on "upload:start", "form", (e) ->
    $(this).find("input[type=submit]").attr "disabled", true
    $("#progress-bar").slideDown('fast')

  $(document).on "upload:progress", "form", (e) ->
    detail          = e.originalEvent.detail
    percentComplete = Math.round(detail.loaded / detail.total * 100)
    $('.progress-bar').width("#{percentComplete}%");
    $("#progress-bar-text").text("#{percentComplete}% Complete")

  $(document).on "upload:success", "form", (e) ->
    $(this).find("input[type=submit]").removeAttr "disabled"  unless $(this).find("input.uploading").length
    $("#progress-bar").slideUp('fast')

By the way I changed to this my application.html.erb

<%= javascript_pack_tag 'application' %>

I also bin/yarn add refile and rails webpacker:compile

The result of my package.json :

{
  "name": "UploadRefile",
  "private": true,
  "dependencies": {
    "@rails/webpacker": "^3.0.2",
    "coffeescript": "1.12.7",
    "jquery": "^3.2.1",
    "refile": "^0.2.11"
  },
  "devDependencies": {
    "webpack-dev-server": "^2.9.5"
  }
}

Still not working.
I also tried to use decaffeinate to modify my coffee script. The result is this :

jQuery(function() {
  $(document).on("upload:start", "form", function(e) {
    $(this).find("input[type=submit]").attr("disabled", true);
    return $("#progress-bar").slideDown('fast');
  });

  $(document).on("upload:progress", "form", function(e) {
    const { detail }          = e.originalEvent;
    const percentComplete = Math.round((detail.loaded / detail.total) * 100);
    $('.progress-bar').width(`${percentComplete}%`);
    return $("#progress-bar-text").text(`${percentComplete}% Complete`);
  });

  return $(document).on("upload:success", "form", function(e) {
    if (!$(this).find("input.uploading").length) { $(this).find("input[type=submit]").removeAttr("disabled"); }
    return $("#progress-bar").slideUp('fast');
  });
});

Error again.

Anybody could lead me towards something ? Because I can't move forward really. I'm a patient guy but I don't understand the webpack process. The explanation are very confusing even if they say the opposit. I simply want to get a progress bar working. With carrierwave or with refile. Doesn't really matter.

Thanks for you help


问:
batch script: including filehandle %%i in DO (subfunction
I'm a bit stuck and need some advice.

I start by doing a FOR loop with %%i as the file variable.

```<code>for %%i in ("C:\*.*") do (
call :function1 "%%i"
goto function2
goto :eof
)
</code>```

the problem is that the file-parameter isn't given to function one..

I have tested with putting an 'echo my echo is %%' in function1 and i get:

```<code>my echo is %i
</code>```

And exacltle the same for the use of %%i in function2

Does anyone has advice for me?  How do i get the file handle to be taken to function in the DO form? By the way, this is windows batch.

答:
I actually found the source of my nightmares and it was pretty simple. The solution mentioned by belisarius was good but it did made the rest of my code unusable.

So on the the solution:

```<code>for %%i in ("C:\*.*") do (
call :function1 "%%~i"
call :function2 "%%~i"
</code>```

That's right! Damn brackets!! But that's a new lesson learnd ;)
Thanx for your time Belisarius

Body:
I'm a bit stuck and need some advice.

I start by doing a FOR loop with %%i as the file variable.

for %%i in ("C:\*.*") do (
call :function1 "%%i"
goto function2
goto :eof
)

the problem is that the file-parameter isn't given to function one..

I have tested with putting an 'echo my echo is %%' in function1 and i get:

my echo is %i

And exacltle the same for the use of %%i in function2

Does anyone has advice for me?  How do i get the file handle to be taken to function in the DO form? By the way, this is windows batch.

Body:
I actually found the source of my nightmares and it was pretty simple. The solution mentioned by belisarius was good but it did made the rest of my code unusable.

So on the the solution:

for %%i in ("C:\*.*") do (
call :function1 "%%~i"
call :function2 "%%~i"

That's right! Damn brackets!! But that's a new lesson learnd ;)
Thanx for your time Belisarius


问:
Teacher forcing with pytorch RNN
The pytorch tutorials do a great job of illustrating a bare-bones RNN by defining the input and hidden layers, and manually feeding the hidden layers back into the network to remember the state.  This flexibility then allows you to very easily perform teacher forcing.

Question 1: How do you perform teacher forcing when using the native nn.RNN() module (since the entire sequence is fed at once)?  Example simple RNN network would be:

```<code>class SimpleRNN(nn.Module):

    def __init__(self, vocab_size,
                 embedding_dim,
                 batch_sz,
                 hidden_size=128,
                 nlayers=1,
                 num_directions=1,
                 dropout=0.1):

        super(SimpleRNN, self).__init__()

        self.batch_sz = batch_sz
        self.hidden_size = hidden_size

        self.encoder = nn.Embedding(vocab_size, embedding_dim)
        self.rnn = nn.RNN(embedding_dim, hidden_size, nlayers, dropout=0.5)
        self.decoder = nn.Linear(hidden_size, vocab_size)

    def init_hidden(self):
        return autograd.Variable(torch.zeros(nlayers, batch_sz, hidden_size)).cuda()

    def forward(self, inputs, hidden):

        # -- encoder returns:
        # -- [batch_sz, seq_len, embed_dim]
        encoded = self.encoder(inputs)
        _, seq_len, _ = encoded.size()

        # -- rnn returns:
        # -- output.size() = [seq_len, batch_sz, hidden_sz]
        # -- hidden.size() = [nlayers, batch_sz, hidden_sz]
        output, hidden = self.rnn(encoded.view(seq_len, batch_sz, embedding_dim), hidden)

        # -- decoder returns:
        # -- output.size() = [batch_sz, seq_len, vocab_size]
        output = F.log_softmax(decoder(output.view(batch_sz, seq_len, self.hidden_size)))

        return output, hidden
</code>```

Where I can call the network with:

```<code>model = SimpleRNN(vocab_size, embedding_dim, batch_sz).cuda()
x_data, y_data = get_sequence_data(train_batches[0])
output, hidden = model(x_data, model.init_hidden())
</code>```

Just for completeness, here are my shapes of x_data,  output, and hidden:

```<code>print(x_data.size(), output.size(), hidden.size())
torch.Size([32, 80]) torch.Size([32, 80, 4773]) torch.Size([1, 32, 128])
</code>```

Question 2: would it be possible to use this SimpleRNN network to then generate a sequence word-by-word, by first feeding it a <GO_TOKEN> and iterating until an <END_TOKEN> is reached?  I ask because when I run this:

```<code>x_data = autograd.Variable(torch.LongTensor([[word2idx['<GO>']]]), volatile=True).cuda()
output, hidden = model(x_data, model.init_hidden(1))

print(output, output.sum())
</code>```

I get an output of all 0s, and the output.sum() = 0.  I get this even after training the network and backpropagating the loss.  Any ideas why?

Question 3: If not terribly inefficient, is it possible to train the SimpleRNN network above word-by-word, analogous to the pytorch tutorial shown (here)[http://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html] (albeit there they're training character-by-character).

答:
Question 1.

Teacher forcing is performed implicitly in this case, since your x_data is [seq_len, batch_size] it will feed in each item in seq_len as input and not use the actual output for the next input.

Question 2.

Your model.init_hidden does not take any input however it looks like you're trying to add the batch size in, maybe you could check that, everything else seems fine. Though you will need to do an max() or multinomial() on the output  before you can feed it back through.

Question 3.

Yes you can do this, yes it is terribly inefficient. This is a limitation of the CUDNN LSTM kernel

Title: Teacher forcing with pytorch RNN

Body:
The pytorch tutorials do a great job of illustrating a bare-bones RNN by defining the input and hidden layers, and manually feeding the hidden layers back into the network to remember the state.  This flexibility then allows you to very easily perform teacher forcing.

Question 1: How do you perform teacher forcing when using the native nn.RNN() module (since the entire sequence is fed at once)?  Example simple RNN network would be:

class SimpleRNN(nn.Module):

    def __init__(self, vocab_size,
                 embedding_dim,
                 batch_sz,
                 hidden_size=128,
                 nlayers=1,
                 num_directions=1,
                 dropout=0.1):

        super(SimpleRNN, self).__init__()

        self.batch_sz = batch_sz
        self.hidden_size = hidden_size

        self.encoder = nn.Embedding(vocab_size, embedding_dim)
        self.rnn = nn.RNN(embedding_dim, hidden_size, nlayers, dropout=0.5)
        self.decoder = nn.Linear(hidden_size, vocab_size)

    def init_hidden(self):
        return autograd.Variable(torch.zeros(nlayers, batch_sz, hidden_size)).cuda()

    def forward(self, inputs, hidden):

        # -- encoder returns:
        # -- [batch_sz, seq_len, embed_dim]
        encoded = self.encoder(inputs)
        _, seq_len, _ = encoded.size()

        # -- rnn returns:
        # -- output.size() = [seq_len, batch_sz, hidden_sz]
        # -- hidden.size() = [nlayers, batch_sz, hidden_sz]
        output, hidden = self.rnn(encoded.view(seq_len, batch_sz, embedding_dim), hidden)

        # -- decoder returns:
        # -- output.size() = [batch_sz, seq_len, vocab_size]
        output = F.log_softmax(decoder(output.view(batch_sz, seq_len, self.hidden_size)))

        return output, hidden

Where I can call the network with:

model = SimpleRNN(vocab_size, embedding_dim, batch_sz).cuda()
x_data, y_data = get_sequence_data(train_batches[0])
output, hidden = model(x_data, model.init_hidden())

Just for completeness, here are my shapes of x_data,  output, and hidden:

print(x_data.size(), output.size(), hidden.size())
torch.Size([32, 80]) torch.Size([32, 80, 4773]) torch.Size([1, 32, 128])

Question 2: would it be possible to use this SimpleRNN network to then generate a sequence word-by-word, by first feeding it a <GO_TOKEN> and iterating until an <END_TOKEN> is reached?  I ask because when I run this:

x_data = autograd.Variable(torch.LongTensor([[word2idx['<GO>']]]), volatile=True).cuda()
output, hidden = model(x_data, model.init_hidden(1))

print(output, output.sum())

I get an output of all 0s, and the output.sum() = 0.  I get this even after training the network and backpropagating the loss.  Any ideas why?

Question 3: If not terribly inefficient, is it possible to train the SimpleRNN network above word-by-word, analogous to the pytorch tutorial shown (here)[http://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html] (albeit there they're training character-by-character).


问:
Little trouble with css
Hello i have some issues with my code because animation won't work here's my code:

```<code>  background-image:url(industry2.jpg);
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  border:1px solid red;
  -webkit-animation: fadein 2s ease-in ;
  -moz-animation: fadein 2s ease-in ;
  animation: fadein 2s ease-in ;
  width:500px;
  height:200px;
  background-repeat: no-repeat;
  background-position: left top;
  padding-top:68px;
  position:absolute;
  top:2700px;
  left:1300px;

@keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
</code>```

you see i don't get animation working and i don't know what to do...

答:
You had not closed the @keyframes. I have removed the left and top position for visibility purpose.

.container {
  background-image: url("http://via.placeholder.com/500x200");
  background-size: cover;
  border: 1px solid red;
  animation: fadein 2s ease-in;
  width: 500px;
  height: 200px;
  background-repeat: no-repeat;
  background-position: left top;
  padding-top: 68px;
  position: absolute;
}

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">Hello</div></code>```

Title: Little trouble with css

Body:
Hello i have some issues with my code because animation won't work here's my code:

  background-image:url(industry2.jpg);
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  border:1px solid red;
  -webkit-animation: fadein 2s ease-in ;
  -moz-animation: fadein 2s ease-in ;
  animation: fadein 2s ease-in ;
  width:500px;
  height:200px;
  background-repeat: no-repeat;
  background-position: left top;
  padding-top:68px;
  position:absolute;
  top:2700px;
  left:1300px;

@keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }

you see i don't get animation working and i don't know what to do...

Body:
You had not closed the @keyframes. I have removed the left and top position for visibility purpose.

.container {
  background-image: url("http://via.placeholder.com/500x200");
  background-size: cover;
  border: 1px solid red;
  animation: fadein 2s ease-in;
  width: 500px;
  height: 200px;
  background-repeat: no-repeat;
  background-position: left top;
  padding-top: 68px;
  position: absolute;
}

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

<div class="container">Hello</div>


问:
Laravel Generate Migration from existing Model

How can I create migration file from existing model in Laravel or model from existing migration?
</p>

答:
```<code> php artisan make:migration create_users_table
</code>```

your Model name will be User and the table name will be users

ContentLicense: CC BY-SA 4.0

Body:
 php artisan make:migration create_users_table

your Model name will be User and the table name will be users


问:
Unable to download sdk components
Whenever I try to start android studio, I get this:

What should I do?

It doesn't download and just keeps repeating this!

答:
Refer: SO query

You can try the solution to avoid Downloading Components at startup so that AS launches and later on proceed manually.

To disable "Downloading Components" at startup,

Go to the installation directory of Android Studio. There you will
  find a folder named "bin". Inside this folder there is a file named
  "idea.properties". Open this file and add the following line to the
  end of the file:

disable.android.first.run=true What this will do is disable the check
  that Android Studio performs on first run and decides to download all
  that stuff.

If it asks to save the file at some different place instead of
  overwriting the original one, please check the access permissions to
  the file.

Title: Unable to download sdk components


问:
How to use transaction by sequelize in my node js
While converting legacy long sql procedure to sequelizer, I met trouble to make transaction to my async functions.

I read sequelizer's transaction documents.  But failed to understand clearly.

Here is my code.

```<code>const models = require('../models/models.js');
const sequelize = models.Sequelize;

async function isExistFeeHist(dansokSeqNo) {
  log.debug("isExistFeeHist()");
  let feeHist = await models.FeeHist.findOne({
    where: {
      DansokSeqNo: dansokSeqNo,
      FeeStatus: {[Op.ne]: null}, //is not null
      DelYN: false
    }
  });
  return !!feeHist;
}

async function isPaid(dansokSeqNo) {
  ...
}

async function getNextDansokHistSerialNo(dansokSeqNo) {
  ...
}

async function getVBankSeqNo(dansokSeqNo) {
  ...
}

async function updateVBankList(dansokSeqNo, vBankSeqNo) {
  ...
}

//check if can cancel
async function checkCancelable(dansokSeqNo) {
  log.debug("checkCancelable() ", dansokSeqNo);

  if (await isExistFeeHist(dansokSeqNo)) {
    let e = {status:400, message: 'already imposed dansokSeqNo ' + dansokSeqNo };
    return Promise.reject({status:400, message: e.message });
  }

  if (await isPaid(dansokSeqNo)) {
    let e = {status:400, message: 'already paid dansokSeqNo ' + dansokSeqNo };
    return Promise.reject({status:400, message: e.message });
  }

  return Promise.resolve();
}

....

async function doCancel(dansokSeqNo, cancelCauseCode, histMemo) {

  try {
    await checkCancelable(dansokSeqNo);

    //// <== Here I want to start transaction

    let nextDansokSerialNo =  await getNextDansokHistSerialNo(dansokSeqNo);
    let dansokHist = await insertNewDansokHist(dansokSeqNo, nextDansokSerialNo, cancelCauseCode, histMemo);
    await updateDansokHist(dansokSeqNo, cancelCauseCode);
    let vBankSeqNo = await getVBankSeqNo(dansokSeqNo);
    if (vBankSeqNo > 0) {
      await updateVBankList(dansokSeqNo, vBankSeqNo);
      let vBankList = await getVBankList(dansokSeqNo);
    }

    // <== Here I want to commit transaction
  } catch (e) {
    // <== Here I want to rollback transaction
    return Promise.reject({status:e.status, message: e.message });
  }
}

exports.cancelDansok = function (req, res) {
  res.setHeader("Content-Type", "application/json; charset=utf-8");
  ...
  jwtAcessAuth(accessToken)
  .then((decoded) => {
    log.info("jwt success, ", decoded);
    worker = decoded.loginName;
    return doCancel(dansokSeqNo, cancelCauseCode, histMemo);
  })
  .then(() => {
    res.status(200).json({ message: 'cancelDansok success.' });
  })
  .catch(e => {
    return res.status(e.status).json(e);
  });
};
</code>```

My function is assembled with several async functions.  And it need to bind one transaction.

What is the best practice to use transaction in my several async await functions?

答:
Here is the best example provided by Sequlize for Transaction :

All you need to care is pass transaction to next level of chaining

```<code>return sequelize.transaction(function (t) {

  // chain all your queries here. make sure you return them.
  return User.create({
    firstName: 'Abraham',
    lastName: 'Lincoln'
  }, {transaction: t}).then(function (user) {
    return user.setShooter({
      firstName: 'John',
      lastName: 'Boothe'
    }, {transaction: t});
  });

}).then(function (result) {
  // Transaction has been committed
  // result is whatever the result of the promise chain returned to the transaction callback
}).catch(function (err) {
  // Transaction has been rolled back
  // err is whatever rejected the promise chain returned to the transaction callback
});
</code>```

For more details : Transactions

Body:
While converting legacy long sql procedure to sequelizer, I met trouble to make transaction to my async functions.

I read sequelizer's transaction documents.  But failed to understand clearly.

Here is my code.

const models = require('../models/models.js');
const sequelize = models.Sequelize;

async function isExistFeeHist(dansokSeqNo) {
  log.debug("isExistFeeHist()");
  let feeHist = await models.FeeHist.findOne({
    where: {
      DansokSeqNo: dansokSeqNo,
      FeeStatus: {[Op.ne]: null}, //is not null
      DelYN: false
    }
  });
  return !!feeHist;
}

async function isPaid(dansokSeqNo) {
  ...
}

async function getNextDansokHistSerialNo(dansokSeqNo) {
  ...
}

async function getVBankSeqNo(dansokSeqNo) {
  ...
}

async function updateVBankList(dansokSeqNo, vBankSeqNo) {
  ...
}

//check if can cancel
async function checkCancelable(dansokSeqNo) {
  log.debug("checkCancelable() ", dansokSeqNo);

  if (await isExistFeeHist(dansokSeqNo)) {
    let e = {status:400, message: 'already imposed dansokSeqNo ' + dansokSeqNo };
    return Promise.reject({status:400, message: e.message });
  }

  if (await isPaid(dansokSeqNo)) {
    let e = {status:400, message: 'already paid dansokSeqNo ' + dansokSeqNo };
    return Promise.reject({status:400, message: e.message });
  }

  return Promise.resolve();
}

....

async function doCancel(dansokSeqNo, cancelCauseCode, histMemo) {

  try {
    await checkCancelable(dansokSeqNo);

    //// <== Here I want to start transaction

    let nextDansokSerialNo =  await getNextDansokHistSerialNo(dansokSeqNo);
    let dansokHist = await insertNewDansokHist(dansokSeqNo, nextDansokSerialNo, cancelCauseCode, histMemo);
    await updateDansokHist(dansokSeqNo, cancelCauseCode);
    let vBankSeqNo = await getVBankSeqNo(dansokSeqNo);
    if (vBankSeqNo > 0) {
      await updateVBankList(dansokSeqNo, vBankSeqNo);
      let vBankList = await getVBankList(dansokSeqNo);
    }

    // <== Here I want to commit transaction
  } catch (e) {
    // <== Here I want to rollback transaction
    return Promise.reject({status:e.status, message: e.message });
  }
}

exports.cancelDansok = function (req, res) {
  res.setHeader("Content-Type", "application/json; charset=utf-8");
  ...
  jwtAcessAuth(accessToken)
  .then((decoded) => {
    log.info("jwt success, ", decoded);
    worker = decoded.loginName;
    return doCancel(dansokSeqNo, cancelCauseCode, histMemo);
  })
  .then(() => {
    res.status(200).json({ message: 'cancelDansok success.' });
  })
  .catch(e => {
    return res.status(e.status).json(e);
  });
};

My function is assembled with several async functions.  And it need to bind one transaction.

What is the best practice to use transaction in my several async await functions?

Body:
Here is the best example provided by Sequlize for Transaction :

All you need to care is pass transaction to next level of chaining

return sequelize.transaction(function (t) {

  // chain all your queries here. make sure you return them.
  return User.create({
    firstName: 'Abraham',
    lastName: 'Lincoln'
  }, {transaction: t}).then(function (user) {
    return user.setShooter({
      firstName: 'John',
      lastName: 'Boothe'
    }, {transaction: t});
  });

}).then(function (result) {
  // Transaction has been committed
  // result is whatever the result of the promise chain returned to the transaction callback
}).catch(function (err) {
  // Transaction has been rolled back
  // err is whatever rejected the promise chain returned to the transaction callback
});

For more details : Transactions


问:
change mysql default engine to innodb
I am using mac and I installed mysql using homebrew.

```<code>brew install mysql
</code>```

pretty standard installation.

```<code>mysql> show engines;
+------------+---------+------------------------------------------------------------+--------------+------+------------+
| Engine     | Support | Comment                                                    | Transactions | XA   | Savepoints |
+------------+---------+------------------------------------------------------------+--------------+------+------------+
| MRG_MYISAM | YES     | Collection of identical MyISAM tables                      | NO           | NO   | NO         |
| CSV        | YES     | CSV storage engine                                         | NO           | NO   | NO         |
| MyISAM     | DEFAULT | Default engine as of MySQL 3.23 with great performance     | NO           | NO   | NO         |
| InnoDB     | YES     | Supports transactions, row-level locking, and foreign keys | YES          | YES  | YES        |
| MEMORY     | YES     | Hash based, stored in memory, useful for temporary tables  | NO           | NO   | NO         |
+------------+---------+------------------------------------------------------------+--------------+------+------------+
</code>```

I would like innodb to be the default storage engine. What do I need to do?

答:
Under [mysqld] section in your ini file, add:

```<code>default-storage-engine = innodb
</code>```

It is usually /etc/my.cnf, but not sure about Mac.

From the docs:

On Unix, Linux and Mac OS X, MySQL programs read startup options from the following files, in the specified order (top items are used first).

```<code>File Name   Purpose

/etc/my.cnf          Global options
/etc/mysql/my.cnf    Global options (as of MySQL 5.1.15)
SYSCONFDIR/my.cnf    Global options
$MYSQL_HOME/my.cnf   Server-specific options
defaults-extra-file  The file specified with --defaults-extra-file=path, if any
~/.my.cnf            User-specific options
</code>```

The last one is never used by the daemon.

Title: change mysql default engine to innodb

Body:
I am using mac and I installed mysql using homebrew.

brew install mysql

pretty standard installation.

mysql> show engines;
+------------+---------+------------------------------------------------------------+--------------+------+------------+
| Engine     | Support | Comment                                                    | Transactions | XA   | Savepoints |
+------------+---------+------------------------------------------------------------+--------------+------+------------+
| MRG_MYISAM | YES     | Collection of identical MyISAM tables                      | NO           | NO   | NO         |
| CSV        | YES     | CSV storage engine                                         | NO           | NO   | NO         |
| MyISAM     | DEFAULT | Default engine as of MySQL 3.23 with great performance     | NO           | NO   | NO         |
| InnoDB     | YES     | Supports transactions, row-level locking, and foreign keys | YES          | YES  | YES        |
| MEMORY     | YES     | Hash based, stored in memory, useful for temporary tables  | NO           | NO   | NO         |
+------------+---------+------------------------------------------------------------+--------------+------+------------+

I would like innodb to be the default storage engine. What do I need to do?

Body:
Under [mysqld] section in your ini file, add:

default-storage-engine = innodb

It is usually /etc/my.cnf, but not sure about Mac.

From the docs:

On Unix, Linux and Mac OS X, MySQL programs read startup options from the following files, in the specified order (top items are used first).

File Name   Purpose

/etc/my.cnf          Global options
/etc/mysql/my.cnf    Global options (as of MySQL 5.1.15)
SYSCONFDIR/my.cnf    Global options
$MYSQL_HOME/my.cnf   Server-specific options
defaults-extra-file  The file specified with --defaults-extra-file=path, if any
~/.my.cnf            User-specific options

The last one is never used by the daemon.


问:
Laravel 5 make routing with unique parameter
I am currently using a route with a parameter nameto query the profile of a user in my application.

So for example: /members/johnwill show the profile of John.

You see the problem here, if there are 2 John's then it's gonna be a problem.

I know I could do something like this /members/idsince id is unique but I want the url to look pretty with the user's name and not a random number.

So my question is if there is a way to use the id to make it unique but to display the name in url?

my route:

```<code>Route::get('/members/{name}', 'UserController@usersProfile');
</code>```

My usersProfile method:

```<code>/**
 * Returns a users profile.
 *
 * @param string $name
 *
 * @return \Illuminate\Http\Response
 */
public function usersProfile($name)
{
    $profile = $this->userService->getProfile($name);

    if ($profile == null) {
        return redirect('members')->with('status', 'Whoops, looks like that member does not exist (yet).');
    }

    return view('members/profile', ['profile' => $profile]);
}
</code>```

答:
You should add another column to your user table with name 'slug' or 'username' and map that column in your route.

In your users model, make a static function to generate unique slug with a number attached and save it in that new column to provide users with public/private profile URLs.

This below sample will stop returning slug/username after 100 users with the same name.

```<code>public static function getUniqueSlug($name) {
  $original_slug = getSlug($name); // Default getter to get value in model
  $slug = str_slug($original_slug); //Convert a string into url friendly string with hyphens

  while(true) {
    $count = User::where('slug', $slug)->count();
    if($count > 0) {
      $slug = $original_slug."-".rand(1,99);
    } else {
      return $slug;
    }
  }
}
</code>```

Body:
I am currently using a route with a parameter nameto query the profile of a user in my application.

So for example: /members/johnwill show the profile of John.

You see the problem here, if there are 2 John's then it's gonna be a problem.

I know I could do something like this /members/idsince id is unique but I want the url to look pretty with the user's name and not a random number.

So my question is if there is a way to use the id to make it unique but to display the name in url?

my route:

Route::get('/members/{name}', 'UserController@usersProfile');

My usersProfile method:

/**
 * Returns a users profile.
 *
 * @param string $name
 *
 * @return \Illuminate\Http\Response
 */
public function usersProfile($name)
{
    $profile = $this->userService->getProfile($name);

    if ($profile == null) {
        return redirect('members')->with('status', 'Whoops, looks like that member does not exist (yet).');
    }

    return view('members/profile', ['profile' => $profile]);
}

Body:
You should add another column to your user table with name 'slug' or 'username' and map that column in your route.

In your users model, make a static function to generate unique slug with a number attached and save it in that new column to provide users with public/private profile URLs.

This below sample will stop returning slug/username after 100 users with the same name.

public static function getUniqueSlug($name) {
  $original_slug = getSlug($name); // Default getter to get value in model
  $slug = str_slug($original_slug); //Convert a string into url friendly string with hyphens

  while(true) {
    $count = User::where('slug', $slug)->count();
    if($count > 0) {
      $slug = $original_slug."-".rand(1,99);
    } else {
      return $slug;
    }
  }
}


问:
Insert returns error: (sub-select returns 6 columns - expected 1)
I have a table SIGHTINGS(NAME, PERSON, LOCATION, SIGHTED), and I'm trying to insert a new row into that table with the following query:

```<code>INSERT INTO SIGHTINGS (NAME, PERSON, LOCATION, SIGHTED)
VALUES ('Douglas dustymaiden', 'Person B', 'Double Mountain', '2005-11-28');
</code>```

But it's returning this error:

```<code>[2017-12-04 17:08:18] [1] [SQLITE_ERROR] SQL error or missing database (sub-select returns 6 columns - expected 1)
</code>```

I've looked up the correct syntax for sqlite inserts here, and from what I can tell, the insert is written correctly. Can someone tell me why it's throwing this error instead of doing the insert? I'm using DataGrip 2017 if that helps identify any issues.

EDIT:

Here's the trigger I added to the database. The insert works without the trigger.

```<code>CREATE TRIGGER SightingLocationError
  BEFORE INSERT ON SIGHTINGS
  FOR EACH ROW
  WHEN NEW.LOCATION NOT IN FEATURES
BEGIN
  SELECT RAISE(ABORT, 'Error: Insert into the SIGHTINGS table references location that is not found in the database.');
END;
</code>```

答:
```<code>WHEN NEW.LOCATION NOT IN FEATURES
</code>```

The FEATURES table has six columns, so the database does not know how it should search for the location value.

Use an explicit subquery to return the column you want to use for this:

```<code>WHEN NEW.LOCATION NOT IN (SELECT xxx FROM FEATURES)
</code>```

Body:
I have a table SIGHTINGS(NAME, PERSON, LOCATION, SIGHTED), and I'm trying to insert a new row into that table with the following query:

INSERT INTO SIGHTINGS (NAME, PERSON, LOCATION, SIGHTED)
VALUES ('Douglas dustymaiden', 'Person B', 'Double Mountain', '2005-11-28');

But it's returning this error:

[2017-12-04 17:08:18] [1] [SQLITE_ERROR] SQL error or missing database (sub-select returns 6 columns - expected 1)

I've looked up the correct syntax for sqlite inserts here, and from what I can tell, the insert is written correctly. Can someone tell me why it's throwing this error instead of doing the insert? I'm using DataGrip 2017 if that helps identify any issues.

EDIT:

Here's the trigger I added to the database. The insert works without the trigger.

CREATE TRIGGER SightingLocationError
  BEFORE INSERT ON SIGHTINGS
  FOR EACH ROW
  WHEN NEW.LOCATION NOT IN FEATURES
BEGIN
  SELECT RAISE(ABORT, 'Error: Insert into the SIGHTINGS table references location that is not found in the database.');
END;

Body:
WHEN NEW.LOCATION NOT IN FEATURES

The FEATURES table has six columns, so the database does not know how it should search for the location value.

Use an explicit subquery to return the column you want to use for this:

WHEN NEW.LOCATION NOT IN (SELECT xxx FROM FEATURES)


问:
How can I separate Perl variables from text in interpolated strings?
Consider:

```<code>print "    $foo", "AAAAAAAA", $foo, "BBBBBBBB";
</code>```

Let's say I want to use this code with a print <<EOF;:

```<code>print <<EOF;
    $fooAAAAAAAA$fooBBBBBBBB";
EOF
</code>```

That won't work, because Perl thinks I have a variable called $fooAAAAAAAA. How can I easily use print << with such lines when I have a long test to print?

答:
And another answer, based on non interpolated strings, which I think is the most appropriate.

```<code>print <<'EOF';
    $fooAAAAAAAA$fooBBBBBBBB";
EOF
</code>```

http://perldoc.perl.org/perlop.html#Quote-Like-Operators

OwnerDisplayName: Julien

Body:
Consider:

print "    $foo", "AAAAAAAA", $foo, "BBBBBBBB";

Let's say I want to use this code with a print <<EOF;:

print <<EOF;
    $fooAAAAAAAA$fooBBBBBBBB";
EOF

That won't work, because Perl thinks I have a variable called $fooAAAAAAAA. How can I easily use print << with such lines when I have a long test to print?

LastEditorDisplayName: brian d foy

Body:
And another answer, based on non interpolated strings, which I think is the most appropriate.

print <<'EOF';
    $fooAAAAAAAA$fooBBBBBBBB";
EOF

http://perldoc.perl.org/perlop.html#Quote-Like-Operators


问:
How Can I Correctly Implement Change Directory Support in Java 8+?
I am writing a script-interpreter/shell and I need change directory support to do this effectively.

As of right now, I am using a File object reference as my current directory, and resolving all relative paths using that file object. This works, but the problem is that every file reference the interpreter makes use of will have an absolute path. This doesn't work so well for things like getting a relative URI or when an error happens, the error messages won't reflect the path that was supplied to the script engine, and this will make script debugging very "non-intuitive" (a correct error message is verbatim with respect to its errant inputs).

If it's not possible to change the current directory, Java's File Object is basically OBSOLETE. Of course, if java would let me specify what my current directory is on the file objects this wouldn't be an issue, but I don't know of a way to do that except to extend the File class with such feature support.

To further compound the LOGICAL-FALLACY of this lack of correct feature support, I am basically facing the same problems with running a process using the process builder.

I am aware that I am already "getting it done", but it is very important to my project that i "get it done CORRECTLY" which means TRANSPARENTLY.

I have seen stack-overflow-answers which say: modify the system property: user.dir, but that is flat out wrong and doesn't work with my JVM.

I don't care at all what the JVM specs say I should or shouldn't do in this particular case (because I don't subscribe to logical fallacies), I just want to change the current directory in a cross-platform-compatible-way. Every major operating system supports the feature but Java doesn't? (HORSERADISH!)

How Can I Correctly Implement Change Directory Support in Java 8+?

After a little digging, I figured it out! This is not possible. Apparently, the JDK team back in the day couldn't understand the concept of current directory (WHICH HAS NOTHING TO DO WITH CHANGING THE CURRENT DIRECTORY OF OTHER PROCESSES AND THREADS).

For all intents and purposes, change directory is for the currently executing thread (process), and all future RELATIVE file system access operations, from within that thread or its children (quote-this). Some operating systems and maybe even all specifcations may have a different notion of its effect, but this reasoning (quote-that) is what change directory does from the perspective of the end user. Being completely system compatible is not the use case for change directory, but how each future file operation IS affected IS the use case hence the word: CHANGE.

Java is basically a system emulation layer, and all Filesystem IO operations are bound within that layer. Neglecting to provide change directory emulation was, and always will be Java's biggest failure in foresight, until they decide to neglect some other pertinent system standard.

I am no stranger to writing emulation layers. It is not about the underlying implementation. That is a core unix philosphy principle. It IS about providing the capability to get the job done. That being said, it is not impossible or diffficult to implement a JDK change directory feature, from the JDK side of development.

If you look at my answer, its as simple as providing a thread safe static variable, which all file operations will access in the case of a relative path. UBER FAIL.

答:
So here is my "example" which provides limited support. I don't accept this as the answer because it does not fix all of the issues. Stream IO for example. But for lightweight projects which only need java.io.File support for changing the current directory with correct error outputs, this SHOULD do.

I say that it should do, because I have not tested it. This code is not complete. I have never worked with file filters in java, so I have no idea how to patch those entry points. The methods are marked deprecated and will throw unsupported operation exceptions if called.

Using this tool, you can set and get your current directory value, and all of your file methods will work with the path you supplied, unless there is a disk access; in that case, it will fallback to the path of the real file. If an exception is raised, the code will attempt (again, not tested) to rectify the error message with the path you supplied.

The people at java really screwed up on this one, undoubtedly; you basically have to patch/hack/mock the entire Java IO Platform just to enable support for changing directories. That my friends is what we call a serious case of neglect; an amatuer coding mistake. There is no coder on this earth worth his salt, who thinks it would be a smart idea to abrogate a computing coding standard older than he or she is, when there is no problem with that standard to begin with.

A disk operating system, with no change directory? You're pretty lucky you don't work for me. You would be getting your termination papers in the mail. Because I would be ready to strangle you if you walked into my office with a "fix" like this=(no change directory support) for something that isn't broken.

```<code>import java.io.*;
import java.net.URI;
import java.nio.file.Path;

public class HSFile extends java.io.File {

  /*
    For this class to work as intended, we need to intervene in any
    method which transposes the file's name, accesses the disk,
    or throws exceptions.
  */

  private final File realFile;
  private final String realDirectory;

  public static String getCurrentDirectory() {
    return currentDirectory.getPath();
  }

  public static void setCurrentDirectory(String currentDirectory) throws
    FileNotFoundException {
    File target = new File(currentDirectory);
    if (! target.exists() )
      throw new FileNotFoundException("target directory: `"+target+"'; does not exist");
    if (! target.isDirectory())
      throw new UnsupportedOperationException("target directory: `"+target+"'; is not a directory");
    HSFile.currentDirectory = target;
  }

  /**
   * The global current directory property
   */
  private static java.io.File currentDirectory =
    new File(java.lang.System.getProperty("user.dir"));

  public File getRealFile() {
    if (realFile != null) return realFile;
    if (! isAbsolute()) return new File(getCurrentDirectory(), getPath());
    return new File(this.getPath());
  }

  public String getRealPath() { return realFile.getPath(); }

  public HSFile(String s) {
    super(s);
    realFile = getRealFile();
    if (! isAbsolute()) {
      realDirectory = getCurrentDirectory() + File.separator;
    } else realDirectory = realFile.getParent() + File.separator;
  }

  public HSFile(String s, String s1) {
    super(s, s1);
    realFile = getRealFile();
    realDirectory = s + File.separator;
  }

  public HSFile(File file, String s) {
    super(file, s);
    realFile = getRealFile();
    realDirectory = file.getPath() + File.separator;
  }

  public HSFile(URI uri) {
    super(uri);
    realFile = getRealFile();
    if (! isAbsolute()) {
      realDirectory = getCurrentDirectory() + File.separator;
    } else realDirectory = realFile.getParent() + File.separator;
  }

  @Override
  public boolean canRead() {
    return realFile.canRead();
  }

  @Override
  public boolean canWrite() {
    return realFile.canWrite();
  }

  @Override
  public boolean exists() {return realFile.exists();}

  @Override
  public boolean isDirectory() {return realFile.isDirectory();}

  @Override
  public boolean isFile() {return realFile.isFile();}

  @Override
  public boolean isHidden() {return realFile.isHidden();}

  @Override
  public long lastModified() {return realFile.lastModified();}

  @Override
  public long length() {return realFile.length();}

  @Override
  public boolean createNewFile() throws IOException {
    return realFile.createNewFile();
  }

  @Override
  public boolean delete() {return realFile.delete();}

  @Override
  public void deleteOnExit() {realFile.deleteOnExit();}

  @Override
  public boolean mkdir() {return realFile.mkdir();}

  @Override
  public boolean mkdirs() {return realFile.mkdirs();}

  @Override
  public boolean setLastModified(long l) {return realFile.setLastModified(l);}

  @Override
  public boolean setWritable(boolean b, boolean b1) {
    return realFile.setWritable(b, b1);
  }

  @Override
  public boolean setWritable(boolean b) {return realFile.setWritable(b);}

  @Override
  public boolean setReadable(boolean b, boolean b1) {
    return realFile.setReadable(b, b1);
  }

  @Override
  public boolean setReadable(boolean b) {return realFile.setReadable(b);}

  @Override
  public boolean setExecutable(boolean b, boolean b1) {
    return realFile.setExecutable(b, b1);
  }

  @Override
  public boolean setExecutable(boolean b) {return realFile.setExecutable(b);}

  @Override
  public boolean canExecute() {
    return realFile.canExecute();
  }

  @Override
  public long getTotalSpace() {return realFile.getTotalSpace();}

  @Override
  public long getFreeSpace() {return realFile.getFreeSpace();}

  @Override
  public long getUsableSpace() {return realFile.getUsableSpace();}

  @Override
  public String getAbsolutePath() {
    return realFile.getAbsolutePath();
  }

  @Override
  public HSFile getAbsoluteFile() {
    return new HSFile(getAbsolutePath());
  }

  @Override
  public String getCanonicalPath() throws IOException {
    return realFile.getCanonicalPath();
  }

  @Override
  public HSFile getCanonicalFile() throws IOException {
    return new HSFile(realFile.getCanonicalPath());
  }

  @Override
  public boolean setReadOnly() {
    return realFile.setReadOnly();
  }

  @Override
  public Path toPath() {
    return realFile.toPath();
  }

  @Override
  public HSFile getParentFile() {
    return new HSFile(getParent());
  }

  @Override
  public boolean renameTo(File file) {
    HSFile target = file instanceof HSFile ?
      (HSFile)file : new HSFile(file.getPath());
    return realFile.renameTo(target.realFile);
  }

  @Override
  public int compareTo(File file) {
    HSFile target = file instanceof HSFile ?
      (HSFile)file : new HSFile(file.getPath());
    return realFile.compareTo(target.realFile);
  }

  @Override
  public String[] list() {return  realFile.list();}

  @Override
  public HSFile[] listFiles() {
    File[] files = realFile.listFiles();
    if (files == null) return null;
    HSFile[] xFiles = new HSFile[files.length];
    int item;
    for (item = 0; item < files.length; item++)
      xFiles[item] = new HSFile(files[item].getPath());
    return xFiles;
  }

  @Override @Deprecated
  public HSFile[] listFiles(FilenameFilter filenameFilter) {
    // fill this in if you need it
    throw new UnsupportedOperationException("this operation is beyond the scope of this class");
  }

  @Override @Deprecated
  public String[] list(FilenameFilter filenameFilter) {
    // fill this in if you need it
    throw new UnsupportedOperationException("this operation is beyond the scope of this class");
  }

  @Override @Deprecated
  public HSFile[] listFiles(FileFilter fileFilter) {
    // fill this in if you need it
    throw new UnsupportedOperationException("this operation is beyond the scope of this class");
  }

}
</code>```

--UPDATE--
The current directory for each file must be cached, or subsequent changes will refrence the wrong file path. It is unknown at this time, if the error message fixes will be viable in their current state.

I have removed the file name changing in the errors. So that this example reflects only change current directory support. The package name is also nixed.

Body:
So here is my "example" which provides limited support. I don't accept this as the answer because it does not fix all of the issues. Stream IO for example. But for lightweight projects which only need java.io.File support for changing the current directory with correct error outputs, this SHOULD do.

I say that it should do, because I have not tested it. This code is not complete. I have never worked with file filters in java, so I have no idea how to patch those entry points. The methods are marked deprecated and will throw unsupported operation exceptions if called.

Using this tool, you can set and get your current directory value, and all of your file methods will work with the path you supplied, unless there is a disk access; in that case, it will fallback to the path of the real file. If an exception is raised, the code will attempt (again, not tested) to rectify the error message with the path you supplied.

The people at java really screwed up on this one, undoubtedly; you basically have to patch/hack/mock the entire Java IO Platform just to enable support for changing directories. That my friends is what we call a serious case of neglect; an amatuer coding mistake. There is no coder on this earth worth his salt, who thinks it would be a smart idea to abrogate a computing coding standard older than he or she is, when there is no problem with that standard to begin with.

A disk operating system, with no change directory? You're pretty lucky you don't work for me. You would be getting your termination papers in the mail. Because I would be ready to strangle you if you walked into my office with a "fix" like this=(no change directory support) for something that isn't broken.

import java.io.*;
import java.net.URI;
import java.nio.file.Path;

public class HSFile extends java.io.File {

  /*
    For this class to work as intended, we need to intervene in any
    method which transposes the file's name, accesses the disk,
    or throws exceptions.
  */

  private final File realFile;
  private final String realDirectory;

  public static String getCurrentDirectory() {
    return currentDirectory.getPath();
  }

  public static void setCurrentDirectory(String currentDirectory) throws
    FileNotFoundException {
    File target = new File(currentDirectory);
    if (! target.exists() )
      throw new FileNotFoundException("target directory: `"+target+"'; does not exist");
    if (! target.isDirectory())
      throw new UnsupportedOperationException("target directory: `"+target+"'; is not a directory");
    HSFile.currentDirectory = target;
  }

  /**
   * The global current directory property
   */
  private static java.io.File currentDirectory =
    new File(java.lang.System.getProperty("user.dir"));

  public File getRealFile() {
    if (realFile != null) return realFile;
    if (! isAbsolute()) return new File(getCurrentDirectory(), getPath());
    return new File(this.getPath());
  }

  public String getRealPath() { return realFile.getPath(); }

  public HSFile(String s) {
    super(s);
    realFile = getRealFile();
    if (! isAbsolute()) {
      realDirectory = getCurrentDirectory() + File.separator;
    } else realDirectory = realFile.getParent() + File.separator;
  }

  public HSFile(String s, String s1) {
    super(s, s1);
    realFile = getRealFile();
    realDirectory = s + File.separator;
  }

  public HSFile(File file, String s) {
    super(file, s);
    realFile = getRealFile();
    realDirectory = file.getPath() + File.separator;
  }

  public HSFile(URI uri) {
    super(uri);
    realFile = getRealFile();
    if (! isAbsolute()) {
      realDirectory = getCurrentDirectory() + File.separator;
    } else realDirectory = realFile.getParent() + File.separator;
  }

  @Override
  public boolean canRead() {
    return realFile.canRead();
  }

  @Override
  public boolean canWrite() {
    return realFile.canWrite();
  }

  @Override
  public boolean exists() {return realFile.exists();}

  @Override
  public boolean isDirectory() {return realFile.isDirectory();}

  @Override
  public boolean isFile() {return realFile.isFile();}

  @Override
  public boolean isHidden() {return realFile.isHidden();}

  @Override
  public long lastModified() {return realFile.lastModified();}

  @Override
  public long length() {return realFile.length();}

  @Override
  public boolean createNewFile() throws IOException {
    return realFile.createNewFile();
  }

  @Override
  public boolean delete() {return realFile.delete();}

  @Override
  public void deleteOnExit() {realFile.deleteOnExit();}

  @Override
  public boolean mkdir() {return realFile.mkdir();}

  @Override
  public boolean mkdirs() {return realFile.mkdirs();}

  @Override
  public boolean setLastModified(long l) {return realFile.setLastModified(l);}

  @Override
  public boolean setWritable(boolean b, boolean b1) {
    return realFile.setWritable(b, b1);
  }

  @Override
  public boolean setWritable(boolean b) {return realFile.setWritable(b);}

  @Override
  public boolean setReadable(boolean b, boolean b1) {
    return realFile.setReadable(b, b1);
  }

  @Override
  public boolean setReadable(boolean b) {return realFile.setReadable(b);}

  @Override
  public boolean setExecutable(boolean b, boolean b1) {
    return realFile.setExecutable(b, b1);
  }

  @Override
  public boolean setExecutable(boolean b) {return realFile.setExecutable(b);}

  @Override
  public boolean canExecute() {
    return realFile.canExecute();
  }

  @Override
  public long getTotalSpace() {return realFile.getTotalSpace();}

  @Override
  public long getFreeSpace() {return realFile.getFreeSpace();}

  @Override
  public long getUsableSpace() {return realFile.getUsableSpace();}

  @Override
  public String getAbsolutePath() {
    return realFile.getAbsolutePath();
  }

  @Override
  public HSFile getAbsoluteFile() {
    return new HSFile(getAbsolutePath());
  }

  @Override
  public String getCanonicalPath() throws IOException {
    return realFile.getCanonicalPath();
  }

  @Override
  public HSFile getCanonicalFile() throws IOException {
    return new HSFile(realFile.getCanonicalPath());
  }

  @Override
  public boolean setReadOnly() {
    return realFile.setReadOnly();
  }

  @Override
  public Path toPath() {
    return realFile.toPath();
  }

  @Override
  public HSFile getParentFile() {
    return new HSFile(getParent());
  }

  @Override
  public boolean renameTo(File file) {
    HSFile target = file instanceof HSFile ?
      (HSFile)file : new HSFile(file.getPath());
    return realFile.renameTo(target.realFile);
  }

  @Override
  public int compareTo(File file) {
    HSFile target = file instanceof HSFile ?
      (HSFile)file : new HSFile(file.getPath());
    return realFile.compareTo(target.realFile);
  }

  @Override
  public String[] list() {return  realFile.list();}

  @Override
  public HSFile[] listFiles() {
    File[] files = realFile.listFiles();
    if (files == null) return null;
    HSFile[] xFiles = new HSFile[files.length];
    int item;
    for (item = 0; item < files.length; item++)
      xFiles[item] = new HSFile(files[item].getPath());
    return xFiles;
  }

  @Override @Deprecated
  public HSFile[] listFiles(FilenameFilter filenameFilter) {
    // fill this in if you need it
    throw new UnsupportedOperationException("this operation is beyond the scope of this class");
  }

  @Override @Deprecated
  public String[] list(FilenameFilter filenameFilter) {
    // fill this in if you need it
    throw new UnsupportedOperationException("this operation is beyond the scope of this class");
  }

  @Override @Deprecated
  public HSFile[] listFiles(FileFilter fileFilter) {
    // fill this in if you need it
    throw new UnsupportedOperationException("this operation is beyond the scope of this class");
  }

}

--UPDATE--
The current directory for each file must be cached, or subsequent changes will refrence the wrong file path. It is unknown at this time, if the error message fixes will be viable in their current state.

I have removed the file name changing in the errors. So that this example reflects only change current directory support. The package name is also nixed.


问:
Idiomatic Gradle script to build 'debug' and 'release' JAR files
I'm trying to create a Gradle build script that will build a Java .jar file in 'release' or 'debug' modes and am having trouble parametrizing the script.

The question is: What is an idiomatic way to do this in a Gradle script, using the Java plugin?
(or, if there's no idiomatic way, what's a hacky solution that actually works?)

I don't mind the method of parametrization, just as long as the command-line and IDE invocations can easily choose between the two output options. The jar file will be used as a library in other projects, e.g. an Android app and a JavaFX app, so I would like the method of parametrization to be invokable/depended-on from their own Gradle scripts.

Ideally I'd like to 'emulate' the Android gradle plugin's ability to have a Debug/Release version of every task, i.e.

```<code>$ ./gradlew build
$ ./gradlew assembleRelease
$ ./gradlew checkDebug
</code>```

but failing that even a top level buildDebug and buildRelease would be suitable.

Stuff I tried

This section isn't really relevant to the question.

Starting point

I have the following gradle file/project:

```<code>group 'TestGradleProjectGroup'
apply plugin: 'java'
sourceCompatibility = 1.8

version '1.0-release'
compileJava {
    options.debug = false
}

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
}
</code>```

This works fine and produces the jar file:

```<code>$ ls TestGradleModule/build/libs/
TestGradleModule-1.0-release.jar
</code>```

which, when the extracted classes are inspected with javap, doesn't contain any debug information. Hurrah. No we need a way to make a debug version.

Add debug & release tasks

```<code>version '1.0-release'
compileJava {
    options.debug = false
}

task buildRelease(type: GradleBuild, dependsOn: build) {
    project.version = '1.0-release'
    compileJava {
        options.debug = false
    }
}

task buildDebug(type: GradleBuild, dependsOn: build) {
    project.version = '1.0-debug'
    compileJava {
        options.debug = true
    }
}
</code>```

This didn't work, as the debug project is always built, even if buildRelease is the task given on the command line. I guess this is because the code for both tasks is run at Configuration time (Gradle build lifecycle), whereas I only want one to run. So I guess I want to run them at Execution time?

Add some doLast tasks

```<code>version '1.0-release'
compileJava {
    options.debug = false
}

task buildRelease(type: GradleBuild, dependsOn: build) {
    doLast {
        project.version = '1.0-release'
        compileJava {
            options.debug = false

        }
    }
}

task buildDebug(type: GradleBuild, dependsOn: build) {
    doLast {
        project.version = '1.0-debug'
        compileJava {
            options.debug = true
        }
    }
}
</code>```

This is even worse. The output file is always 1.0-release, and that's because of the 'default' at the top level. If I comment that out then a versioned jar is not made, instead the default of TestGradleModule.jar is made. It seems that the contents of the doLast blocks are completely useless in their effect upon the compileJava task (but there's no warning about this?). I guess these modifications are too late to be done at execution time, or that there's something else that needs to be done so that the compileJava tasks is "configured" differently?

Using Configurations?

I noticed the manual for the Java plugin contained a reference to buildConfigName and uploadConfigName, and claimed they depend on "The tasks which produce the artifacts in configuration ConfigName.". Given that I was failing to parametrize stuff at Configuration time, the plugin's ability to do that looked promising:

```<code>group 'TestGradleProjectGroup'
apply plugin: 'java'
sourceCompatibility = 1.8

configurations {
    debug
    release
}

version '1.0-release'
compileJava {
    options.debug = false
}

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
}
</code>```

but:

This didn't add buildRelease or buildDebug to the output of ./gradlew tasks --all, as I expected it to. But I could run those tasks.

It only seemed to make buildRelease and buildDebug, not e.g. assembleRelease etc

buildRelease didn't seem to depend on anything when run so therefore had no useful effect.

Iterating tasks?

As a final attempt I've tried to create all of the appropriate tasks and linking the dependencies for everything. I tried iterating over the tasks and adding the dependencies:

```<code>gradle.taskGraph.whenReady { taskGraph ->

    taskGraph.allTasks.each { taskIter ->

        println("iterating" + taskIter)

        def releaseTask = project.task(taskIter.name + "Release")
        def debugTask = project.task(taskIter.name + "Debug")

        taskIter.dependsOn += [releaseTask, debugTask].toSet()
        println("new taskIter.dependsOn:" + taskIter.dependsOn)

        /*
            set debug mode here,
            copy over effects of task to debug/release
            disable effects of task
        */
    }
}
</code>```

but

This didn't seem to create the tasks properly, they weren't accessible from the command line and running "build" didn't run "buildRelease" etc.

I would also have to "move" all of the "actions" from the current, existing tasks and into the debug and release tasks, to avoid duplicating the effects of each. And I don't know how to do that.

In short, I have no idea what I'm doing. As a last resort I could just create all of the tasks manually, but that seems to defeat the point of using the the java plugin and is very spammy?

答:
Your question is detailed since you made a deep analysis of the problem. Although I believe that this issue could be solved if you would think in simpler way.

So if we think simple, a possible solution to your case is to run the debug task after the release is finalized. See the example below:

```<code>compileJava {
    options.debug = false
}

task buildRelease(type: GradleBuild, dependsOn: build) {
    doLast {
        project.version = '1.0-release'
        compileJava {
            options.debug = false

        }
    }
}

task buildDebug(type: GradleBuild, dependsOn: build) {
    doLast {
        project.version = '1.0-debug'
        compileJava {
            options.debug = true
        }
    }
}

// Here you are telling the buildDebug task to be executed right after the
// buildRelease task is finalized.
buildDebug.mustRunAfter buildRelease
</code>```

In the above way you control the order of the task execution without introducing an explicit dependency between them.

Body:
I'm trying to create a Gradle build script that will build a Java .jar file in 'release' or 'debug' modes and am having trouble parametrizing the script.

The question is: What is an idiomatic way to do this in a Gradle script, using the Java plugin?
(or, if there's no idiomatic way, what's a hacky solution that actually works?)

I don't mind the method of parametrization, just as long as the command-line and IDE invocations can easily choose between the two output options. The jar file will be used as a library in other projects, e.g. an Android app and a JavaFX app, so I would like the method of parametrization to be invokable/depended-on from their own Gradle scripts.

Ideally I'd like to 'emulate' the Android gradle plugin's ability to have a Debug/Release version of every task, i.e.

$ ./gradlew build
$ ./gradlew assembleRelease
$ ./gradlew checkDebug

but failing that even a top level buildDebug and buildRelease would be suitable.

Stuff I tried

This section isn't really relevant to the question.

Starting point

I have the following gradle file/project:

group 'TestGradleProjectGroup'
apply plugin: 'java'
sourceCompatibility = 1.8

version '1.0-release'
compileJava {
    options.debug = false
}

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
}

This works fine and produces the jar file:

$ ls TestGradleModule/build/libs/
TestGradleModule-1.0-release.jar

which, when the extracted classes are inspected with javap, doesn't contain any debug information. Hurrah. No we need a way to make a debug version.

Add debug & release tasks

version '1.0-release'
compileJava {
    options.debug = false
}

task buildRelease(type: GradleBuild, dependsOn: build) {
    project.version = '1.0-release'
    compileJava {
        options.debug = false
    }
}

task buildDebug(type: GradleBuild, dependsOn: build) {
    project.version = '1.0-debug'
    compileJava {
        options.debug = true
    }
}

This didn't work, as the debug project is always built, even if buildRelease is the task given on the command line. I guess this is because the code for both tasks is run at Configuration time (Gradle build lifecycle), whereas I only want one to run. So I guess I want to run them at Execution time?

Add some doLast tasks

version '1.0-release'
compileJava {
    options.debug = false
}

task buildRelease(type: GradleBuild, dependsOn: build) {
    doLast {
        project.version = '1.0-release'
        compileJava {
            options.debug = false

        }
    }
}

task buildDebug(type: GradleBuild, dependsOn: build) {
    doLast {
        project.version = '1.0-debug'
        compileJava {
            options.debug = true
        }
    }
}

This is even worse. The output file is always 1.0-release, and that's because of the 'default' at the top level. If I comment that out then a versioned jar is not made, instead the default of TestGradleModule.jar is made. It seems that the contents of the doLast blocks are completely useless in their effect upon the compileJava task (but there's no warning about this?). I guess these modifications are too late to be done at execution time, or that there's something else that needs to be done so that the compileJava tasks is "configured" differently?

Using Configurations?

I noticed the manual for the Java plugin contained a reference to buildConfigName and uploadConfigName, and claimed they depend on "The tasks which produce the artifacts in configuration ConfigName.". Given that I was failing to parametrize stuff at Configuration time, the plugin's ability to do that looked promising:

group 'TestGradleProjectGroup'
apply plugin: 'java'
sourceCompatibility = 1.8

configurations {
    debug
    release
}

version '1.0-release'
compileJava {
    options.debug = false
}

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
}

but:

This didn't add buildRelease or buildDebug to the output of ./gradlew tasks --all, as I expected it to. But I could run those tasks.

It only seemed to make buildRelease and buildDebug, not e.g. assembleRelease etc

buildRelease didn't seem to depend on anything when run so therefore had no useful effect.

Iterating tasks?

As a final attempt I've tried to create all of the appropriate tasks and linking the dependencies for everything. I tried iterating over the tasks and adding the dependencies:

gradle.taskGraph.whenReady { taskGraph ->

    taskGraph.allTasks.each { taskIter ->

        println("iterating" + taskIter)

        def releaseTask = project.task(taskIter.name + "Release")
        def debugTask = project.task(taskIter.name + "Debug")

        taskIter.dependsOn += [releaseTask, debugTask].toSet()
        println("new taskIter.dependsOn:" + taskIter.dependsOn)

        /*
            set debug mode here,
            copy over effects of task to debug/release
            disable effects of task
        */
    }
}

but

This didn't seem to create the tasks properly, they weren't accessible from the command line and running "build" didn't run "buildRelease" etc.

I would also have to "move" all of the "actions" from the current, existing tasks and into the debug and release tasks, to avoid duplicating the effects of each. And I don't know how to do that.

In short, I have no idea what I'm doing. As a last resort I could just create all of the tasks manually, but that seems to defeat the point of using the the java plugin and is very spammy?

Body:
Your question is detailed since you made a deep analysis of the problem. Although I believe that this issue could be solved if you would think in simpler way.

So if we think simple, a possible solution to your case is to run the debug task after the release is finalized. See the example below:

compileJava {
    options.debug = false
}

task buildRelease(type: GradleBuild, dependsOn: build) {
    doLast {
        project.version = '1.0-release'
        compileJava {
            options.debug = false

        }
    }
}

task buildDebug(type: GradleBuild, dependsOn: build) {
    doLast {
        project.version = '1.0-debug'
        compileJava {
            options.debug = true
        }
    }
}

// Here you are telling the buildDebug task to be executed right after the
// buildRelease task is finalized.
buildDebug.mustRunAfter buildRelease

In the above way you control the order of the task execution without introducing an explicit dependency between them.