问:
Building memory game minigame in JQuery (Javascript)
I am making a set of minigames for my major project, have being following a tutorial on the internet to make a memory game for one of them.

The code works up to where I generate a new board but the rest of the code doesn't seem to work. Have I done something wrong in my scipting? Can anyone tell me where I'm going wrong?

This is my code for the memory minigame.

$(document).ready(function() {

  //speech
  var progress = 0;
  var txt;
  $('#complete, #speech').hide();

  function eventHandler() {
    switch (progress) {
      case 0:
        txt = "Complete";
        break;
      case 1:
        txt = "Move on the the next game";
        $('#speech').click(function() {
          window.location.href = "minigame4.html"; //next minigame
        });
        break;
    }
    progress++;
    $('#speech').html(txt);
  }

  $('#speech').click(eventHandler);

  // Memory Game //

  var memory_array = ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F', 'G', 'G', 'H', 'H', 'I', 'I', 'J', 'J', 'K', 'K', 'L', 'L'];
  var memory_values = [];
  var memory_tile_ids = [];
  var tiles_flipped = 0;

  //shuffle method
  Array.prototype.memory_tile_shuffle = function() {
    var i = this.length,
      j, temp;
    while (--i > 0) {
      j = Math.floor(Math.random() * (i + 1));
      temp = this[j];
      this[j] = this[i];
      this[i] = temp;
    }
  }

  //generate new board
  function newBoard() {
    tiles_flipped = 0;
    var output = '';
    memory_array.memory_tile_shuffle();
    for (var i = 0; i < memory_array.length; i++) {
      output += '

';
    }
    $('#memory_board').html(output);
  }

  newBoard();

  //
  // all code works up to here

  function memoryFlipTile(tile, val) {
    // When tile is clicked, change colour to white along with its letter
    if (tile.html == "" && memory_values.length < 2) {
      tile.style.background = '#FFF';
      tile.html = val;
      // If no tiles are flipped
      if (memory_values.length == 0) {
        memory_values.push(val);
        memory_tile_ids.push(tile.id);
        // If one tile is already flipped
      } else if (memory_values.length == 1) {
        memory_values.push(val);
        memory_tile_ids.push(tile.id);
        // See if both tiles are a match
        if (memory_values[0] == memory_values[1]) {
          tiles_flipped += 2;
          // Clear both arrays
          memory_values = [];
          memory_tile_ids = [];
          // Check to see if the whole board is cleared
          // then display complete
          if (tiles_flipped == memory_array.length) {
            $("#complete").show(0, function() {
              eventHandler()
              $('#speech').show();
            });
          }
        } else {
          function flip2Back() {
            // Flip the 2 tiles back over
            var tile_1 = document.getElementById(memory_tile_ids[0]);
            var tile_2 = document.getElementById(memory_tile_ids[1]);
            tile_1.style.background - image = 'url(images/puzzle5/blank.png) no-repeat';
            tile_1.html = "";
            tile_2.style.background - image = 'url(images/puzzle5/blank.png) no-repeat';
            tile_2.html = "";
            // Clear both arrays
            memory_values = [];
            memory_tile_ids = [];
          }
          setTimeout(flip2Back, 700);
        }
      }
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div#memory_board {
  padding: 24px;
  margin: 0px auto;
  width: 456px;
  height: 300px;
}

div#memory_board div {
  float: left;
  margin: 10px;
  padding: 28px;
  font-size: 50px;
  cursor: pointer;
  text-align: center;
  background-image: url(images/puzzle5/blank.png);
}

#complete {
  position: absolute;
  width: 105px;
  height: 25px;
  top: 240px;
  left: 289px;
  background-color: black;
  color: white;
  font-size: 20px;
  padding: 10px;
  border-style: solid;
  border-width: 5px;
  border-color: white;
  z-index: 5;
}

#speech {
  position: absolute;
  width: 655px;
  height: 100px;
  top: 330px;
  left: 15px;
  background-color: black;
  color: white;
  font-size: 25px;
  padding: 10px;
  border-style: solid;
  border-width: 5px;
  border-color: white;
  z-index: 99;
}</code>```

<!doctype html>

  <meta charset="utf-8">
  <title>MAS340</title>
  <link href="styles.css" rel="stylesheet" />

```

答:
Apart from mentioned changes by some users, there are also other changes required in your script. As you are already using jQuery why don't utilize it fully?

Also have attached the event using jQuery like below as I suspect its able to see the function defined in the script while putting elements in dom. (Not sure about reason though yet)

I have changed your code in below fiddle. please check if its work for you (just corrected the syntax and replace some javascript code with jquery)

$(document).on('click','.tiles',function(){
    memoryFlipTile($(this),$(this).data("memchar"))
})

Check Fiddle

There is still a scope to optimize the code.

Body:
I am making a set of minigames for my major project, have being following a tutorial on the internet to make a memory game for one of them.

The code works up to where I generate a new board but the rest of the code doesn't seem to work. Have I done something wrong in my scipting? Can anyone tell me where I'm going wrong?

This is my code for the memory minigame.

$(document).ready(function() {

  //speech
  var progress = 0;
  var txt;
  $('#complete, #speech').hide();

  function eventHandler() {
    switch (progress) {
      case 0:
        txt = "Complete";
        break;
      case 1:
        txt = "Move on the the next game";
        $('#speech').click(function() {
          window.location.href = "minigame4.html"; //next minigame
        });
        break;
    }
    progress++;
    $('#speech').html(txt);
  }

  $('#speech').click(eventHandler);

  // Memory Game //

  var memory_array = ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F', 'G', 'G', 'H', 'H', 'I', 'I', 'J', 'J', 'K', 'K', 'L', 'L'];
  var memory_values = [];
  var memory_tile_ids = [];
  var tiles_flipped = 0;

  //shuffle method
  Array.prototype.memory_tile_shuffle = function() {
    var i = this.length,
      j, temp;
    while (--i > 0) {
      j = Math.floor(Math.random() * (i + 1));
      temp = this[j];
      this[j] = this[i];
      this[i] = temp;
    }
  }

  //generate new board
  function newBoard() {
    tiles_flipped = 0;
    var output = '';
    memory_array.memory_tile_shuffle();
    for (var i = 0; i < memory_array.length; i++) {
      output += '

';
    }
    $('#memory_board').html(output);
  }

  newBoard();

  //
  // all code works up to here

  function memoryFlipTile(tile, val) {
    // When tile is clicked, change colour to white along with its letter
    if (tile.html == "" && memory_values.length < 2) {
      tile.style.background = '#FFF';
      tile.html = val;
      // If no tiles are flipped
      if (memory_values.length == 0) {
        memory_values.push(val);
        memory_tile_ids.push(tile.id);
        // If one tile is already flipped
      } else if (memory_values.length == 1) {
        memory_values.push(val);
        memory_tile_ids.push(tile.id);
        // See if both tiles are a match
        if (memory_values[0] == memory_values[1]) {
          tiles_flipped += 2;
          // Clear both arrays
          memory_values = [];
          memory_tile_ids = [];
          // Check to see if the whole board is cleared
          // then display complete
          if (tiles_flipped == memory_array.length) {
            $("#complete").show(0, function() {
              eventHandler()
              $('#speech').show();
            });
          }
        } else {
          function flip2Back() {
            // Flip the 2 tiles back over
            var tile_1 = document.getElementById(memory_tile_ids[0]);
            var tile_2 = document.getElementById(memory_tile_ids[1]);
            tile_1.style.background - image = 'url(images/puzzle5/blank.png) no-repeat';
            tile_1.html = "";
            tile_2.style.background - image = 'url(images/puzzle5/blank.png) no-repeat';
            tile_2.html = "";
            // Clear both arrays
            memory_values = [];
            memory_tile_ids = [];
          }
          setTimeout(flip2Back, 700);
        }
      }
    }
  }
});

div#memory_board {
  padding: 24px;
  margin: 0px auto;
  width: 456px;
  height: 300px;
}

div#memory_board div {
  float: left;
  margin: 10px;
  padding: 28px;
  font-size: 50px;
  cursor: pointer;
  text-align: center;
  background-image: url(images/puzzle5/blank.png);
}

#complete {
  position: absolute;
  width: 105px;
  height: 25px;
  top: 240px;
  left: 289px;
  background-color: black;
  color: white;
  font-size: 20px;
  padding: 10px;
  border-style: solid;
  border-width: 5px;
  border-color: white;
  z-index: 5;
}

#speech {
  position: absolute;
  width: 655px;
  height: 100px;
  top: 330px;
  left: 15px;
  background-color: black;
  color: white;
  font-size: 25px;
  padding: 10px;
  border-style: solid;
  border-width: 5px;
  border-color: white;
  z-index: 99;
}

<!doctype html>

  <meta charset="utf-8">
  <title>MAS340</title>
  <link href="styles.css" rel="stylesheet" />


来源: stackexchange

问:
apple mach-o linker error linker command failed with exit code 1 (use -v to see invocation)

2I am working with Objective C with core data, I got an error:

Apple Mach-O Linker Error, Linker command failed with exit code 1 (use -v to see invocation)

答:
It's because the project inserted the core data's xcdatamodeld file in compile sources.
Select your project -> Build Phases -> Compile Sources and delete projectName.xcdatamodeld file.
Just try it and reply me if still any error.

ContentLicense: CC BY-SA 3.0


问:
How to use if statement within map in javascript/vuejs
I'm building a small application in Vuejs where I'm getting a response data and I'm mapping it to a variable, I've got few elements which has empty array, so while mapping I want to check the condition and map accordingly. Here is my code:

```<code>this.model = a.map(i => Object.assign({
    'id': i.id,
    'meeting_date': i.schedule,
    'meeting_call': i.type,
    'event_type': i.event_type,
    'venue': i.venue,
    'with_client': i.with_client
},{
    if(i.meeting.meeting_summaries)
    {
        'meeting_summaries': i.meeting_summaries.map(ms => ({
            client_name: ms.client_name,
            nature: ms.nature,
            action: ms.action,
            mention: ms.user_id,
            feedback: ms.feedback
        }))
    }

},
</code>```

答:
map is purely functional, it doesn't modify the elements instead return a newly formed array, so you can do like this:

```<code>this.model = a.map(i => {
  var item = {}
  item['id']= i.id,
  item['meeting_date']= i.schedule,
  item['meeting_call']= i.type,
  item['event_type']= i.event_type,
  item['venue']= i.venue,
  item['with_client']= i.with_client
  if(i.meeting && i.meeting.meeting_summaries) {
     item['meeting_summaries']= i.meeting.meeting_summaries.map(ms =>({
            client_name: ms.client_name,
            nature: ms.nature,
            action: ms.action,
            mention: ms.user_id,
            feedback: ms.feedback
        }))
  }else {
   item['meeting_summaries'] = []
  }
 return item
}
</code>```

Body:
I'm building a small application in Vuejs where I'm getting a response data and I'm mapping it to a variable, I've got few elements which has empty array, so while mapping I want to check the condition and map accordingly. Here is my code:

this.model = a.map(i => Object.assign({
    'id': i.id,
    'meeting_date': i.schedule,
    'meeting_call': i.type,
    'event_type': i.event_type,
    'venue': i.venue,
    'with_client': i.with_client
},{
    if(i.meeting.meeting_summaries)
    {
        'meeting_summaries': i.meeting_summaries.map(ms => ({
            client_name: ms.client_name,
            nature: ms.nature,
            action: ms.action,
            mention: ms.user_id,
            feedback: ms.feedback
        }))
    }

},

Body:
map is purely functional, it doesn't modify the elements instead return a newly formed array, so you can do like this:

this.model = a.map(i => {
  var item = {}
  item['id']= i.id,
  item['meeting_date']= i.schedule,
  item['meeting_call']= i.type,
  item['event_type']= i.event_type,
  item['venue']= i.venue,
  item['with_client']= i.with_client
  if(i.meeting && i.meeting.meeting_summaries) {
     item['meeting_summaries']= i.meeting.meeting_summaries.map(ms =>({
            client_name: ms.client_name,
            nature: ms.nature,
            action: ms.action,
            mention: ms.user_id,
            feedback: ms.feedback
        }))
  }else {
   item['meeting_summaries'] = []
  }
 return item
}


问:
Database query needs a lot of time
I am currently running this query and it takes around 15 sec to load i want to optimize the query

```<code>SELECT *, `points`.`players` as `players` ,
FROM_UNIXTIME(`points`.`timestamp`, '%Y-%m-%d %H:%i') as `date`,
        (SELECT   `points`.`players`
        FROM `points`
        WHERE   FROM_UNIXTIME(`points`.`timestamp`, '%Y-%m-%d %H:%i') > `date` - INTERVAL 7 DAY
                AND FROM_UNIXTIME(`points`.`timestamp`, '%Y-%m-%d %H:%i') < `date` - INTERVAL 167 HOUR
                AND `server_id` = {$server_id}
                AND `type` = 2
                LIMIT 1
        ) as `prevplayers`
FROM `points`
WHERE   `points`.`timestamp` > UNIX_TIMESTAMP(NOW() - INTERVAL 7 DAY)
        AND `server_id` = {$server_id}
        AND `type`=2
GROUP BY DATE_FORMAT(FROM_UNIXTIME(`points`.`timestamp`), '%Y-%m-%d %H')
ORDER BY DATE_FORMAT(FROM_UNIXTIME(`points`.`timestamp`),'%Y-%m-%d %H')
</code>```

Table structure

Indexes

With Explain Output

Ideal time is 1-2 secs

Any Suggestions?

Thanks
Somdeb

答:
Can you create an additional index with the columns in following order and retry the query?

server_id

type

timestamp (mention descending order)

Title: Database query needs a lot of time

Body:
I am currently running this query and it takes around 15 sec to load i want to optimize the query

SELECT *, `points`.`players` as `players` ,
FROM_UNIXTIME(`points`.`timestamp`, '%Y-%m-%d %H:%i') as `date`,
        (SELECT   `points`.`players`
        FROM `points`
        WHERE   FROM_UNIXTIME(`points`.`timestamp`, '%Y-%m-%d %H:%i') > `date` - INTERVAL 7 DAY
                AND FROM_UNIXTIME(`points`.`timestamp`, '%Y-%m-%d %H:%i') < `date` - INTERVAL 167 HOUR
                AND `server_id` = {$server_id}
                AND `type` = 2
                LIMIT 1
        ) as `prevplayers`
FROM `points`
WHERE   `points`.`timestamp` > UNIX_TIMESTAMP(NOW() - INTERVAL 7 DAY)
        AND `server_id` = {$server_id}
        AND `type`=2
GROUP BY DATE_FORMAT(FROM_UNIXTIME(`points`.`timestamp`), '%Y-%m-%d %H')
ORDER BY DATE_FORMAT(FROM_UNIXTIME(`points`.`timestamp`),'%Y-%m-%d %H')

Table structure

Indexes

With Explain Output

Ideal time is 1-2 secs

Any Suggestions?

Thanks
Somdeb


问:
Eclipse not found Existing web Project
I Have existing web app Project. I followed following steps to import the existing project
import->Existing project into workspace->folder . but it showing no project are found to import. Here I'm also attaching screen shots which I proceeded.

first:

second:

I'm not able to figure out the error. could you please help me

答:
In order for a folder to be a valid Eclipse project folder, it should contain .project .settings and .classpath files.

You should choose the folder that contains these files.

Title: Eclipse not found Existing web Project


问:
How to unit test (in C#) that a button is clicked?
I have a user control that has button whose click event handler contains the core logic. I want to test this button click handler.
This handler function calls a public function of another user control (which resides in separate C# project) which ultimately calls public function of a reference assembly.
Can anyone please tell me - how will be the unit test for such a handler?</p>

答:
You can write a method that programmatically raises the Click event and call that from your unit test.

Edit: Ah, this actually exists already: http://msdn.microsoft.com/en-us/library/hkkb40tf(VS.90).aspx

ContentLicense: CC BY-SA 2.5


问:
files in C++ and strings
i have learned basic C but i have to write a code in C++ so i am facing difficulty.there is a code

```<code>ifstream file(filename.c_str());
if (! file.is_open())
{ return -1; }
</code>```

as much i have googled about string and then file handling in C++ ifstream is a class in C++ and it needs an object to access this class functions and variables and c_str() is a function which is being used to return a C kind of char array. but i am unable to understand that where the object is in this case? is file is an object or it is  function? and on the second line it  is calling a function is_open which seams to return a true or false but why we are calling it here before even opening the file?

答:
filename i'm presuming is a std::string which is a class that has a function c_str
http://www.cplusplus.com/reference/string/string/c_str/

file is using ifstream, a class which is being constructed with whatever code is in the (const char*) constructor function.
The class constructor function from ifstream opens the file on class construction so you can check to see if it succeeded.

http://www.cplusplus.com/reference/fstream/ifstream/ifstream/

Title: files in C++ and strings

Body:
i have learned basic C but i have to write a code in C++ so i am facing difficulty.there is a code

ifstream file(filename.c_str());
if (! file.is_open())
{ return -1; }

as much i have googled about string and then file handling in C++ ifstream is a class in C++ and it needs an object to access this class functions and variables and c_str() is a function which is being used to return a C kind of char array. but i am unable to understand that where the object is in this case? is file is an object or it is  function? and on the second line it  is calling a function is_open which seams to return a true or false but why we are calling it here before even opening the file?


问:
How to test a function with N distinct paths?
I have a function which validates a model class where it has to check every member of the class to be non-null or non-empty in case of a String.

The logic for this is_complete function is something like this:

```<code>def is_complete(profile):
    if profile.first_name in (None, ''):
        return False
    elif profile.last_name in (None, ''):
        return False
    elif profile.dob is None:
        return False
    .
    .
    .# and checks so on for all members of the profile instance
    .
    .

    return True
</code>```

My question since the number of possible paths the execution can take is quite large and increases in proportion to the number of member variables of profile to be checked, how does one reliably write tests for all the possible paths?

Right now, I have two simple test cases:

where only some of the members are set and checks assertFalse(is_complete(foo))

where all the members are set and checks assertTrue(is_complete(foo))

But I have a feeling that this may not be enough.

答:
I'm not sure what you mean by having MxN paths. In the posted code you have as many paths as fields + 1.

Create a helper method that creates a profile that is complete and passes is_complete.

Add a test method to verify is_complete(profile) is True for the complete profile.

Add one test method for each field, with the following steps:

Call the helper method to create a complete profile that we know would pass is_complete

Break the field under test

Verify that is_complete returns False

You will have as many test methods as fields + 1.

Btw, instead of this:

```<code>if profile.first_name in (None, ''):
</code>```

You can writer simpler:

```<code>if not profile.first_name:
</code>```

Body:
I have a function which validates a model class where it has to check every member of the class to be non-null or non-empty in case of a String.

The logic for this is_complete function is something like this:

def is_complete(profile):
    if profile.first_name in (None, ''):
        return False
    elif profile.last_name in (None, ''):
        return False
    elif profile.dob is None:
        return False
    .
    .
    .# and checks so on for all members of the profile instance
    .
    .

    return True

My question since the number of possible paths the execution can take is quite large and increases in proportion to the number of member variables of profile to be checked, how does one reliably write tests for all the possible paths?

Right now, I have two simple test cases:

where only some of the members are set and checks assertFalse(is_complete(foo))

where all the members are set and checks assertTrue(is_complete(foo))

But I have a feeling that this may not be enough.

Body:
I'm not sure what you mean by having MxN paths. In the posted code you have as many paths as fields + 1.

Create a helper method that creates a profile that is complete and passes is_complete.

Add a test method to verify is_complete(profile) is True for the complete profile.

Add one test method for each field, with the following steps:

Call the helper method to create a complete profile that we know would pass is_complete

Break the field under test

Verify that is_complete returns False

You will have as many test methods as fields + 1.

Btw, instead of this:

if profile.first_name in (None, ''):

You can writer simpler:

if not profile.first_name:


问:
Store a ListBox Value into a variable
I am trying to store a selected listbox value as a variable. When I Debug RowSelect = .List(r, 9). The .List(r, 9) returns "10" which is correct but RowSelect returns "" Which is not correct. It should Return "10". Why does the variable not Return the correct string?

This is what I have so far.

```<code>Dim PendClick As Boolean
Dim RrkBoxChg As Long
Dim r As Long
Dim m As Long
Dim wsh As Worksheet
Dim RowSelect As String

Private Sub ListBox2_Click()
With Me.ListBox2
    If .ListIndex = -1 Then
    ElseIf .ListIndex >= 0 Then
    r = .ListIndex
        If PendClick = True Then
            Me.TextBox_Remarks = .List(r, 5)
            RowSelect = .List(r, 9)
        ElseIf PendClick = False Then
            Me.TextBox_Remarks = .List(r, 6)
            RowSelect = .List(r, 9)
        End If
    End If
End With
End Sub

Private Sub TextBox_Remarks_Change()
    r = Me.ListBox2.ListIndex
    If PendClick = True Then
        Me.ListBox2.List(r, 5) = Me.TextBox_Remarks
        Worksheets("ToolData").Cells(RowSelect, 12) = Me.TextBox_Remarks
    ElseIf PendClick = False Then
        Me.ListBox2.List(r, 6) = Me.TextBox_Remarks
        Worksheets("ToolData").Cells(RowSelect, 12) = Me.TextBox_Remarks
    End If
End Sub
</code>```

答:
So I found the issue. Me.TextBox_Remarks = .List(r, 5) was triggering the TextBox_Remarks_Change() event. Which would then error out because the variable RowSelect = "". I simply swaped the positions of Me.TextBox_Remarks = .List(r, 5) and RowSelect = .List(r, 9) so that the order of events was correct. This is the correction.

```<code>     If PendClick = True Then
        RowSelect = .List(r, 9)
        Me.TextBox_Remarks = .List(r, 5)
     ElseIf PendClick = False Then
        RowSelect = .List(r, 9)
        Me.TextBox_Remarks = .List(r, 6)
    End If
</code>```

Title: Store a ListBox Value into a variable

Body:
I am trying to store a selected listbox value as a variable. When I Debug RowSelect = .List(r, 9). The .List(r, 9) returns "10" which is correct but RowSelect returns "" Which is not correct. It should Return "10". Why does the variable not Return the correct string?

This is what I have so far.

Dim PendClick As Boolean
Dim RrkBoxChg As Long
Dim r As Long
Dim m As Long
Dim wsh As Worksheet
Dim RowSelect As String

Private Sub ListBox2_Click()
With Me.ListBox2
    If .ListIndex = -1 Then
    ElseIf .ListIndex >= 0 Then
    r = .ListIndex
        If PendClick = True Then
            Me.TextBox_Remarks = .List(r, 5)
            RowSelect = .List(r, 9)
        ElseIf PendClick = False Then
            Me.TextBox_Remarks = .List(r, 6)
            RowSelect = .List(r, 9)
        End If
    End If
End With
End Sub

Private Sub TextBox_Remarks_Change()
    r = Me.ListBox2.ListIndex
    If PendClick = True Then
        Me.ListBox2.List(r, 5) = Me.TextBox_Remarks
        Worksheets("ToolData").Cells(RowSelect, 12) = Me.TextBox_Remarks
    ElseIf PendClick = False Then
        Me.ListBox2.List(r, 6) = Me.TextBox_Remarks
        Worksheets("ToolData").Cells(RowSelect, 12) = Me.TextBox_Remarks
    End If
End Sub

Body:
So I found the issue. Me.TextBox_Remarks = .List(r, 5) was triggering the TextBox_Remarks_Change() event. Which would then error out because the variable RowSelect = "". I simply swaped the positions of Me.TextBox_Remarks = .List(r, 5) and RowSelect = .List(r, 9) so that the order of events was correct. This is the correction.

     If PendClick = True Then
        RowSelect = .List(r, 9)
        Me.TextBox_Remarks = .List(r, 5)
     ElseIf PendClick = False Then
        RowSelect = .List(r, 9)
        Me.TextBox_Remarks = .List(r, 6)
    End If


问:
Qt/C++: Icons not showing up when program is run
I've added a QAction to my QToolBar in my MainWindow in Qt Designer (using the Qt Creator IDE) and given that Action an icon (done by "Choose File" and selecting my .png located in the same directory as my project and source code). The icon shows up fine in the toolbar in Qt Designer, but does not show when the project is running. I've had similar trouble when choosing the title bar icon on windows. I've never used graphics in Qt before, is there something special I need to do?

Screenshot:

答:
While adding icons use "Choose Resource" option instead of "Choose
File" option.

Right click your project's name and click "Run
qmake".


问:
Hibernate: hbm2ddl.auto=update in production?
Is it okay to run Hibernate applications configured with hbm2ddl.auto=update to update the database schema in a production environment?

答:
It's not a good idea to use hbm2ddl.auto in production.

The only way to manage the database schema is to use incremental migration scripts because:

the scripts will reside in VCS along with your codebase. When you check out a branch, you recreate the whole schema from scratch.

the incremental scripts can be tested on a QA server before being applied in production

there is no need for manual intervention since the scripts can be run by Flyway, hence it reduces the possibility of human error associated with running scripts manually.

Even the Hibernate User Guide advise you to avoid using the hbm2ddl tool for production environments.

OwnerDisplayName: cretzel

ContentLicense: CC BY-SA 4.0


问:
How to add a space between the subtitle and a comma between some of the words?
How would I add a space between the subtitle and a comma between some of the words? I'm using swift 3.</p>

```<code> override
public  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!

    let selectedItem = matchingItems[indexPath.row].placemark
    cell.textLabel?.text = selectedItem.name
    cell.detailTextLabel?.text = selectedItem.subThoroughfare!  + selectedItem.thoroughfare!
    + selectedItem.locality! + selectedItem.administrativeArea! + selectedItem.postalCode!

    return cell
}
</code>```

答: You are using forced unwrap on values and there is a possibility that one of the value is nil due to which you are getting the crash when code is trying to concatenate string to nil values.

Body:
How would I add a space between the subtitle and a comma between some of the words? I'm using swift 3.

 override
public  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!

    let selectedItem = matchingItems[indexPath.row].placemark
    cell.textLabel?.text = selectedItem.name
    cell.detailTextLabel?.text = selectedItem.subThoroughfare!  + selectedItem.thoroughfare!
    + selectedItem.locality! + selectedItem.administrativeArea! + selectedItem.postalCode!

    return cell
}


问:
R - send two-line command to system
I am using a ImageMagick command on a OS X system to create a 2x2 panel consisting of four .png figures that I have on my disk:

```<code>convert \( image1.png image2.png -append \) \
\( image3.png image4.png -append \) +append result.png
</code>```

When pasted to my terminal, the above command gets adjusted by the system, receiving a > to the beginning of the second line:

```<code>convert \( image1.png image2.png -append \) \
> \( image3.png image4.png -append \) +append result.png
</code>```

The resulting figure looks like this:

I am trying to reproduce this last command from within R by using the following commands:

```<code>> line1 <- paste0(" convert \\(", " img1.png img2.png -append \\)", " \\")
> line2 <- paste0(" < \\(", " img3.png img4.png -append \\) ", "+append result.png")
> cat(paste(line1, line2, sep='\n'))
 convert \( img1.png img2.png -append \) \
 < \( img3.png img4.png -append \) +append result.png
</code>```

Apparently, the result from cat is what I need, but I can't find the right way to send it to the system. I tried to combine it with system, but I get an error:

```<code>system(cat(paste(line1, line2, sep='\n')))
Error in system(cat(paste(line1, line2, sep = "\n"))) :
  non-empty character argument expected
</code>```

The question is: how can I use R to send that specific two-line command to the system?

答:
Based on the comments to this question, I ended up finding the answer. This is the code I used from within R:</p>

```<code>system(paste0("convert \\( img1.png img2.png -append \\) \\( img3.png img4.png -append \\) +append result.png"))
</code>```

Title: R - send two-line command to system

Body:
I am using a ImageMagick command on a OS X system to create a 2x2 panel consisting of four .png figures that I have on my disk:

convert \( image1.png image2.png -append \) \
\( image3.png image4.png -append \) +append result.png

When pasted to my terminal, the above command gets adjusted by the system, receiving a > to the beginning of the second line:

convert \( image1.png image2.png -append \) \
> \( image3.png image4.png -append \) +append result.png

The resulting figure looks like this:

I am trying to reproduce this last command from within R by using the following commands:

> line1 <- paste0(" convert \\(", " img1.png img2.png -append \\)", " \\")
> line2 <- paste0(" < \\(", " img3.png img4.png -append \\) ", "+append result.png")
> cat(paste(line1, line2, sep='\n'))
 convert \( img1.png img2.png -append \) \
 < \( img3.png img4.png -append \) +append result.png

Apparently, the result from cat is what I need, but I can't find the right way to send it to the system. I tried to combine it with system, but I get an error:

system(cat(paste(line1, line2, sep='\n')))
Error in system(cat(paste(line1, line2, sep = "\n"))) :
  non-empty character argument expected

The question is: how can I use R to send that specific two-line command to the system?

Body:
Based on the comments to this question, I ended up finding the answer. This is the code I used from within R:

system(paste0("convert \\( img1.png img2.png -append \\) \\( img3.png img4.png -append \\) +append result.png"))


问:
Xamarin Connectivity plugin always throws NotImplementedException
I am trying to use Xam.Plugin.Connectivity 2.3.0 by James Montemagno in my Cross platform Xamarin app. The package is installed in all the three projects i.e. protable, android and iOS. But whenever i try to check connectivity, it throws NotImplementedException. This behaviour is independent of whether i try to access it in the portable or platform specific project. This is the code with which i try to access it

```<code>if (CrossConnectivity.Current.IsConnected)
{
    //business logic
}
</code>```

The exception details are as follows

System.NotImplementedException: This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.

I have read similar posts on various forums, but none helped.

答:
I have this

version installed and it works for me. download and install same version and try again. Hope that helps.

Body:
I am trying to use Xam.Plugin.Connectivity 2.3.0 by James Montemagno in my Cross platform Xamarin app. The package is installed in all the three projects i.e. protable, android and iOS. But whenever i try to check connectivity, it throws NotImplementedException. This behaviour is independent of whether i try to access it in the portable or platform specific project. This is the code with which i try to access it

if (CrossConnectivity.Current.IsConnected)
{
    //business logic
}

The exception details are as follows

System.NotImplementedException: This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.

I have read similar posts on various forums, but none helped.


问:
Different onClick and onLongClick methods for two buttons
I'm trying to create buttons that will execute certain different instructions based on a simple click and a long click, but I'm struck with low understanding on how to put everything together. Performing a defined method for every button is ok, but I think it would be better to use onClickListeners for this, isn't it?

So my code is as follows. As you can see, I'm trying to catch both types of event for each button, but when I press the button 1A I get the toast of the 2A, and when I click the button 2A I get an error and the app crashes.
The second thing to fix is to bind together the onClick and the onLongClick.

activity_scout.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.android.scout.ScoutActivity">

<LinearLayout
    android:id="@+id/activity_scout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="8dp"
    android:paddingLeft="8dp"
    android:paddingRight="8dp"
    android:paddingTop="8dp"
    android:orientation="vertical" >

    <Button
        android:id="@+id/but1A"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1a"
        android:onClick="click1a"
        />

    <Button
        android:id="@+id/but2A"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="2a"
        android:onClick="click2a" />

   </LinearLayout>
</ScrollView>
</code>```

ScoutActivity.java

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import static com.example.android.basketscout.R.id.butPlayer1A;
import static com.example.android.basketscout.R.id.butPlayer2A;
import static com.example.android.basketscout.R.id.butPlayer3A;
import static com.example.android.basketscout.R.id.butPlayer4A;
import static com.example.android.basketscout.R.id.butPlayer5A;
import static com.example.android.basketscout.R.id.textView;

public class ScoutActivity extends AppCompatActivity {

    Button but1A;
    Button but2A;
    Button but3A;
    Button but4A;
    Button but5A;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scout);

        but1A = (Button) findViewById(R.id.but1A);
        but2A = (Button) findViewById(R.id.but1A);

        but1A.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view){
                Toast.makeText(getApplicationContext(), "Button 1A clicked", Toast.LENGTH_SHORT).show();
            }
        });

        but2A.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view){
                Toast.makeText(getApplicationContext(), "Button 2A clicked", Toast.LENGTH_SHORT).show();
            }
        });

        but1A.setOnLongClickListener(new View.OnLongClickListener(){
            public void onLongClick (View view) {
                Toast.makeText(getApplicationContext(),"Button 1A long clicked", Toast.LENGTH_SHORT).show();
            }
        });

    but2A.setOnLongClickListener(new View.OnLongClickListener(){
        public void onLongClick (View view) {
            Toast.makeText(getApplicationContext(),"Button 2A long clicked", Toast.LENGTH_SHORT).show();
        }
    });
    }

 }
</code>```

[If you see any error like unclosed parentheris or not completely correct variable names, it's because of some edit from the copy/paste I did]

答:
Remove the onClick attribute from
Button layout

And correct this code

```<code>but1A = (Button)findViewById(R.id.but1A);
but2A = (Button)findViewById(R.id.but1A);
</code>```

To

```<code>but1A = (Button)findViewById(R.id.but1A);
but2A = (Button)findViewById(R.id.but2A);
</code>```

Body:
I'm trying to create buttons that will execute certain different instructions based on a simple click and a long click, but I'm struck with low understanding on how to put everything together. Performing a defined method for every button is ok, but I think it would be better to use onClickListeners for this, isn't it?

So my code is as follows. As you can see, I'm trying to catch both types of event for each button, but when I press the button 1A I get the toast of the 2A, and when I click the button 2A I get an error and the app crashes.
The second thing to fix is to bind together the onClick and the onLongClick.

activity_scout.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.android.scout.ScoutActivity">

<LinearLayout
    android:id="@+id/activity_scout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="8dp"
    android:paddingLeft="8dp"
    android:paddingRight="8dp"
    android:paddingTop="8dp"
    android:orientation="vertical" >

    <Button
        android:id="@+id/but1A"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1a"
        android:onClick="click1a"
        />

    <Button
        android:id="@+id/but2A"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="2a"
        android:onClick="click2a" />

   </LinearLayout>
</ScrollView>

ScoutActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import static com.example.android.basketscout.R.id.butPlayer1A;
import static com.example.android.basketscout.R.id.butPlayer2A;
import static com.example.android.basketscout.R.id.butPlayer3A;
import static com.example.android.basketscout.R.id.butPlayer4A;
import static com.example.android.basketscout.R.id.butPlayer5A;
import static com.example.android.basketscout.R.id.textView;

public class ScoutActivity extends AppCompatActivity {

    Button but1A;
    Button but2A;
    Button but3A;
    Button but4A;
    Button but5A;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scout);

        but1A = (Button) findViewById(R.id.but1A);
        but2A = (Button) findViewById(R.id.but1A);

        but1A.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view){
                Toast.makeText(getApplicationContext(), "Button 1A clicked", Toast.LENGTH_SHORT).show();
            }
        });

        but2A.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view){
                Toast.makeText(getApplicationContext(), "Button 2A clicked", Toast.LENGTH_SHORT).show();
            }
        });

        but1A.setOnLongClickListener(new View.OnLongClickListener(){
            public void onLongClick (View view) {
                Toast.makeText(getApplicationContext(),"Button 1A long clicked", Toast.LENGTH_SHORT).show();
            }
        });

    but2A.setOnLongClickListener(new View.OnLongClickListener(){
        public void onLongClick (View view) {
            Toast.makeText(getApplicationContext(),"Button 2A long clicked", Toast.LENGTH_SHORT).show();
        }
    });
    }

 }

[If you see any error like unclosed parentheris or not completely correct variable names, it's because of some edit from the copy/paste I did]

Body:
Remove the onClick attribute from
Button layout

And correct this code

but1A = (Button)findViewById(R.id.but1A);
but2A = (Button)findViewById(R.id.but1A);

To

but1A = (Button)findViewById(R.id.but1A);
but2A = (Button)findViewById(R.id.but2A);


问:
What am I missing between version 6 & 7 of Android?
I have an admin app that developed about a year ago. There are 2 admins only (me and one other person). There is a login screen that requires user name/password.

Up until I upgraded my Note 5 from 6 to 7 - I was able to login without any issues. Now that I am on 7 that is no longer the case.

The other admin (who is using version 5 of Android) is having no issues. I have also successfully logged into the app on a Android emulator on my computer.

I have been unable to locate anything when reading about android 7 that would indicate there should be a problem with that part of the app as far as programming would go.

What am I missing?

答:
your

```<code>android:targetSdkVersion
</code>```

make everything work

Body:
your

android:targetSdkVersion

make everything work


问:
dyld: lazy symbol binding failed: Symbol not found: __ZN5boost11this_thread5hiden11sleep_untilERK8timespec (have ...6hidden11sleep_untilERK8timespec)
Trying to use OMPL 1.1.0 library. I'm using this sample code (not really relevant to the problem, which happens at runtime):

```<code>#include <ompl/base/Goal.h>
#include <ompl/base/goals/GoalState.h>
#include <ompl/base/goals/GoalStates.h>
#include <ompl/base/ProjectionEvaluator.h>
#include <ompl/base/StateSpace.h>
#include <ompl/geometric/PathSimplifier.h>
#include <ompl/base/samplers/UniformValidStateSampler.h>

#include <ompl/base/spaces/RealVectorStateSpace.h>
#include <ompl/base/spaces/SE2StateSpace.h>
#include <ompl/base/spaces/SE3StateSpace.h>

#include <ompl/geometric/SimpleSetup.h>
#include <ompl/geometric/planners/rrt/RRT.h>

#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>

#include <iostream>

namespace ob = ompl::base;
namespace og = ompl::geometric;

bool isStateValid(const ob::State *state)
{
    return true;
}

int main(int /*argc*/, char ** /*argv*/)
{
    std::cout << "OMPL version: " << OMPL_VERSION << std::endl;
    boost::shared_ptr<ob::SE3StateSpace> space(boost::make_shared<ob::SE3StateSpace>());
    ob::RealVectorBounds bounds(3);
    bounds.setLow(-1);
    bounds.setHigh(1);
    space->setBounds(bounds);
    og::SimpleSetup ss(space);
    //ss.setStateValidityChecker([](const ob::State *state) { return isStateValid(state); });
    ob::ScopedState<> start(space);
    start.random();
    ob::ScopedState<> goal(space);
    goal.random();
    ss.setStartAndGoalStates(start, goal);
    ss.setup();
    ss.print();
    ob::PlannerStatus solved = ss.solve(1.0);
    if(solved)
    {
        std::cout << "Found solution:" << std::endl;
        ss.simplifySolution();
        ss.getSolutionPath().print(std::cout);
    }
    else
        std::cout << "No solution found" << std::endl;
    return 0;
}
</code>```

and the following makefile:

```<code>CXXFLAGS=-I/usr/local/Cellar/ompl/1.1.0/include -I/usr/local/Cellar/boost/1.64.0_1/include
LDLIBS=-lc++ -L/usr/local/Cellar/boost/1.64.0_1/lib/ -lboost_thread-mt -lboost_filesystem -lboost_system -lompl
ompltest: ompltest.o
</code>```

when I run the executable I get:

```<code>dyld: lazy symbol binding failed: Symbol not found: __ZN5boost11this_thread5hiden11sleep_untilERK8timespec
  Referenced from: /usr/local/opt/ompl/lib/libompl.11.dylib
  Expected in: /usr/local/opt/boost/lib/libboost_thread-mt.dylib

dyld: Symbol not found: __ZN5boost11this_thread5hiden11sleep_untilERK8timespec
  Referenced from: /usr/local/opt/ompl/lib/libompl.11.dylib
  Expected in: /usr/local/opt/boost/lib/libboost_thread-mt.dylib

Abort trap: 6
</code>```

I look for the missing symbol in the boost shared library, and I find:

```<code>$ nm -gU /usr/local/opt/boost/lib/libboost_thread-mt.dylib | grep sleep_until.*timespec
0000000000004130 T __ZN5boost11this_thread21no_interruption_point6hidden11sleep_untilERK8timespec
0000000000004390 T __ZN5boost11this_thread6hidden11sleep_untilERK8timespec
</code>```

there is __ZN5boost11this_thread6hidden11sleep_untilERK8timespec and not __ZN5boost11this_thread5hiden11sleep_untilERK8timespec .
what is that? a typo? or intended?
the point is that I cannot use this library which I didn't even build by myself (installed via homebrew)

EDIT: unmangled symbol names:

```<code>$ nm -jgU /usr/local/opt/boost/lib/libboost_thread-mt.dylib | grep sleep_until.*timespec | c++filt
boost::this_thread::no_interruption_point::hidden::sleep_until(timespec const&)
boost::this_thread::hidden::sleep_until(timespec const&)
$ echo __ZN5boost11this_thread5hiden11sleep_untilERK8timespec | c++filt
boost::this_thread::hiden::sleep_until(timespec const&)
</code>```

答:
As suggested by John Zwinck

echo __ZN5boost11this_thread5hiden11sleep_untilERK8timespec |c++filt
boost::this_thread::hiden::sleep_until(timespec const&)

echo __ZN5boost11this_thread6hidden11sleep_untilERK8timespec |c++filt
boost::this_thread::hidden::sleep_until(timespec const&)

Perhaps your /usr/local/opt/ompl/lib/libompl.11.dylib was built using different version of boost library then your current 1.64 ?
What boost library was used to build OMPL ?

Body:
Trying to use OMPL 1.1.0 library. I'm using this sample code (not really relevant to the problem, which happens at runtime):

#include <ompl/base/Goal.h>
#include <ompl/base/goals/GoalState.h>
#include <ompl/base/goals/GoalStates.h>
#include <ompl/base/ProjectionEvaluator.h>
#include <ompl/base/StateSpace.h>
#include <ompl/geometric/PathSimplifier.h>
#include <ompl/base/samplers/UniformValidStateSampler.h>

#include <ompl/base/spaces/RealVectorStateSpace.h>
#include <ompl/base/spaces/SE2StateSpace.h>
#include <ompl/base/spaces/SE3StateSpace.h>

#include <ompl/geometric/SimpleSetup.h>
#include <ompl/geometric/planners/rrt/RRT.h>

#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>

#include <iostream>

namespace ob = ompl::base;
namespace og = ompl::geometric;

bool isStateValid(const ob::State *state)
{
    return true;
}

int main(int /*argc*/, char ** /*argv*/)
{
    std::cout << "OMPL version: " << OMPL_VERSION << std::endl;
    boost::shared_ptr<ob::SE3StateSpace> space(boost::make_shared<ob::SE3StateSpace>());
    ob::RealVectorBounds bounds(3);
    bounds.setLow(-1);
    bounds.setHigh(1);
    space->setBounds(bounds);
    og::SimpleSetup ss(space);
    //ss.setStateValidityChecker([](const ob::State *state) { return isStateValid(state); });
    ob::ScopedState<> start(space);
    start.random();
    ob::ScopedState<> goal(space);
    goal.random();
    ss.setStartAndGoalStates(start, goal);
    ss.setup();
    ss.print();
    ob::PlannerStatus solved = ss.solve(1.0);
    if(solved)
    {
        std::cout << "Found solution:" << std::endl;
        ss.simplifySolution();
        ss.getSolutionPath().print(std::cout);
    }
    else
        std::cout << "No solution found" << std::endl;
    return 0;
}

and the following makefile:

CXXFLAGS=-I/usr/local/Cellar/ompl/1.1.0/include -I/usr/local/Cellar/boost/1.64.0_1/include
LDLIBS=-lc++ -L/usr/local/Cellar/boost/1.64.0_1/lib/ -lboost_thread-mt -lboost_filesystem -lboost_system -lompl
ompltest: ompltest.o

when I run the executable I get:

dyld: lazy symbol binding failed: Symbol not found: __ZN5boost11this_thread5hiden11sleep_untilERK8timespec
  Referenced from: /usr/local/opt/ompl/lib/libompl.11.dylib
  Expected in: /usr/local/opt/boost/lib/libboost_thread-mt.dylib

dyld: Symbol not found: __ZN5boost11this_thread5hiden11sleep_untilERK8timespec
  Referenced from: /usr/local/opt/ompl/lib/libompl.11.dylib
  Expected in: /usr/local/opt/boost/lib/libboost_thread-mt.dylib

Abort trap: 6

I look for the missing symbol in the boost shared library, and I find:

$ nm -gU /usr/local/opt/boost/lib/libboost_thread-mt.dylib | grep sleep_until.*timespec
0000000000004130 T __ZN5boost11this_thread21no_interruption_point6hidden11sleep_untilERK8timespec
0000000000004390 T __ZN5boost11this_thread6hidden11sleep_untilERK8timespec

there is __ZN5boost11this_thread6hidden11sleep_untilERK8timespec and not __ZN5boost11this_thread5hiden11sleep_untilERK8timespec .
what is that? a typo? or intended?
the point is that I cannot use this library which I didn't even build by myself (installed via homebrew)

EDIT: unmangled symbol names:

$ nm -jgU /usr/local/opt/boost/lib/libboost_thread-mt.dylib | grep sleep_until.*timespec | c++filt
boost::this_thread::no_interruption_point::hidden::sleep_until(timespec const&)
boost::this_thread::hidden::sleep_until(timespec const&)
$ echo __ZN5boost11this_thread5hiden11sleep_untilERK8timespec | c++filt
boost::this_thread::hiden::sleep_until(timespec const&)


问:
Gluster remove-brick from volume failed, what to do to remove a brick?
I had a gluster volume named data of distributed mode. I added a brick server1:/vdata/bricks/data to the volume data, However I found that vdata/bricks/data is on the / disk of linux. I wanna remove the brick from volume. So I use gluster volume remove disk data server1:/vdata/bricks/data start. Then I check the status using gluster volume remove-brick data server1:/vdata/bricks/data status but found the status is failed, and the scanned files is always 0. So what could I do to remove this brick without lossing data?

答: I have found the reason myself. It is because of DNS resolution failure for some server nodes. After I recovered the DNS, everything works OK!</p>


问:
Hotlinking protecttion of only one directory
I want to block access to only one directory say http://www.example.com/pictures
Every file in other directory should be available as normal.

I have gone through a referrer checking solution. That can be easily bypassed.

I Simply want to show images in pictures directory on a page say view.php
if images in this directory accessed from anywhere else. Just redirect to an image that says hotlinking not allowed"

Thanks

答:
I have gone through a referrer checking solution. That can be easily bypassed.

Yes, it can. But so can any hotlink-prevention scheme. It'll deter casual/careless use, but that's about it.

For what it's worth, referrer-checking is pretty much the way to do it.


问:
How to import module into xcode
I am trying to use socket.io in my swift app.

I am new in swift.

I'm following the instructions from https://github.com/socketio/socket.io-client-swift

but here is the problem, I don't understand how to do the following step.

(Install Manually) "Copy the Source folder into your Xcode project.
  (Make sure you add the files to your target(s))"

I don't understand how to achieve this, I have "Added the SocketIO.h and the entire folder into the project, but no matter what, the module is not found.

Am i supposed to add some binaries, if so what are the binaries? What are the extension? How can I identify it?

Here is the image of my xcode project....image of my screen in xcode

答:
When you clone or or download the socket io project you get a directory with multiple subdirectories. One of the subdirectories is named Source. Simply drag that folder into Xcode (into the Project Navigator in the left sidebar).

You will then be presented with a screen like this:

Make sure the box for your app is ticked in the "Add to targets" list. This is what the instructions mean by "Make sure you add the files to your target(s)"

Title: How to import module into xcode


问:
Storing and checking a boolean in a python class
So I was trying to create an object which basically has a constructor that takes two coordinates, xcoord and ycoord. I further created methods which shift the coordinates and I have to check if the point is valid or not(criteria for validity is if the coordinates are out of a specified range it should return False else True).

Problem:

My class only returns the validity for the initial points, not the shifted points.

What do I need to correct my code?

Code:

```<code>class Point:
    MaxScreenSize=10
    def __init__(self,x,y):
        self.xcoord=x
        self.ycoord=y
        if 0>self.xcoord or self.xcoord>Point.MaxScreenSize or 0>self.ycoord or self.ycoord>Point.MaxScreenSize:
            Point.isValidPt=False
        else:
            Point.isValidPt=True
    def translateX(self,shiftX):
        self.xcoord=self.xcoord+shiftX
    def translateY(self,shiftY):
        self.ycoord=self.ycoord+shiftY
</code>```

Test Code:

I tried my code and it only returns the isValidFunction variable for my initial points (gives me True instead of False for following code)

```<code>p=Point(9,2)
p.translateX(20)
p.translateY(10)
p.isValidPt
</code>```

答:
Your isValidPt is only calculated when the class is instantiated. Instead try something like:

Code:

```<code>class Point:
    MaxScreenSize = 10

    def __init__(self, x, y):
        self.xcoord = x
        self.ycoord = y

    def translateX(self, shiftX):
        self.xcoord = self.xcoord + shiftX

    def translateY(self, shiftY):
        self.ycoord = self.ycoord + shiftY

    @property
    def isValidPt(self):
        return (
            0 <= self.xcoord <= Point.MaxScreenSize and
            0 <= self.ycoord <= Point.MaxScreenSize
        )
</code>```

Test Code:

```<code>p = Point(9, 2)
p.translateX(20)
p.translateY(10)
print(p.isValidPt)
</code>```

Result:

```<code>False
</code>```

Body:
So I was trying to create an object which basically has a constructor that takes two coordinates, xcoord and ycoord. I further created methods which shift the coordinates and I have to check if the point is valid or not(criteria for validity is if the coordinates are out of a specified range it should return False else True).

Problem:

My class only returns the validity for the initial points, not the shifted points.

What do I need to correct my code?

Code:

class Point:
    MaxScreenSize=10
    def __init__(self,x,y):
        self.xcoord=x
        self.ycoord=y
        if 0>self.xcoord or self.xcoord>Point.MaxScreenSize or 0>self.ycoord or self.ycoord>Point.MaxScreenSize:
            Point.isValidPt=False
        else:
            Point.isValidPt=True
    def translateX(self,shiftX):
        self.xcoord=self.xcoord+shiftX
    def translateY(self,shiftY):
        self.ycoord=self.ycoord+shiftY

Test Code:

I tried my code and it only returns the isValidFunction variable for my initial points (gives me True instead of False for following code)

p=Point(9,2)
p.translateX(20)
p.translateY(10)
p.isValidPt

Body:
Your isValidPt is only calculated when the class is instantiated. Instead try something like:

Code:

class Point:
    MaxScreenSize = 10

    def __init__(self, x, y):
        self.xcoord = x
        self.ycoord = y

    def translateX(self, shiftX):
        self.xcoord = self.xcoord + shiftX

    def translateY(self, shiftY):
        self.ycoord = self.ycoord + shiftY

    @property
    def isValidPt(self):
        return (
            0 <= self.xcoord <= Point.MaxScreenSize and
            0 <= self.ycoord <= Point.MaxScreenSize
        )

Test Code:

p = Point(9, 2)
p.translateX(20)
p.translateY(10)
print(p.isValidPt)

Result:

False


问:
How to allow user to input a color (non hex or rbga) for list customization but make sure it's valid
Just wondering if anyone knows the best way to implement this into code. Is there a method for checking if a string is a valid color?

I want to allow the user to click a button to change color and then enter a color name, changing the background color of their list.

答:
You can get the valid color names from the specification CSS Color Module Level 4, set pattern attribute to RegExp as string from array delimited by | for OR; set required attribute at input type="text" element, provide notification to user at adjacent  element whether or not color name is valid.

window.onload = () => {
  const cssColor = "https://drafts.csswg.org/css-color/";
  const input = document.querySelector("form input[type=text]");
  const button = document.querySelector("form input[type=button]");
  const img = document.querySelector("form img");
  const span = document.querySelector("span");

  fetch(cssColor)
    .then(response => response.text())
    .then(html => {
      const parser = new DOMParser();
      const doc = parser.parseFromString(html, "text/html");
      const colorNames = Array.from(
        doc.querySelectorAll(".named-color-table dfn")
        , ({textContent}) => textContent
      );
      console.log(colorNames);
      input.pattern = colorNames
        .concat(colorNames.map(color => color.toUpperCase())).join("|");
      button.addEventListener("click", e => {
        if (input.checkValidity())
          img.style.backgroundColor = input.value;
      });
      input.removeAttribute("disabled");
      button.removeAttribute("disabled");
      span.style.display = "none";
    })
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>form * {
  padding: 4px;
  margin: 4px;
}

img {
  border: 1px solid black;
}

#colorName:invalid+[for=colorName]:after {
  content: "Invalid color";
  color: red;
}

#colorName:valid+[for=colorName]:after {
  content: "Valid color";
  color: green;
}</code>```

loading valid color names..
<form>
  <input id="colorName" type="text" required pattern="" disabled/>

  <input type="button" value="click" disabled>

</form>```

Body:
You can get the valid color names from the specification CSS Color Module Level 4, set pattern attribute to RegExp as string from array delimited by | for OR; set required attribute at input type="text" element, provide notification to user at adjacent <label> element whether or not color name is valid.

window.onload = () => {
  const cssColor = "https://drafts.csswg.org/css-color/";
  const input = document.querySelector("form input[type=text]");
  const button = document.querySelector("form input[type=button]");
  const img = document.querySelector("form img");
  const span = document.querySelector("span");

  fetch(cssColor)
    .then(response => response.text())
    .then(html => {
      const parser = new DOMParser();
      const doc = parser.parseFromString(html, "text/html");
      const colorNames = Array.from(
        doc.querySelectorAll(".named-color-table dfn")
        , ({textContent}) => textContent
      );
      console.log(colorNames);
      input.pattern = colorNames
        .concat(colorNames.map(color => color.toUpperCase())).join("|");
      button.addEventListener("click", e => {
        if (input.checkValidity())
          img.style.backgroundColor = input.value;
      });
      input.removeAttribute("disabled");
      button.removeAttribute("disabled");
      span.style.display = "none";
    })
}

form * {
  padding: 4px;
  margin: 4px;
}

img {
  border: 1px solid black;
}

#colorName:invalid+[for=colorName]:after {
  content: "Invalid color";
  color: red;
}

#colorName:valid+[for=colorName]:after {
  content: "Valid color";
  color: green;
}

<span>loading valid color names..</span>
<form>
  <input id="colorName" type="text" required pattern="" disabled/><label for="colorName"></label><br>
  <input type="button" value="click" disabled><br>
  <img alt="color" width="100px" height="100px">
</form>


问:
delete a row in table view in swift
I am trying to delete a row in table view. I have implemented the required methods but when i am swiping the row horizontally no delete button is coming. I have searched and I have found the same solution everywhere but it is not working in my case. I don't know where i am making mistake. Can anyone help me please? </p>

```<code>func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool
{
    return true
}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
     if editingStyle == .Delete
     {
        dataHandler.deletePeripheral(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
     }
}
</code>```

答:
for swift 3 </p>

```<code>func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == UITableViewCellEditingStyle.delete {
        dataHandler.deletePeripheral(indexPath.row)
        tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
        // - OR -
        // mTableView.reloadData() //mTableView is an outlet for the tableView
    }
}
</code>```

Title: delete a row in table view in swift

Body:
I am trying to delete a row in table view. I have implemented the required methods but when i am swiping the row horizontally no delete button is coming. I have searched and I have found the same solution everywhere but it is not working in my case. I don't know where i am making mistake. Can anyone help me please?

func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool
{
    return true
}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
     if editingStyle == .Delete
     {
        dataHandler.deletePeripheral(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
     }
}

Body:
for swift 3

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == UITableViewCellEditingStyle.delete {
        dataHandler.deletePeripheral(indexPath.row)
        tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
        // - OR -
        // mTableView.reloadData() //mTableView is an outlet for the tableView
    }
}


问:
About transaction in Realm database
This is my Realm object:

```<code>class AchievementDate : Object {

    dynamic var date: Date = Date()
    dynamic var apple: Int = Int(0)

    func save() {
        do {
            let realm = try Realm()
            try realm.write {
                realm.add(self)
            }
        } catch let error as NSError {
            fatalError(error.localizedDescription)
        }
    }
}
</code>```

I change apple's value in View controller's viewDidLoad() method, as you can see:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    achievementDate.apple = 2
    achievementDate.save()
}
</code>```

then I update the apple's value when user clicks the pause button on the screen like this:

```<code>@IBAction func pausedButtonTapped(_ sender: UIButton) {
    achievementDate.apple += 1
    achievementDate.save()
}
</code>```

Xcode runs it successfully but when I click the pause button, the app crashes. In the console it says:

*** Terminating app due to uncaught exception 'RLMException', reason: 'Attempting to modify object outside of a write transaction - call
  beginWriteTransaction on an RLMRealm instance first.'

I am quite confused about this, btw, what does transaction mean in general? Thanks a lot.

答:
A write transaction is used to group modifications of objects within a Realm into a single unit of work. Managed Realm objects may only be modified within a write transaction. The write transaction is scoped to the block you pass to the call to Realm.write(_:). The call to write begins a write transaction, the body is executed with the transaction active, and when the block returns the write transaction is committed and the changes are persisted to the Realm file.

You've not shared how achievementDate is initialized, but it seems safe to assume based on the exception you're seeing that it is an AchievementDate instance that is a managed object (that is, it was either created then added to a Realm, or it was loaded from a Realm). As the exception notes, you can only modify managed objects within a write transaction. You can either expand the scope of your write transaction to encompass the modification of the managed object, or you can avoid modifying a managed object altogether (by adding a primary key to your model class, and using either Realm.create(_:value:update:) or Realm.add(_:update:) with update: true to update an existing object with the given primary key value).

Title: About transaction in Realm database

Body:
This is my Realm object:

class AchievementDate : Object {

    dynamic var date: Date = Date()
    dynamic var apple: Int = Int(0)

    func save() {
        do {
            let realm = try Realm()
            try realm.write {
                realm.add(self)
            }
        } catch let error as NSError {
            fatalError(error.localizedDescription)
        }
    }
}

I change apple's value in View controller's viewDidLoad() method, as you can see:

override func viewDidLoad() {
    super.viewDidLoad()
    achievementDate.apple = 2
    achievementDate.save()
}

then I update the apple's value when user clicks the pause button on the screen like this:

@IBAction func pausedButtonTapped(_ sender: UIButton) {
    achievementDate.apple += 1
    achievementDate.save()
}

Xcode runs it successfully but when I click the pause button, the app crashes. In the console it says:

*** Terminating app due to uncaught exception 'RLMException', reason: 'Attempting to modify object outside of a write transaction - call
  beginWriteTransaction on an RLMRealm instance first.'

I am quite confused about this, btw, what does transaction mean in general? Thanks a lot.


问:
Get process variable
Given a process id, is it possible to connect to a Python process (launched from another interpreter instance) and retrieve user-defined variable values?

I'd like to get the progress from a worker process. The mechanisms described here (Value, Array) seem to assume communication between parent process (i.e. process initiator) and child process only. I could only think of an indirect way by letting the process write its variables to a data storage, but was hoping there's also a more direct way to achieve this. How would the Python code look like that "connects" to other non-child processes to retrieve variable values?

Title: Get process variable

Body:
checkout psutil:

>>> import psutil
>>> psutil.pids()
[1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, ..., 32498]
>> psutil.Process(32498).environ()
{}


问:
What measurement do you use in your development process to determine *Doneness* of your software?
I just finished listening to a very eye-opening podcast on Hanselminutes about the definition of "Done". So my question to everyone is "When do you consider a piece of software to be "Done"? Is it when it's fully unit tested? Is it when it's completely documented? What measurement do you use in your development process to determine Doneness of your software?

答: It's never done, simply versioned and released.</p>

OwnerDisplayName: Micah

OwnerDisplayName: tgm


问:
Retrofit & RxJava multiple requests complete
I need to do:

Request 2 lists of news from different websites

Combine results from requests

Sort items by date

Get 10 newest news

Save them

Show complete message

For example, I have this two observables:

```<code>Observable<RegionalNews> regionalNews;
Observable<NationalNews> nationalNews;

public interface NewsNationalService {
  @GET("news/national")
  Observable<News> getNationalNews();
}

public interface NewsRegionalService {
  @GET("news/regional")
  Observable<News> getRegionalNews();
}
</code>```

答:
If you don't want to do something specific with the combined results, then merge() is enough:</p>

```<code>Observable<RegionalNews> regionalNews = ...;
Observable<NationalNews> nationalNews = ...;

Observable
.merge(regionalNews, nationalNews)
.ignoreElements()
.observeOn(AndroidSchedulers.mainThread())
.doOnComplete(() -> { /* show alert */ })
.subscribe()
</code>```

Body:
I need to do:

Request 2 lists of news from different websites

Combine results from requests

Sort items by date

Get 10 newest news

Save them

Show complete message

For example, I have this two observables:

Observable<RegionalNews> regionalNews;
Observable<NationalNews> nationalNews;

public interface NewsNationalService {
  @GET("news/national")
  Observable<News> getNationalNews();
}

public interface NewsRegionalService {
  @GET("news/regional")
  Observable<News> getRegionalNews();
}

Body:
If you don't want to do something specific with the combined results, then merge() is enough:

Observable<RegionalNews> regionalNews = ...;
Observable<NationalNews> nationalNews = ...;

Observable
.merge(regionalNews, nationalNews)
.ignoreElements()
.observeOn(AndroidSchedulers.mainThread())
.doOnComplete(() -> { /* show alert */ })
.subscribe()


问:
Creating multiple intro screens in nativescript
I'm trying to create an intro screen for an app I'm building using nativescript and angular. However, I didn't found anything about this type of view, so I don't know exactly what to use in this case.

This intro should be visible only on the first access, but this part I think it's pretty straight forward. I'll be using applicationSettings and checking if a given property (e.g. firstAccess) is false, indicating it's user's first access.

But how can I create the actual intro? These images show exactly what I want to build:

I almost did it using TabView, but it's definitely not the way to go. I can't match the styles to the one like in the images, etc.

What component should I use to achieve this result?

答: There is no component to create something like that in {N} but there is available plugin you can use. Please see https://www.npmjs.com/package/nativescript-slides</p>


问:
Formatted elapsed time in C
I'm writing a function that, among other things, must print out an elapsed time counter. It receives by reference a start time _start, and compares it to current, both typed as time_t. I want to use strftime() to print out the observed time delta in ISO 8601 format. Here's what I attempted to do:

```<code>// Negative start time implies program has not begun
if (*_start > 0) {
    time_t elapsed = current - *_start;
    strftime(time_str, sizeof(time_str) - 1, "%T", localtime(&elapsed));
    printf("%s\n", time_str);
}
</code>```

And here is the output I get immediately after running the program

```<code>01:00:00
01:00:00
01:00:01
01:00:01
01:00:01
</code>```

The seconds work fine, if I let it run longer they get incremented as expected, so do the minutes, however the hour starts as 01 as opposed to 00. Why is this happening? How can I get the hours to start zeroed, like the minutes?

答:
I realize this question already has an answer, but I thought I might shift the focus a little and expand on the accepted answer. Since the OP specified that they are dealing with elapsed times, one can avoid dealing with absolute timestamps altogether using the clock() function.

```<code>clock_t start = clock();
.
.
clock_t end = clock();
double elapsed = (end - start) / (double)CLOCKS_PER_SEC;
</code>```

then you can call the notionally revised format_elapsed_time() function, like so:

```<code>void format_elapsed_time(char *time_str, double elapsed) {
    int h, m, s, ms;

    h = m = s = ms = 0;
    ms = elapsed * 1000; // promote the fractional part to milliseconds
    h = ms / 3600000;
    ms -= (h * 3600000);
    m = ms / 60000;
    ms -= (m * 60000);
    s = ms / 1000;
    ms -= (s * 1000);
    sprintf(time_str, "%02i:%02i:%02i.%03i", h, m, s, ms);
}
</code>```

Title: Formatted elapsed time in C

Body:
I'm writing a function that, among other things, must print out an elapsed time counter. It receives by reference a start time _start, and compares it to current, both typed as time_t. I want to use strftime() to print out the observed time delta in ISO 8601 format. Here's what I attempted to do:

// Negative start time implies program has not begun
if (*_start > 0) {
    time_t elapsed = current - *_start;
    strftime(time_str, sizeof(time_str) - 1, "%T", localtime(&elapsed));
    printf("%s\n", time_str);
}

And here is the output I get immediately after running the program

01:00:00
01:00:00
01:00:01
01:00:01
01:00:01

The seconds work fine, if I let it run longer they get incremented as expected, so do the minutes, however the hour starts as 01 as opposed to 00. Why is this happening? How can I get the hours to start zeroed, like the minutes?

Body:
I realize this question already has an answer, but I thought I might shift the focus a little and expand on the accepted answer. Since the OP specified that they are dealing with elapsed times, one can avoid dealing with absolute timestamps altogether using the clock() function.

clock_t start = clock();
.
.
clock_t end = clock();
double elapsed = (end - start) / (double)CLOCKS_PER_SEC;

then you can call the notionally revised format_elapsed_time() function, like so:

void format_elapsed_time(char *time_str, double elapsed) {
    int h, m, s, ms;

    h = m = s = ms = 0;
    ms = elapsed * 1000; // promote the fractional part to milliseconds
    h = ms / 3600000;
    ms -= (h * 3600000);
    m = ms / 60000;
    ms -= (m * 60000);
    s = ms / 1000;
    ms -= (s * 1000);
    sprintf(time_str, "%02i:%02i:%02i.%03i", h, m, s, ms);
}


问:
<identifier> expected in HackerRank code
I have been trying this code on hackerRank, and I get the following error.

```<code>Solution.java:36: error: <identifier> expected
  System.out.print(ans);
                  ^
Solution.java:36: error: <identifier> expected
  System.out.print(ans);
                      ^
2 errors
</code>```

code:

```<code>import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
  int n = scan.nextInt();
  scan.close();
  String ans="";

  // if 'n' is NOT evenly divisible by 2 (i.e.: n is odd)
  if(n%2==1){
     ans = "Weird";
  }

   else if (n%2==0)//even no
       {
       if(n>2 && n<=5)
      ans="Not Wierd";
       }

        if(n>6 && n<20)
            {
               ans="Wierd";
             }
        else
        {
     ans="Not Wierd";
           }

  }
  System.out.print(ans);
}
</code>```

What is my mistake?

答:
You need to indent your code properly. Then you can see clearly structure of blocks. Your System.out outside the main method. cut that line and paste it in one }.

If you look at the same code properly indented at a glance you will understand whats happening, like below:

```<code>public class B {
    if(n%2==1){
        ans = "Weird";
    }else if (n%2==0){//even no
        if(n>2 && n<=5)
            ans="Not Wierd";
    }

    if(n>6 && n<20){
        ans="Wierd";
    }else{
        ans="Not Wierd";
    }

    System.out.println(ans);
}
</code>```

Body:
I have been trying this code on hackerRank, and I get the following error.

Solution.java:36: error: <identifier> expected
  System.out.print(ans);
                  ^
Solution.java:36: error: <identifier> expected
  System.out.print(ans);
                      ^
2 errors

code:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
  int n = scan.nextInt();
  scan.close();
  String ans="";

  // if 'n' is NOT evenly divisible by 2 (i.e.: n is odd)
  if(n%2==1){
     ans = "Weird";
  }

   else if (n%2==0)//even no
       {
       if(n>2 && n<=5)
      ans="Not Wierd";
       }

        if(n>6 && n<20)
            {
               ans="Wierd";
             }
        else
        {
     ans="Not Wierd";
           }

  }
  System.out.print(ans);
}

What is my mistake?

Body:
You need to indent your code properly. Then you can see clearly structure of blocks. Your System.out outside the main method. cut that line and paste it in one }.

If you look at the same code properly indented at a glance you will understand whats happening, like below:

public class B {
    if(n%2==1){
        ans = "Weird";
    }else if (n%2==0){//even no
        if(n>2 && n<=5)
            ans="Not Wierd";
    }

    if(n>6 && n<20){
        ans="Wierd";
    }else{
        ans="Not Wierd";
    }

    System.out.println(ans);
}


问:
fatal: bad revision 'bc3c10d5ba0428b17e7da14e80339b8a621a067d
Each time I attempt to commit to my GIT repo using WebStorm I get the following

```<code>fatal: bad revision 'bc3c10d5ba0428b17e7da14e80339b8a621a067d:registration/age/age-olp.component.ts'
</code>```

For each file that an attempt to commit is made the revision is the same but the file name changes.

There are no other .git repo in my application folder.

I have looked at some help in stack but none helps.

Is there a way to correct this? I can't remember doing anything unusual.

答:
In that case, start first to:

switch to command line

make sure you are using the latest Git 2.13

check git status to see if your repo is correctly checked out to a valid branch

Also try and see if the issue persists on a new clone of the same repo (cloned in a different folder): if you can make a commit there, chances are you will be able to report your work from your defective local repo to that new one, and push from the new cloned repo.

Body:
Each time I attempt to commit to my GIT repo using WebStorm I get the following

fatal: bad revision 'bc3c10d5ba0428b17e7da14e80339b8a621a067d:registration/age/age-olp.component.ts'

For each file that an attempt to commit is made the revision is the same but the file name changes.

There are no other .git repo in my application folder.

I have looked at some help in stack but none helps.

Is there a way to correct this? I can't remember doing anything unusual.


问:
Disabling url() check in css-loader
I have a React project with Leaflet 1.0.3 in it. On building with Webpack which uses css-loader, I get:

```
ERROR in ./~/css-loader!./~/leaflet/dist/leaflet.css
Module not found: Error: Can't resolve './images/layers.png' in '/home/tim/work/portal/node_modules/leaflet/dist'
resolve './images/layers.png' in '/home/tim/work/portal/node_modules/leaflet/dist'
  using description file: /home/tim/work/portal/node_modules/leaflet/package.json (relative path: ./dist)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: /home/tim/work/portal/node_modules/leaflet/package.json (relative path: ./dist)
    using description file: /home/tim/work/portal/node_modules/leaflet/package.json (relative path: ./dist/images/layers.png)
      as directory
        /home/tim/work/portal/node_modules/leaflet/dist/images/layers.png doesn't exist
      no extension
        Field 'browser' doesn't contain a valid alias configuration
        /home/tim/work/portal/node_modules/leaflet/dist/images/layers.png doesn't exist
      .js
        Field 'browser' doesn't contain a valid alias configuration
        /home/tim/work/portal/node_modules/leaflet/dist/images/layers.png.js doesn't exist
```

This appears to be because there is a relative image path used in the leaflet.css. I have tried to turn off the css-loader checks with:

```
{
        test: /\.css$/,
        exclude: [/node_modules/, /sanitize/],
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              url: false, // leaflet uses relative paths
              minimize: false,
              modules: false,
            }
          }
        ]
      },
```

but the documented options do not apparently work.

答:
I can also verify that under windows at least

yarn add leaflet

does not correctly install the leaflet dependency in node_modules -missing images folder. However if you stick with NPM you should be fine.

npm install --save leaflet

Title: Disabling url() check in css-loader

Body:
I have a React project with Leaflet 1.0.3 in it. On building with Webpack which uses css-loader, I get:

ERROR in ./~/css-loader!./~/leaflet/dist/leaflet.css
Module not found: Error: Can't resolve './images/layers.png' in '/home/tim/work/portal/node_modules/leaflet/dist'
resolve './images/layers.png' in '/home/tim/work/portal/node_modules/leaflet/dist'
  using description file: /home/tim/work/portal/node_modules/leaflet/package.json (relative path: ./dist)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: /home/tim/work/portal/node_modules/leaflet/package.json (relative path: ./dist)
    using description file: /home/tim/work/portal/node_modules/leaflet/package.json (relative path: ./dist/images/layers.png)
      as directory
        /home/tim/work/portal/node_modules/leaflet/dist/images/layers.png doesn't exist
      no extension
        Field 'browser' doesn't contain a valid alias configuration
        /home/tim/work/portal/node_modules/leaflet/dist/images/layers.png doesn't exist
      .js
        Field 'browser' doesn't contain a valid alias configuration
        /home/tim/work/portal/node_modules/leaflet/dist/images/layers.png.js doesn't exist

This appears to be because there is a relative image path used in the leaflet.css. I have tried to turn off the css-loader checks with:

{
        test: /\.css$/,
        exclude: [/node_modules/, /sanitize/],
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              url: false, // leaflet uses relative paths
              minimize: false,
              modules: false,
            }
          }
        ]
      },

but the documented options do not apparently work.