问:
loop posting ajax results until they are all posted
the below code works great for displaying in my first file

```<code>$.ajax({
    url : "http://localhost/website/files/userstuff/files/",
    asynch : false,
    cache : false,
    success: function (data) {
        $(data).find("a").each(function(i, el) {
            var val = $(el).attr('href');
            if (val.match(/\.(pdf|doc|docx|txt|html|js|css|rar|7zip)$/)) {
                var fileslocation = ("http://localhost/website/files/userstuff/files/" + val)
                var displayfilestable = ("<table><thead><tr><th>Files</th></tr></table>");
                var adddata = ("<tr><td><a href='"+ fileslocation +"'target='_blank'>"+ val +"</td></tr>");
                $("#filestable").html(displayfilestable)
                $("filestable, table").append(adddata);
                console.log(adddata)
            }
        });
    }
});
</code>```

this code will as you would think pull and display the files in the table row, however it is only performing this for the first file it finds I was wondering if anyone here could help get this to display all of the files in the files folder in the table. thanks in advance

enter image description here

答:
Your code just works fine. The problems is, in that loop (each) you keep re-create table. That why it show only 1 data. Check my example based on your code.

HTML

```<code> <div>
<a href="sad1.pdf">sad1.pdf</a><br>
<a href="sad2.pdf">sad2.pdf</a><br>
<a href="sad3.pdf">sad3.pdf</a>

<div id="filestable"></div>
</div>
</code>```

JAVASCRIPT

```<code>var displayfilestable = ("<table><thead><tr><th>Files</th></tr></table>");
$("#filestable").html(displayfilestable);
$("DIV").find("a").each(function(i, el) { // this is your data
    var val = $(el).attr('href');
    if (val.match(/\.(pdf|doc|docx|txt|html|js|css|rar|7zip)$/)) {
        var fileslocation = ("http://localhost/website/files/userstuff/files/" + val)
        var adddata = ("<tr><td><a href='"+ fileslocation +"'target='_blank'>"+ val +"</td></tr>");
        $("filestable, table").append(adddata);
                console.log(adddata)
    }
 });
</code>```

AND Jsfiddle here :https://jsfiddle.net/synz/yrag1zpr/

Body:
the below code works great for displaying in my first file

$.ajax({
    url : "http://localhost/website/files/userstuff/files/",
    asynch : false,
    cache : false,
    success: function (data) {
        $(data).find("a").each(function(i, el) {
            var val = $(el).attr('href');
            if (val.match(/\.(pdf|doc|docx|txt|html|js|css|rar|7zip)$/)) {
                var fileslocation = ("http://localhost/website/files/userstuff/files/" + val)
                var displayfilestable = ("

Files

");
                var adddata = ("
"+ val +"
");
                $("#filestable").html(displayfilestable)
                $("filestable, table").append(adddata);
                console.log(adddata)
            }
        });
    }
});

this code will as you would think pull and display the files in the table row, however it is only performing this for the first file it finds I was wondering if anyone here could help get this to display all of the files in the files folder in the table. thanks in advance

enter image description here

Body:
Your code just works fine. The problems is, in that loop (each) you keep re-create table. That why it show only 1 data. Check my example based on your code.

HTML

 <div>
<a href="sad1.pdf">sad1.pdf</a><br>
<a href="sad2.pdf">sad2.pdf</a><br>
<a href="sad3.pdf">sad3.pdf</a>

<div id="filestable"></div>
</div>

JAVASCRIPT

var displayfilestable = ("<table><thead><tr><th>Files</th></tr></table>");
$("#filestable").html(displayfilestable);
$("DIV").find("a").each(function(i, el) { // this is your data
    var val = $(el).attr('href');
    if (val.match(/\.(pdf|doc|docx|txt|html|js|css|rar|7zip)$/)) {
        var fileslocation = ("http://localhost/website/files/userstuff/files/" + val)
        var adddata = ("<tr><td><a href='"+ fileslocation +"'target='_blank'>"+ val +"</td></tr>");
        $("filestable, table").append(adddata);
                console.log(adddata)
    }
 });

AND Jsfiddle here :https://jsfiddle.net/synz/yrag1zpr/


来源: stackexchange

问:
Python dict subclass instance behaving different from dict instance
I recently noticed in Python that if I create a dict subclass I can add attributes, however this isn't the case with instances of dict. I.E:</p>

```<code>class aDict(dict):
    pass

myDict = aDict({"name" : "A"})

myDict.color = "red"

print(myDict.color) #"red"

myOtherDict = dict({"name" : "B"})
myOtherDict.color = "green" #"AttributeError: 'dict' object has no attribute color"
</code>```

答:
You are interacting with myDict's
__dict__ which is the attribute dictionary given to an object, this is different to the myOtherDict which is the inbuilt dictionary. You can see the difference with how you interact with these by trying:

```<code>dir(myDict)
dir(myOtherDict)
</code>```

and you can see what is accessible via myDict's dict attribute (and compare it with the lack of attribute on myOtherDict via vars()

```<code>vars(myDict)
vars(myOtherDict)
</code>```

There's some more information available here and here that helped me to understand your problem.

ContentLicense: CC BY-SA 3.0

Body:
I recently noticed in Python that if I create a dict subclass I can add attributes, however this isn't the case with instances of dict. I.E:

class aDict(dict):
    pass

myDict = aDict({"name" : "A"})

myDict.color = "red"

print(myDict.color) #"red"

myOtherDict = dict({"name" : "B"})
myOtherDict.color = "green" #"AttributeError: 'dict' object has no attribute color"

Body:
You are interacting with myDict's
__dict__ which is the attribute dictionary given to an object, this is different to the myOtherDict which is the inbuilt dictionary. You can see the difference with how you interact with these by trying:

dir(myDict)
dir(myOtherDict)

and you can see what is accessible via myDict's dict attribute (and compare it with the lack of attribute on myOtherDict via vars()

vars(myDict)
vars(myOtherDict)

There's some more information available here and here that helped me to understand your problem.


问:
How can we achieve product filter page using angularjs with multi selection of checkboxes?
I have created a tabular page in which i need to filter the table with filters using a left side facets boxes of different category but with multi-selection options and i need to use Angularjs for this requirement.

I need to check/uncheck using the clear filter selection .

Any helping library can help to achieve the same or we need to do some logic around the checkboxes to achieve this.

My checkbox code looks like this:

```<code> <div class="col-sm-2" style="padding-top: 10px; padding-bottom: 20px;">
                <div class="facetBx sltBx" ng-show="tabFilters.length > 0">
                    <p class="facetBxTitle"><i class="fa fa-filter"></i> Filter Selection
                        <a class="clrSlt" ng-click="clearAllFilters();">Clear</a>
                    </p>

                    <div class="facetBxChld" id="uRslctn">

                        <ul>
                            <li ng-repeat="item in tabFilters">

                                <div class="crop">
                                    <strong title="{{item}}">{{item}}</strong>
                                </div>
                                <i class="fa fa-remove rmvThs" style="font-size: 14px;color:#000;float: right;" ng-click="checkItem(item, item,false);"></i>
                            </li>
                        </ul>
                    </div>
                </div>
                <div class="facetBx" ng-repeat="item in filters">
                    <p class="facetBxTitle bomtype">{{item.label}}</p>

                    <div class="facetBxChld" id="bomFacet">
                        <ul class="multiselect" style="max-height: 140px;overflow-y: auto;">
                            <li ng-repeat="(k,v) in item.values">
                                <input type="checkbox" ng-model='isSelected' ng-click='checkItem(item.name, k, isSelected)'>
                                <span> {{k}} ({{v}})</span>
                            </li>
                            <li ng-show="value.length == 0">
                                No Data Available.
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
</code>```

Below website are the reference of the code which i am trying to build:

www.jabong.com

The UI(HTML) is done but i am facing the trouble in the maintaining the checking and un-checking of the checkboxes which are not clearing off.

I believe i need to code something in the ng-model of checkbox to achieve it but i am not able to be successfull so need help on the same.

Sample Plunkur for the same:

enter link description here

Thanks in advance.

答:
You should try 'ng-change' on checkboxes to trigger a method which changes the values according to checked and unchecked checkboxes.

For Ex.

```<code><input type="checkbox" ng-model='isSelected' ng-click='checkItem(key, k, isSelected)' ng-change="yourMethodHere()">
</code>```

in JS:

```<code>$scope.yourMethodHere = function() {
  if (isSelected) {
    // filter the values here
  } else {
    // non filtered values
  }
}
</code>```

By doing this you do not need to even maintain the values of exiting checked/unchecked checkbox.

Body:
I have created a tabular page in which i need to filter the table with filters using a left side facets boxes of different category but with multi-selection options and i need to use Angularjs for this requirement.

I need to check/uncheck using the clear filter selection .

Any helping library can help to achieve the same or we need to do some logic around the checkboxes to achieve this.

My checkbox code looks like this:

 0">

 Filter Selection
                        Clear

                                    {{item}}

{{item.label}}

                                <input type="checkbox" ng-model='isSelected' ng-click='checkItem(item.name, k, isSelected)'>
                                 {{k}} ({{v}})

                                No Data Available.

Below website are the reference of the code which i am trying to build:

www.jabong.com

The UI(HTML) is done but i am facing the trouble in the maintaining the checking and un-checking of the checkboxes which are not clearing off.

I believe i need to code something in the ng-model of checkbox to achieve it but i am not able to be successfull so need help on the same.

Sample Plunkur for the same:

enter link description here

Thanks in advance.

Body:
You should try 'ng-change' on checkboxes to trigger a method which changes the values according to checked and unchecked checkboxes.

For Ex.

<input type="checkbox" ng-model='isSelected' ng-click='checkItem(key, k, isSelected)' ng-change="yourMethodHere()">

in JS:

$scope.yourMethodHere = function() {
  if (isSelected) {
    // filter the values here
  } else {
    // non filtered values
  }
}

By doing this you do not need to even maintain the values of exiting checked/unchecked checkbox.


问:
How to update ListView without freezing the program
So I have a list of strings (ISBNs), and I need to fill a listview with the objects (Book objects) associated with these strings. The problem is that the function I have to get the Book object using the string takes time, and so to get, say 30 books, the wait approaches 4 or 5 seconds.

One approach I've thought of is to get the Book objects one at a time, and to add them to the list as I get them. But this process will freeze the UI until it's done adding them all. If I try to put this process in a new thread, it won't let me add to the any UI objects (since it's from another thread). If I try to put it in an AsyncTask, I can't access the ListView since it's in the MainActivity class.

There must be a way to dynamically update a UI element, I'm sure I've seen it done. Any suggestions?

EDIT:

This is the code I'm using to actually add items to the list:

```<code>//List view and adapter setup
listView = (ListView) findViewById(R.id.listViewCheckout);
bookAdapter = new SearchBookAdapter(getApplicationContext(), R.layout.search_row_layout);
listView.setAdapter(bookAdapter);

for(int i = 0; i < searches.size(); i++) {

    //Get the book
    Book book = BackendFunctions.getBookFromISBN(fbSnapshot, searches.get(i));

    //Assign data to the adapter variables
    Bitmap cover = book.getCover();
    String title = book.getTitle();
    String author = book.getAuthor();

    //Add data to the adapter and set the list
    SearchBookDataProvider dataProvider = new SearchBookDataProvider(cover, title, author);
    bookAdapter.add(dataProvider);
    bookAdapter.notifyDataSetChanged();
}
</code>```

答:
You can get the list of the books in a Thread and send a Broadcast with the data received.
Register a broadcast receiver in your MainActivity class and update the Adapter in the receiver. That should not freeze the UI.

EDIT -

```<code>  BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Book book = (Book)intent.getSerializableExtra("Book");
        SearchBookDataProvider dataProvider = new SearchBookDataProvider(cover, title, author);
        bookAdapter.add(dataProvider);
        bookAdapter.notifyDataSetChanged();
    }
};

Thread thread = new Thread(){
    @Override
    public void run()
    {
        for(int i = 0; i < searches.size(); i++) {

            //Get the book
            Book book = BackendFunctions.getBookFromISBN(fbSnapshot, searches.get(i));

            Intent intent = new Intent();
            intent.setAction("Book Received");
            intent.putExtra("Book",book);
            sendBroadcast(intent);
        }
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listView = (ListView) findViewById(R.id.listView);
    listView.setAdapter(bookAdapter);
    registerReceiver(broadcastReceiver,new IntentFilter("Book Received"));
    thread.start();

}
</code>```

Body:
So I have a list of strings (ISBNs), and I need to fill a listview with the objects (Book objects) associated with these strings. The problem is that the function I have to get the Book object using the string takes time, and so to get, say 30 books, the wait approaches 4 or 5 seconds.

One approach I've thought of is to get the Book objects one at a time, and to add them to the list as I get them. But this process will freeze the UI until it's done adding them all. If I try to put this process in a new thread, it won't let me add to the any UI objects (since it's from another thread). If I try to put it in an AsyncTask, I can't access the ListView since it's in the MainActivity class.

There must be a way to dynamically update a UI element, I'm sure I've seen it done. Any suggestions?

EDIT:

This is the code I'm using to actually add items to the list:

//List view and adapter setup
listView = (ListView) findViewById(R.id.listViewCheckout);
bookAdapter = new SearchBookAdapter(getApplicationContext(), R.layout.search_row_layout);
listView.setAdapter(bookAdapter);

for(int i = 0; i < searches.size(); i++) {

    //Get the book
    Book book = BackendFunctions.getBookFromISBN(fbSnapshot, searches.get(i));

    //Assign data to the adapter variables
    Bitmap cover = book.getCover();
    String title = book.getTitle();
    String author = book.getAuthor();

    //Add data to the adapter and set the list
    SearchBookDataProvider dataProvider = new SearchBookDataProvider(cover, title, author);
    bookAdapter.add(dataProvider);
    bookAdapter.notifyDataSetChanged();
}

Body:
You can get the list of the books in a Thread and send a Broadcast with the data received.
Register a broadcast receiver in your MainActivity class and update the Adapter in the receiver. That should not freeze the UI.

EDIT -

  BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Book book = (Book)intent.getSerializableExtra("Book");
        SearchBookDataProvider dataProvider = new SearchBookDataProvider(cover, title, author);
        bookAdapter.add(dataProvider);
        bookAdapter.notifyDataSetChanged();
    }
};

Thread thread = new Thread(){
    @Override
    public void run()
    {
        for(int i = 0; i < searches.size(); i++) {

            //Get the book
            Book book = BackendFunctions.getBookFromISBN(fbSnapshot, searches.get(i));

            Intent intent = new Intent();
            intent.setAction("Book Received");
            intent.putExtra("Book",book);
            sendBroadcast(intent);
        }
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listView = (ListView) findViewById(R.id.listView);
    listView.setAdapter(bookAdapter);
    registerReceiver(broadcastReceiver,new IntentFilter("Book Received"));
    thread.start();

}


问:
Installing Multiple Versions Of A Windows Service On The Same PC
I have a .NET 3.5 Windows Service that comes in several different configurations/flavours ie. Release, Test, Debug etc.  I've created an installer package for the service which is built as part of an msbuild script, but I need to be able to build the installers in a way which would allow each flavour of the service to be installed on the same machine.  Does anyone know the best way to do this?

Thanks

答:
Just wanted to draw attention to the comments in the article Cody gray references.  It seems that the author and a commenter agreed that there was an easier method using sc.exe as follows</p>

```<code>sc \\myserver create NewService binpath= c:\nt\system32\NewServ.exe
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Just wanted to draw attention to the comments in the article Cody gray references.  It seems that the author and a commenter agreed that there was an easier method using sc.exe as follows

sc \\myserver create NewService binpath= c:\nt\system32\NewServ.exe


问:
Stuck on login page after re-styling of login form using css and js
I know there was a similar question posted before and I already go through it, here's the link Login code doesn't work, stay stuck on log in page but our code is totally different and I already go through it for 3 hours but come with no solution. Here's what my code initially look like before I style it.

<?php
 require('db.php');
 session_start();
    // If form submitted, insert values into the database.
    if (isset($_POST['username'])){

  $username = stripslashes($_REQUEST['username']); // removes backslashes
  $username = mysqli_real_escape_string($con,$username); //escapes special characters in a string
  $password = stripslashes($_REQUEST['password']);
  $password = mysqli_real_escape_string($con,$password);

 //Checking is user existing in the database or not
        $query = "SELECT * FROM `users` WHERE username='$username' and password='".md5($password)."'";
  $result = mysqli_query($con,$query) or die(mysql_error());
  $rows = mysqli_num_rows($result);
        if($rows==1){
   $_SESSION['username'] = $username;
   header("Location:../user/page/emergency.php"); // Redirect user to index.php
            }else{
    echo "

Username/password is incorrect.

Click here to Login
";
    }
    }else{
?>

Log In

<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" required />
<input type="password" name="password" placeholder="Password" required />
<input name="submit" type="submit" value="Login" />
</form>

<?php } ?>

```
</div>
</div>
</p>

<p>and here is what it look like after I try to style it using css and javascript.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

<h2> Selamat Datang, Sila Log Masuk Untuk Kemaskini</h2>

<?php
 require('db.php');
 session_start();
    // If form submitted, insert values into the database.
    if (isset($_POST['username'])){

  $username = stripslashes($_REQUEST['username']); // removes backslashes
  $username = mysqli_real_escape_string($con,$username); //escapes special characters in a string
  $password = stripslashes($_REQUEST['password']);
  $password = mysqli_real_escape_string($con,$password);

 //Checking is user existing in the database or not
        $query = "SELECT * FROM `users` WHERE username='$username' and password='".md5($password)."'";
  $result = mysqli_query($con,$query) or die(mysql_error());
  $rows = mysqli_num_rows($result);
        if($rows==1){
   $_SESSION['username'] = $username;
   header("Location:../user/page/emergency.php"); // direct user to update page
            }else{
    echo "<div class='form'><h3>Username/password is incorrect.</h3><br/>Click here to Login</div>";
    }
    }else{
?>
 <div class="container">
 <section id="content">
  <form action="" method="post" name="login">
   <h1>Daftar Masuk</h1>

   <div>
   <input type="text" placeholder= "Username" required ="" id ="username"/>
   </div>

   <div>
   <input type="password" placeholder= "Password" required ="" id ="password"/>
   </div>

     <input name="submit" type="submit" value="Login" />

   </form>
  </section>
 </div>
<?php } ?>
  <script  src="js/index.js"></script>

</body></code>```

and once I style it, the form stay stuck on the login page. Help me, what should I do? Any suggestion and guidance is greatly appreciated.

updated:

okay guys, I found the source of the problem already, I just need to remove  on the second form.

答:
Turns out, on the form where I do my styling, I just need to remove the  tag

so from

  <form action="" method="post" name="login">

Daftar Masuk

   <input type="text" placeholder= "Username" required ="" id ="username"/>

   <input type="password" placeholder= "Password" required ="" id ="password"/>

     <input name="submit" type="submit" value="Login" />

   </form>

```
</div>
</div>
</p>

<p>to</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
 <section id="content">
  <form action="" method="post" name="login">
   <h1>Daftar Masuk</h1>

   <input type="text" placeholder= "Username" required ="" id ="username"/>

   <input type="password" placeholder= "Password" required ="" id ="password"/>

     <input name="submit" type="submit" value="Login" />

   </form>
  </section>
 </div></code>```

Body:
I know there was a similar question posted before and I already go through it, here's the link Login code doesn't work, stay stuck on log in page but our code is totally different and I already go through it for 3 hours but come with no solution. Here's what my code initially look like before I style it.

<?php
 require('db.php');
 session_start();
    // If form submitted, insert values into the database.
    if (isset($_POST['username'])){

  $username = stripslashes($_REQUEST['username']); // removes backslashes
  $username = mysqli_real_escape_string($con,$username); //escapes special characters in a string
  $password = stripslashes($_REQUEST['password']);
  $password = mysqli_real_escape_string($con,$password);

 //Checking is user existing in the database or not
        $query = "SELECT * FROM `users` WHERE username='$username' and password='".md5($password)."'";
  $result = mysqli_query($con,$query) or die(mysql_error());
  $rows = mysqli_num_rows($result);
        if($rows==1){
   $_SESSION['username'] = $username;
   header("Location:../user/page/emergency.php"); // Redirect user to index.php
            }else{
    echo "

Username/password is incorrect.

Click here to Login
";
    }
    }else{
?>

Log In

<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" required />
<input type="password" name="password" placeholder="Password" required />
<input name="submit" type="submit" value="Login" />
</form>

<?php } ?>

and here is what it look like after I try to style it using css and javascript.

 Selamat Datang, Sila Log Masuk Untuk Kemaskini

<?php
 require('db.php');
 session_start();
    // If form submitted, insert values into the database.
    if (isset($_POST['username'])){

  $username = stripslashes($_REQUEST['username']); // removes backslashes
  $username = mysqli_real_escape_string($con,$username); //escapes special characters in a string
  $password = stripslashes($_REQUEST['password']);
  $password = mysqli_real_escape_string($con,$password);

 //Checking is user existing in the database or not
        $query = "SELECT * FROM `users` WHERE username='$username' and password='".md5($password)."'";
  $result = mysqli_query($con,$query) or die(mysql_error());
  $rows = mysqli_num_rows($result);
        if($rows==1){
   $_SESSION['username'] = $username;
   header("Location:../user/page/emergency.php"); // direct user to update page
            }else{
    echo "

Username/password is incorrect.

Click here to Login
";
    }
    }else{
?>

  <form action="" method="post" name="login">

Daftar Masuk

   <input type="text" placeholder= "Username" required ="" id ="username"/>

   <input type="password" placeholder= "Password" required ="" id ="password"/>

     <input name="submit" type="submit" value="Login" />

   </form>

<?php } ?>

and once I style it, the form stay stuck on the login page. Help me, what should I do? Any suggestion and guidance is greatly appreciated.

updated:

okay guys, I found the source of the problem already, I just need to remove  on the second form.

Body:
Turns out, on the form where I do my styling, I just need to remove the  tag

so from

<div class="container">
 <section id="content">
  <form action="" method="post" name="login">
   <h1>Daftar Masuk</h1>

   <div>
   <input type="text" placeholder= "Username" required ="" id ="username"/>
   </div>

   <div>
   <input type="password" placeholder= "Password" required ="" id ="password"/>
   </div>

     <input name="submit" type="submit" value="Login" />

   </form>
  </section>
 </div>

to

<div class="container">
 <section id="content">
  <form action="" method="post" name="login">
   <h1>Daftar Masuk</h1>

   <input type="text" placeholder= "Username" required ="" id ="username"/>

   <input type="password" placeholder= "Password" required ="" id ="password"/>

     <input name="submit" type="submit" value="Login" />

   </form>
  </section>
 </div>


问:
How to clear ListView on Fragment when back button pressed?
All data from that ListView is provided by a CursorAdapter.
Whenever I pressed back button and return to activity, then click on the activity to start my fragment, all previous data still there stacking on top of each other.

答: Make public a method in fragment which will clear your list and call that method from its parent activity's On onBackPressed using fragment's instance.


问:
MYSql query to find booking available in hotel management system
I am working on a sample project "Hotel Management System". Here I have created two tables.

tbl_room

|roomid|roomno|

and

tbl_booking

|bookingid|roomid|checkin|checkout|

I have created a query
I get $indate and $outdate from the form.

```<code>$sql="SELECT roomid from tbl_room
      where tbl_room.roomid not in (select roomid from tbl_booking where
      checkout>'$indate' )";
</code>```

This query doesn't work. It only checks the checkout date and i cannot book the previous date.

答:
```<code> $sql="SELECT * FROM tbl_room WHERE roomid not in (SELECT b.roomid FROM tbl_booking b
 where(b.checkout BETWEEN '$checkin' and '$checkout') and
 (b.checkin BETWEEN '$checkin' and '$checkout'))";
</code>```

Finally, This query Worked.

Body:
I am working on a sample project "Hotel Management System". Here I have created two tables.

tbl_room

|roomid|roomno|

and

tbl_booking

|bookingid|roomid|checkin|checkout|

I have created a query
I get $indate and $outdate from the form.

$sql="SELECT roomid from tbl_room
      where tbl_room.roomid not in (select roomid from tbl_booking where
      checkout>'$indate' )";

This query doesn't work. It only checks the checkout date and i cannot book the previous date.

Body:
 $sql="SELECT * FROM tbl_room WHERE roomid not in (SELECT b.roomid FROM tbl_booking b
 where(b.checkout BETWEEN '$checkin' and '$checkout') and
 (b.checkin BETWEEN '$checkin' and '$checkout'))";

Finally, This query Worked.


问:
Using Thrift for offline serialisation?
I use Apache Thrift protocol for tablet-server and interlanguage integration, and all is OK few years.

Integration is between languages (C#/C++/PC Java/Dalvik Java) and thrift is probably one of simplest and safest. So I want pack-repack sophisticated data structures (and changed over years) with Thrift library. Lets say in thrift terms kind of OfflineTransport or OfflineProtocol.

Scenario:

I want to make backup solution, for example during internet provider failure process data in offline mode: serialise, store, try to process in few ways. For example sent serialised data by normal email via poor backup connection etc.

Question is: where in Thrift philosophy is best extension point for me?

I understand, only part of online protocol is possible to backup offline, ie real time return of value is not possible, that is OK.

答:
There is an RPC framework that uses the standard thrift Protocol named "thrifty", and it is the same effect as using thrift IDL to define the service, that is, thrify can be compatible with code that uses thrift IDL, which is very helpful for cross-platform. And has a ThriftSerializer class in it:

```<code>[ThriftStruct]
public class LogEntry
{

    [ThriftConstructor]
    public LogEntry([ThriftField(1)]String category, [ThriftField(2)]String message)
    {
        this.Category = category;
        this.Message = message;
    }

    [ThriftField(1)]
    public String Category { get; }

    [ThriftField(2)]
    public String Message { get; }
}

ThriftSerializer s = new ThriftSerializer(ThriftSerializer.SerializeProtocol.Binary);
byte[] s = s.Serialize<LogEntry>();

s.Deserialize<LogEntry>(s);
</code>```

you can try it:https://github.com/endink/Thrifty

Title: Using Thrift for offline serialisation?

Body:
There is an RPC framework that uses the standard thrift Protocol named "thrifty", and it is the same effect as using thrift IDL to define the service, that is, thrify can be compatible with code that uses thrift IDL, which is very helpful for cross-platform. And has a ThriftSerializer class in it:

[ThriftStruct]
public class LogEntry
{

    [ThriftConstructor]
    public LogEntry([ThriftField(1)]String category, [ThriftField(2)]String message)
    {
        this.Category = category;
        this.Message = message;
    }

    [ThriftField(1)]
    public String Category { get; }

    [ThriftField(2)]
    public String Message { get; }
}

ThriftSerializer s = new ThriftSerializer(ThriftSerializer.SerializeProtocol.Binary);
byte[] s = s.Serialize<LogEntry>();

s.Deserialize<LogEntry>(s);

you can try it:https://github.com/endink/Thrifty


问:
Printing structures using loop
How to print structure contents using for-loop? If pointers, how to assign pointer to structure? I have attached code that I made that makes a structure using data that user inputs, and prints them out in an orderly fashion. My problem is that you have to write a lot of printf() and gets_s() statements to receive and print input. I feel like it would be easier to do this using a for-loop. I tried to make a for-loop as you can see in the code using pointers, but it doesn't compile, and I'm pretty sure that it is the wrong way to assign pointers to structures.

TL;DR: How to print structure contents using for-loop? If pointers, how to assign pointer to structure?

```<code>#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <conio.h>

#define maxName 50
#define maxNation 50
#define maxAge 100

struct astronaut
{
    char firstName[maxName];
    char lastName[maxName];
    char nation[maxNation];
    int age = 0;
    char missionName[maxAge];
    int missionYear[50];
};

int main()
{
    int i = 0;
    struct astronaut candidate1;
    struct astronaut candidate2;
    struct astronaut candidate3;
    struct astronaut mission1;
    struct astronaut mission2;
    struct astronaut mission3;

    printf("Please enter the first name of the candidate: ");
    gets_s(candidate1.firstName);
    printf("Please enter the last name of the candidate: ");
    gets_s(candidate1.lastName);
    printf("Please enter the nationality of the candidate: ");
    gets_s(candidate1.nation);
    printf("Please enter the age of the candidate: ");
    scanf("%d", &candidate1.age);

    printf("Please enter the first name of the candidate: ");
    gets_s(candidate2.firstName);
    printf("Please enter the last name of the candidate: ");
    gets_s(candidate2.lastName);
    printf("Please enter the nationality of the candidate: ");
    gets_s(candidate2.nation);
    printf("Please enter the age of the candidate: ");
    scanf("%d", &candidate2.age);

    printf("Please enter the first name of the candidate: ");
    gets_s(candidate3.firstName);
    printf("Please enter the last name of the candidate: ");
    gets_s(candidate3.lastName);
    printf("Please enter the nationality of the candidate: ");
    gets_s(candidate3.nation);
    printf("Please enter the age of the candidate: ");
    scanf("%d", &candidate3.age);

    printf("Enter a Mission Name: ");
    gets_s(mission1.missionName);
    printf("Enter the year the mission was conducted: ");
    scanf("%d", &mission1.missionYear);

    printf("Enter a Mission Name: ");
    gets_s(mission2.missionName);
    printf("Enter the year the mission was conducted: ");
    scanf("%d", &mission2.missionYear);

    printf("Enter a Mission Name: ");
    gets_s(mission3.missionName);
    printf("Enter the year the mission was conducted: ");
    scanf("%d", &mission3.missionYear);

    struct astronaut *ptr;
    struct candidate *ptr;

//  printf("\n\tAstronaut Candidate Database\n");
//  printf("Name: %s %s \t Age: %d \t Nationality: %s\n",     candidate1.firstName, candidate1.lastName, candidate1.age, candidate1.nation);
//  printf("Name: %s %s \t Age: %d \t Nationality: %s\n",     candidate2.firstName, candidate2.lastName, candidate2.age, candidate2.nation);
//  printf("Name: %s %s \t Age: %d \t Nationality: %s\n",     candidate3.firstName, candidate3.lastName, candidate3.age, candidate3.nation);
//  printf("\n\tAstronaut Mission Database\n");
//  printf("Mission Name: %s \t Year: %d\n", mission1.missionName,     mission1.missionYear);
//  printf("Mission Name: %s \t Year: %d\n", mission2.missionName,     mission2.missionYear);
//  printf("Mission Name: %s \t Year: %d\n", mission3.missionName,     mission3.missionYear);

    for (int index = 0; index < 5; index++)
    {
        printf("Name: %s %s \t Age: %d \t Nationality: %s\n",     *ptr.firstName, *ptr.lastName, *ptr.age, *ptr.nation);
        ptr++;
    }

    _getch();
    return 0;
}
</code>```

答:
I think you need 2 structs. An astronaut and a mission aren't the same thing.  As it is now, you have several unused fields depending on whether you're entering data for an astronaut or a mission.  You could do something like this:

```<code>#include <stdio.h>

#define maxName 50
#define maxNation 50
#define maxAge 100

struct astronaut
{
    char firstName[maxName];
    char lastName[maxName];
    char nation[maxNation];
    int age;
};

struct mission
{
    char missionName[maxAge];
    int missionYear;  // why do you have an array of 50 ints for the missionYear?
};

void enter_candidate_data(struct candidate* cand)
{
    // not famliar with gets_s .. I would use fgets here, you can read the manpage on that if you desire
    printf("Please enter the first name of the candidate: ");
    gets_s(cand->firstName);
    printf("Please enter the last name of the candidate: ");
    gets_s(cand->lastName);
    printf("Please enter the nationality of the candidate: ");
    gets_s(cand->nation);
    printf("Please enter the age of the candidate: ");
    scanf("%d", &(cand->age));
}

void enter_mission_data(struct mission* mis)
{
    printf("Enter a Mission Name: ");
    gets_s(mis->missionName);
    printf("Enter the year the mission was conducted: ");
    scanf("%d", &(mis->missionYear));
}

int main()
{
    int i;
    struct astronaut candidates[3];
    struct mission missions[3];

    for (i=0; i<3; i++)
    {
        enter_candidate_data(&(candidates[i]));
        // you can put this in a separate loop if you want to enter all
        // candidate data first
        enter_mission_data(&(missions[i]));
    }

    // you could also write functions to print the data instead, depends on
    // how you want it all presented

    for (int i=0; i<3; i++)
    {
        printf("Name: %s %s \t Age: %d \t Nationality: %s\n",
            candidates[i].firstName, candidates[i].lastName, candidates[i].nation);
        printf("Mission Name: %s, year %d\n", missions[i].missionName,
            missions[i].missionYear);
    }

    return 0;
}
</code>```

You may want a number of missions (or even just one) associated with a particular astronaut. If so, I would define the data structures like this

```<code>#define MAX_ASTRONAUT_MISSIONS 20

struct mission
{
    char missionName[maxAge];
    int missionYear;
};

struct astronaut
{
    char firstName[maxName];
    char lastName[maxName];
    char nation[maxNation];
    int age;
    struct mission missions[MAX_ASTRONAUT_MISSIONS];
};
</code>```

This will allow you to associate MAX_ASTRONAUT_MISSION missions with each astronaut.  Or, more realistically, a single mission could be associated with several astronauts.  In that case, you may want data structures more like this

```<code>struct mission
{
    char missionName[maxAge];
    int missionYear;
};

struct astronaut
{
    char firstName[maxName];
    char lastName[maxName];
    char nation[maxNation];
    int age;
    // using a pointer to missions will allow you to create one mission, and
    // all the astronauts on that mission could get a pointer to it,
    // designating they were all on that singular mission.
    struct mission* missions[MAX_ASTRONAUT_MISSIONS];
};
</code>```

Title: Printing structures using loop

Body:
How to print structure contents using for-loop? If pointers, how to assign pointer to structure? I have attached code that I made that makes a structure using data that user inputs, and prints them out in an orderly fashion. My problem is that you have to write a lot of printf() and gets_s() statements to receive and print input. I feel like it would be easier to do this using a for-loop. I tried to make a for-loop as you can see in the code using pointers, but it doesn't compile, and I'm pretty sure that it is the wrong way to assign pointers to structures.

TL;DR: How to print structure contents using for-loop? If pointers, how to assign pointer to structure?

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <conio.h>

#define maxName 50
#define maxNation 50
#define maxAge 100

struct astronaut
{
    char firstName[maxName];
    char lastName[maxName];
    char nation[maxNation];
    int age = 0;
    char missionName[maxAge];
    int missionYear[50];
};

int main()
{
    int i = 0;
    struct astronaut candidate1;
    struct astronaut candidate2;
    struct astronaut candidate3;
    struct astronaut mission1;
    struct astronaut mission2;
    struct astronaut mission3;

    printf("Please enter the first name of the candidate: ");
    gets_s(candidate1.firstName);
    printf("Please enter the last name of the candidate: ");
    gets_s(candidate1.lastName);
    printf("Please enter the nationality of the candidate: ");
    gets_s(candidate1.nation);
    printf("Please enter the age of the candidate: ");
    scanf("%d", &candidate1.age);

    printf("Please enter the first name of the candidate: ");
    gets_s(candidate2.firstName);
    printf("Please enter the last name of the candidate: ");
    gets_s(candidate2.lastName);
    printf("Please enter the nationality of the candidate: ");
    gets_s(candidate2.nation);
    printf("Please enter the age of the candidate: ");
    scanf("%d", &candidate2.age);

    printf("Please enter the first name of the candidate: ");
    gets_s(candidate3.firstName);
    printf("Please enter the last name of the candidate: ");
    gets_s(candidate3.lastName);
    printf("Please enter the nationality of the candidate: ");
    gets_s(candidate3.nation);
    printf("Please enter the age of the candidate: ");
    scanf("%d", &candidate3.age);

    printf("Enter a Mission Name: ");
    gets_s(mission1.missionName);
    printf("Enter the year the mission was conducted: ");
    scanf("%d", &mission1.missionYear);

    printf("Enter a Mission Name: ");
    gets_s(mission2.missionName);
    printf("Enter the year the mission was conducted: ");
    scanf("%d", &mission2.missionYear);

    printf("Enter a Mission Name: ");
    gets_s(mission3.missionName);
    printf("Enter the year the mission was conducted: ");
    scanf("%d", &mission3.missionYear);

    struct astronaut *ptr;
    struct candidate *ptr;

//  printf("\n\tAstronaut Candidate Database\n");
//  printf("Name: %s %s \t Age: %d \t Nationality: %s\n",     candidate1.firstName, candidate1.lastName, candidate1.age, candidate1.nation);
//  printf("Name: %s %s \t Age: %d \t Nationality: %s\n",     candidate2.firstName, candidate2.lastName, candidate2.age, candidate2.nation);
//  printf("Name: %s %s \t Age: %d \t Nationality: %s\n",     candidate3.firstName, candidate3.lastName, candidate3.age, candidate3.nation);
//  printf("\n\tAstronaut Mission Database\n");
//  printf("Mission Name: %s \t Year: %d\n", mission1.missionName,     mission1.missionYear);
//  printf("Mission Name: %s \t Year: %d\n", mission2.missionName,     mission2.missionYear);
//  printf("Mission Name: %s \t Year: %d\n", mission3.missionName,     mission3.missionYear);

    for (int index = 0; index < 5; index++)
    {
        printf("Name: %s %s \t Age: %d \t Nationality: %s\n",     *ptr.firstName, *ptr.lastName, *ptr.age, *ptr.nation);
        ptr++;
    }

    _getch();
    return 0;
}

Body:
I think you need 2 structs. An astronaut and a mission aren't the same thing.  As it is now, you have several unused fields depending on whether you're entering data for an astronaut or a mission.  You could do something like this:

#include <stdio.h>

#define maxName 50
#define maxNation 50
#define maxAge 100

struct astronaut
{
    char firstName[maxName];
    char lastName[maxName];
    char nation[maxNation];
    int age;
};

struct mission
{
    char missionName[maxAge];
    int missionYear;  // why do you have an array of 50 ints for the missionYear?
};

void enter_candidate_data(struct candidate* cand)
{
    // not famliar with gets_s .. I would use fgets here, you can read the manpage on that if you desire
    printf("Please enter the first name of the candidate: ");
    gets_s(cand->firstName);
    printf("Please enter the last name of the candidate: ");
    gets_s(cand->lastName);
    printf("Please enter the nationality of the candidate: ");
    gets_s(cand->nation);
    printf("Please enter the age of the candidate: ");
    scanf("%d", &(cand->age));
}

void enter_mission_data(struct mission* mis)
{
    printf("Enter a Mission Name: ");
    gets_s(mis->missionName);
    printf("Enter the year the mission was conducted: ");
    scanf("%d", &(mis->missionYear));
}

int main()
{
    int i;
    struct astronaut candidates[3];
    struct mission missions[3];

    for (i=0; i<3; i++)
    {
        enter_candidate_data(&(candidates[i]));
        // you can put this in a separate loop if you want to enter all
        // candidate data first
        enter_mission_data(&(missions[i]));
    }

    // you could also write functions to print the data instead, depends on
    // how you want it all presented

    for (int i=0; i<3; i++)
    {
        printf("Name: %s %s \t Age: %d \t Nationality: %s\n",
            candidates[i].firstName, candidates[i].lastName, candidates[i].nation);
        printf("Mission Name: %s, year %d\n", missions[i].missionName,
            missions[i].missionYear);
    }

    return 0;
}

You may want a number of missions (or even just one) associated with a particular astronaut. If so, I would define the data structures like this

#define MAX_ASTRONAUT_MISSIONS 20

struct mission
{
    char missionName[maxAge];
    int missionYear;
};

struct astronaut
{
    char firstName[maxName];
    char lastName[maxName];
    char nation[maxNation];
    int age;
    struct mission missions[MAX_ASTRONAUT_MISSIONS];
};

This will allow you to associate MAX_ASTRONAUT_MISSION missions with each astronaut.  Or, more realistically, a single mission could be associated with several astronauts.  In that case, you may want data structures more like this

struct mission
{
    char missionName[maxAge];
    int missionYear;
};

struct astronaut
{
    char firstName[maxName];
    char lastName[maxName];
    char nation[maxNation];
    int age;
    // using a pointer to missions will allow you to create one mission, and
    // all the astronauts on that mission could get a pointer to it,
    // designating they were all on that singular mission.
    struct mission* missions[MAX_ASTRONAUT_MISSIONS];
};


问:
How to show custom error messages in wordpress contact form 7.?
In wordpress contact form 7, i want to show different error messages for sender must fill in field like "Your name is required", "Your email is required" instead of common message Please fill the required field. for all the fields in my form,

please share here, if you have any idea.

Thanks in advance.

答:
PHP code,Link contact form 7

```<code>add_filter( 'wpcf7_validate_email*', 'custom_email_confirmation_validation_filter', 20, 2 );

function custom_email_confirmation_validation_filter( $result, $tag ) {
if ( 'your-email-confirm' == $tag->name ) {
    $your_email = isset( $_POST['your-email'] ) ? trim( $_POST['your-email'] ) : '';
    $your_email_confirm = isset( $_POST['your-email-confirm'] ) ? trim( $_POST['your-email-confirm'] ) : '';

    if ( $your_email != $your_email_confirm ) {
        $result->invalidate( $tag, "Are you sure this is the correct address?" );
    }
}

return $result;
}
</code>```

Hope this will helps you.

Body:
PHP code,Link contact form 7

add_filter( 'wpcf7_validate_email*', 'custom_email_confirmation_validation_filter', 20, 2 );

function custom_email_confirmation_validation_filter( $result, $tag ) {
if ( 'your-email-confirm' == $tag->name ) {
    $your_email = isset( $_POST['your-email'] ) ? trim( $_POST['your-email'] ) : '';
    $your_email_confirm = isset( $_POST['your-email-confirm'] ) ? trim( $_POST['your-email-confirm'] ) : '';

    if ( $your_email != $your_email_confirm ) {
        $result->invalidate( $tag, "Are you sure this is the correct address?" );
    }
}

return $result;
}

Hope this will helps you.


问:
App stopped working after publishing to app store in adhoc for testing
My published app stopped working after xcode upgrade. My Xcode version is now 9.0.1. Publishing goes well except an error in the last stop of upload "Missing app store icon. ios apps must include a 1024x1024px app store icon in png format."
 but the app quits without throwing any errors on the device. The interesting thing is that it works ok when I attach the device to my mac and runs the application. Doesn't show any errors. Please let me know how can I troubleshoot this issue?</p>

答: Finally I was able to publish the app correctly. It was a mistake in renaming the app. I created a new cordova project with the new name and copied the existing code to the www directory. Now everything works ok. </p>


问:
Read a specific letter using argv then using that for a switch (C Program)
This is for Homework

This is kind of a duplicate from one of my posts, but I'm having issues with command line reading. I have to alphabetize the planets and that's a simple task, however getting my program to read the command line argument then using that for my switch is the issue. I'll post my program and go further into detail after that.

```<code>#include<stdio.h>
#include<string.h>

void alpha(char planet[][9], char tempo[9]){
    int i, j;

     for(i=0;i<=9;i++)
      for(j=i+1;j<=9;j++){
         if(strcmp(planet[i],planet[j])>0){
            strcpy(tempo,planet[i]);
            strcpy(planet[i],planet[j]);
            strcpy(planet[j],tempo);
         }
      }
}
int main(int argc , char *argv[]){

   char str[][9] = {"Earth", "Jupiter", "Mars", "Mercury", "Neptune", "Pluto", "Saturn", "Uranus", "Venus"};
   char temp[9];

    if (argc == 3) {
    switch (argv[1][1]) {

    case 'a':
    alpha(str, temp);
    printf("The planets in alphabetical order are:  ");
   for(int i=0;i<=9;i++)
      printf("%s, " , str[i]);
    printf("\n");

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

So for my program to go ahead and alphabetize the planets I need to type in the command -o a after running the program.

So it'd be like this:

./planets -o a

From my understanding the if (argc == 3) line of code reads the position of the character entered. That would skip the -o and only care about the a in the command line. However this doesn't work and I have no clue why. Also when I compile the program it has a comma before Earth and Venus.

So it complies like this(without using the command line portion):

,Earth, ......Venus,

How would I get rid of the comma before Earth and after Venus?

Any help would be appreciated!

答:
```<code> ./planets    -o       a
 argv[0]   argv[1]   argv[2]
</code>```

Now earlier you were checking o by passing argv[1][1]. That's why switch was failing.

Also you had undefined behaviour accessing array index out of bound.

That's why the change

```<code>for(i=0;i<9;i++)
</code>```

Because the array has 9 elements. Also in the second loop  for(j=i+1;j<9;j++)

Body:
This is for Homework

This is kind of a duplicate from one of my posts, but I'm having issues with command line reading. I have to alphabetize the planets and that's a simple task, however getting my program to read the command line argument then using that for my switch is the issue. I'll post my program and go further into detail after that.

#include<stdio.h>
#include<string.h>

void alpha(char planet[][9], char tempo[9]){
    int i, j;

     for(i=0;i<=9;i++)
      for(j=i+1;j<=9;j++){
         if(strcmp(planet[i],planet[j])>0){
            strcpy(tempo,planet[i]);
            strcpy(planet[i],planet[j]);
            strcpy(planet[j],tempo);
         }
      }
}
int main(int argc , char *argv[]){

   char str[][9] = {"Earth", "Jupiter", "Mars", "Mercury", "Neptune", "Pluto", "Saturn", "Uranus", "Venus"};
   char temp[9];

    if (argc == 3) {
    switch (argv[1][1]) {

    case 'a':
    alpha(str, temp);
    printf("The planets in alphabetical order are:  ");
   for(int i=0;i<=9;i++)
      printf("%s, " , str[i]);
    printf("\n");

   return 0;
}
}
}

So for my program to go ahead and alphabetize the planets I need to type in the command -o a after running the program.

So it'd be like this:

./planets -o a

From my understanding the if (argc == 3) line of code reads the position of the character entered. That would skip the -o and only care about the a in the command line. However this doesn't work and I have no clue why. Also when I compile the program it has a comma before Earth and Venus.

So it complies like this(without using the command line portion):

,Earth, ......Venus,

How would I get rid of the comma before Earth and after Venus?

Any help would be appreciated!

Body:
 ./planets    -o       a
 argv[0]   argv[1]   argv[2]

Now earlier you were checking o by passing argv[1][1]. That's why switch was failing.

Also you had undefined behaviour accessing array index out of bound.

That's why the change

for(i=0;i<9;i++)

Because the array has 9 elements. Also in the second loop  for(j=i+1;j<9;j++)


问:
Laravel 5.5 Resource Controller and Dependecy Injection
I am working on a Laravel 5.5 application. When I use php artisan make:model SomeModel -mr it creates the model, migration and resource controller.

I've been noticed that some methods have by default only one parameter: the model:

```<code>public function show(SomeModel $someModel)
{
    ...
}
</code>```

If you look into the $someModel variable it has an empty SomeModel object.

I was reading on Laravel Documentation that it looks like the Containers or Facades but I am not sure how to use this. Do you?

Edit 1:

I had my routes defined in routes/web.php as: Route::resource('users', 'UserController');

Now I had to define all the routes manually since automatic binding was not working:

```<code>Route::get('users', 'UserController@index');
Route::get('users/create', 'UserController@create');
Route::post('users', 'UserController@store');
Route::get('users/{user}/edit', 'UserController@edit', function(App\User $user) {});
Route::post('users/{user}', 'UserController@update', function(App\User $user) {});
Route::post('users/{user}/delete', 'UserController@destroy', function(App\User $user) {});
</code>```

So, should I replace every resource controller route to manual routing like this?

答:
I too came across with the same problem.
If your model having two or more words, you have to use only small letters like  $modeModel as $somemodel.</p>

```<code>public function show(SomeModel $somemodel)
{
    ...
}
</code>```

Body:
I am working on a Laravel 5.5 application. When I use php artisan make:model SomeModel -mr it creates the model, migration and resource controller.

I've been noticed that some methods have by default only one parameter: the model:

public function show(SomeModel $someModel)
{
    ...
}

If you look into the $someModel variable it has an empty SomeModel object.

I was reading on Laravel Documentation that it looks like the Containers or Facades but I am not sure how to use this. Do you?

Edit 1:

I had my routes defined in routes/web.php as: Route::resource('users', 'UserController');

Now I had to define all the routes manually since automatic binding was not working:

Route::get('users', 'UserController@index');
Route::get('users/create', 'UserController@create');
Route::post('users', 'UserController@store');
Route::get('users/{user}/edit', 'UserController@edit', function(App\User $user) {});
Route::post('users/{user}', 'UserController@update', function(App\User $user) {});
Route::post('users/{user}/delete', 'UserController@destroy', function(App\User $user) {});

So, should I replace every resource controller route to manual routing like this?

Body:
I too came across with the same problem.
If your model having two or more words, you have to use only small letters like  $modeModel as $somemodel.

public function show(SomeModel $somemodel)
{
    ...
}


问:
jQuery: keyup for TAB-key?
So, i'm having some trouble getting my script to run IF the Tab key is pressed. After some quick googling, the charcode for Tab is 9. Also, while we're talking, is there any better ways of checking if a key is pressed without using charcodes? I'm asking because i keep getting the following Warning by firebug when using charcode:

The 'charCode' property of a keyup event should not be used. The value is meaningless.

Anyway, it still works, so that's not the problem. This is the code i use:

```<code>$('/* my inputs */').keyup(function(e) {
   console.log('keyup called');
   var code = e.keyCode || e.which;
   if (code == '9') {
     console.log('Tab pressed');
   }
});
</code>```

Using the above code the console is left blank, nothing is added (using Firebug). Of course i've tried actually doing stuff instead of logging text, but nothing  executes. So can anyone see why this isn't working? Is there a better way of checking if a key is pressed?

Thanks in advance.

答:
if nothing happens no matter what key you press, perhaps there is something wrong with the selector you are using?  Can you verify you are selecting properly, perhaps with something like:</p>

```<code>console.log($('/* my inputs */').length);
</code>```

Title: jQuery: keyup for TAB-key?

Body:
So, i'm having some trouble getting my script to run IF the Tab key is pressed. After some quick googling, the charcode for Tab is 9. Also, while we're talking, is there any better ways of checking if a key is pressed without using charcodes? I'm asking because i keep getting the following Warning by firebug when using charcode:

The 'charCode' property of a keyup event should not be used. The value is meaningless.

Anyway, it still works, so that's not the problem. This is the code i use:

$('/* my inputs */').keyup(function(e) {
   console.log('keyup called');
   var code = e.keyCode || e.which;
   if (code == '9') {
     console.log('Tab pressed');
   }
});

Using the above code the console is left blank, nothing is added (using Firebug). Of course i've tried actually doing stuff instead of logging text, but nothing  executes. So can anyone see why this isn't working? Is there a better way of checking if a key is pressed?

Thanks in advance.

Body:
if nothing happens no matter what key you press, perhaps there is something wrong with the selector you are using?  Can you verify you are selecting properly, perhaps with something like:

console.log($('/* my inputs */').length);


问:
Codeigniter connection to Filezilla Server is getting rejected
Here's my controller class

```<code>public function download_ftp(){
    $this->load->library('ftp');

    $config['hostname'] = 'localhost';
    $config['username'] = 'Admin';
    $config['password'] = 'admin';
    $config['debug']        = TRUE;

    $this->ftp->connect($config);
}
</code>```

And this is the server log for the operation.

```<code>(000126)03/12/2017 23:01:53 - (not logged in) (::1)> Connected on port 21, sending welcome message...
(000126)03/12/2017 23:01:53 - (not logged in) (::1)> 220 Welcom
(000126)03/12/2017 23:01:53 - (not logged in) (::1)> USER Admin
(000126)03/12/2017 23:01:53 - (not logged in) (::1)> 331 Password required for admin
(000126)03/12/2017 23:01:53 - (not logged in) (::1)> PASS *****
(000126)03/12/2017 23:01:53 - admin (::1)> 230 Logged on
(000126)03/12/2017 23:01:53 - admin (::1)> EPSV
(000126)03/12/2017 23:01:53 - admin (::1)> 229 Entering Extended Passive Mode (|||983|)
(000126)03/12/2017 23:01:53 - admin (::1)> could not send reply, disconnected.
</code>```

The filezilla server is hosted on localhost. As you can see the function successfully logs in, but the server seems unable to respond and it terminates the connection.

答:
By default, Filezilla accepts passive mode for connection. But at times, the environment dose not support clearly for passive modes. What we normally do in such scenario from ftp client - we switch the mode of connection from Passive to Active.

The Passive property controls whether data connections for uploads/downloads are established in Active or Passive mode. To use Active mode, set the Passive property = false

```<code>// turn passive mode on
ftp_pasv($conn_id, true);

// turn active mode on
ftp_pasv($conn_id, false);
</code>```

Body:
Here's my controller class

public function download_ftp(){
    $this->load->library('ftp');

    $config['hostname'] = 'localhost';
    $config['username'] = 'Admin';
    $config['password'] = 'admin';
    $config['debug']        = TRUE;

    $this->ftp->connect($config);
}

And this is the server log for the operation.

(000126)03/12/2017 23:01:53 - (not logged in) (::1)> Connected on port 21, sending welcome message...
(000126)03/12/2017 23:01:53 - (not logged in) (::1)> 220 Welcom
(000126)03/12/2017 23:01:53 - (not logged in) (::1)> USER Admin
(000126)03/12/2017 23:01:53 - (not logged in) (::1)> 331 Password required for admin
(000126)03/12/2017 23:01:53 - (not logged in) (::1)> PASS *****
(000126)03/12/2017 23:01:53 - admin (::1)> 230 Logged on
(000126)03/12/2017 23:01:53 - admin (::1)> EPSV
(000126)03/12/2017 23:01:53 - admin (::1)> 229 Entering Extended Passive Mode (|||983|)
(000126)03/12/2017 23:01:53 - admin (::1)> could not send reply, disconnected.

The filezilla server is hosted on localhost. As you can see the function successfully logs in, but the server seems unable to respond and it terminates the connection.

Body:
By default, Filezilla accepts passive mode for connection. But at times, the environment dose not support clearly for passive modes. What we normally do in such scenario from ftp client - we switch the mode of connection from Passive to Active.

The Passive property controls whether data connections for uploads/downloads are established in Active or Passive mode. To use Active mode, set the Passive property = false

// turn passive mode on
ftp_pasv($conn_id, true);

// turn active mode on
ftp_pasv($conn_id, false);


问:
how to sendkeys to textbox with selenium on vba excel

```<code>selenium.FindElementByXPath("/html/body/div[1]/div[1]/div[3]/div[2]/div[1]/div[3]/ul/ul/li[13]/ul/li[18]/a").SendKeys ("TEST")
</code>```

don't work

答:
Try like this xpath</p>

```<code>//input[contains(@name,'prop_') and contains(@value='ATG0002T')]").SendKeys ("TEST")
</code>```

Body:
selenium.FindElementByXPath("/html/body/div[1]/div[1]/div[3]/div[2]/div[1]/div[3]/ul/ul/li[13]/ul/li[18]/a").SendKeys ("TEST")

don't work

Body:
Try like this xpath

//input[contains(@name,'prop_') and contains(@value='ATG0002T')]").SendKeys ("TEST")


问:
What is a raw type and why shouldn't we use it?

Questions:

What are raw types in Java, and why do I often hear that they shouldn't be used in new code?

What is the alternative if we can't use raw types, and how is it better?

答:
Here's another case where raw types will bite you:

```<code>public class StrangeClass<T> {
  @SuppressWarnings("unchecked")
  public <X> X getSomethingElse() {
    return (X)"Testing something else!";
  }

  public static void main(String[] args) {
    final StrangeClass<String> withGeneric    = new StrangeClass<>();
    final StrangeClass         withoutGeneric = new StrangeClass();
    final String               value1,
                               value2;

    // Compiles
    value1 = withGeneric.getSomethingElse();

    // Produces compile error:
    // incompatible types: java.lang.Object cannot be converted to java.lang.String
    value2 = withoutGeneric.getSomethingElse();
  }
}
</code>```

This is counter-intuitive because you'd expect the raw type to only affect methods bound to the class type parameter, but it actually also affects generic methods with their own type parameters.

As was mentioned in the accepted answer, you lose all support for generics within the code of the raw type. Every type parameter is converted to its erasure (which in the above example is just Object).

Body:
Here's another case where raw types will bite you:

public class StrangeClass<T> {
  @SuppressWarnings("unchecked")
  public <X> X getSomethingElse() {
    return (X)"Testing something else!";
  }

  public static void main(String[] args) {
    final StrangeClass<String> withGeneric    = new StrangeClass<>();
    final StrangeClass         withoutGeneric = new StrangeClass();
    final String               value1,
                               value2;

    // Compiles
    value1 = withGeneric.getSomethingElse();

    // Produces compile error:
    // incompatible types: java.lang.Object cannot be converted to java.lang.String
    value2 = withoutGeneric.getSomethingElse();
  }
}

This is counter-intuitive because you'd expect the raw type to only affect methods bound to the class type parameter, but it actually also affects generic methods with their own type parameters.

As was mentioned in the accepted answer, you lose all support for generics within the code of the raw type. Every type parameter is converted to its erasure (which in the above example is just Object).

ContentLicense: CC BY-SA 4.0


问:
Django-Crontab with deployment environment
I'm developing a module with the crontab.

Actually, the framework I'm using is django so I did install 'django-crontab'

I did test as the instruction did and make it with localhost environment.

When I deployed("sudo service apache2 restart") it on AWS after doing a command 'python manage.py crontab add', it didn't work.

I thiknk it's working on only localhost environment, isn't it?

How can I solve this problem?

答:
If you have more than one profile in your django settings, you shuold specify one before add crontab. if not specified, django crontab run as default environment, which is develop mostly. To run it on product environment , you should do these:

specify crontab enviromen in settings.product.py, something like

CRONTAB_DJANGO_SETTINGS_MODULE = 'gold.settings.product'

specify settings profile and add crontab

export MYPROJECT_PROFILE = product
python manage.py crontab add


问:
Natural size of user avatars twice as large as display size
I am new to web development and I have a question regarding the natural size of profile pictures vs their actual size.

I noticed that when I inspect element on the profile pictures on popular websites, the natural size of the avatar image is usually twice as large as the displayed size.

Some examples:

And when trying this out on my own, I noticed that images do really look better when you make sure the actual (natural) size of the image is twice as large as the displayed size.

As you can see the 64x64 picture looks a lot more crisp than the 32x32 picture. My question is if there is anything special about the two-factor. Can I make it a 128x128 picture and display it as a 32x32 to make it look even better?

答:
Image clarity works on the pixel, if you using the high-resolution image for a small display it's not a good idea because High-Resolution image size is big always. your website will be slow.

you can go with this For Example - Natural Size (64x64)px and you can show in (50x50)px not the big difference of Image Pixel.

it will also show your image clear.


问:
Import to the same Subversion repository directory multiple times?
For a number of reasons, the canonical source of some files I have can't be a working copy of the repository (the Subversion server is behind an inaccessible firewall, and the data doesn't natively exist in the file system in my preferred structure). So, I wrote a tool that downloads the data, generates a directory structure from it, and then uses SharpSvn to import the result into the repository. This works… the first time. The second time, of course, a directory of that name already exists in the repository, and I can't import again.

Instead, I could:

Delete the directory, then import. I haven't tested this, but aside from sounding stupid, it probably also deletes the revision history of the respective files, regarding the new ones as entirely different.

See if the directory exists, check it out, remotely delete the files that no longer exist in the canonical source, then replace the remainder and commit. This would probably work, but sounds error-prone and needlessly difficult.

Is my assumption correct that deleting files will mark new ones of the same ways as different files? Is there an easier way than the second approach?

答:
Subversion has a loose connection to the files.  For files inside a folder, you can easily do a get/update, make massive changes (including deleting, replacing, or adding files), then commit the differences.  That file-level behavior is typical Subversion usage.

The directories are slightly different.  Subversion stores the repository information at the folder level.  So, if you create a new folder, it won't automatically have a connection to Subversion.  (Using something like TortoiseSvn, it takes care of much of that for you.)

If you are going to be adding and deleting directories during the generation process, you'll have some slightly different issues than with the files themselves.  But, you can still accomplish your goal through the command-line, SharpSvn, TortoiseSvn, or other similar tools.

OwnerDisplayName: Sören Kuklau

OwnerDisplayName: John Fisher


问:
Linq to Entities and Linq to XML
Given the following XML structure in form of XDocument:

```<code><Header><person><ID>0888-123-45</ID><Name>Joe</Name><LocationID>Loc1</LocationID><LocationName>New York</LocationName><CarName>Honda</CarName><CarYear>2000</CarYear></person><person><ID>199-20-333</ID><LocationID>My House</LocationID><LocationName>My House</LocationName><CarName>BMW</CarName><CarYear>2011</CarYear></person></Header>
</code>```

There are 3 entities involved:

Person:

GUID, ID (varchar), Name (varchar), LocationID (Location's GUID)

Car:

GUID, PersonID (Person's GUID), CarName (varchar), CarYear (varchar)

Location:

GUID, LocationID (varchar), LocatioName (varchar)

What I want to achieve is the following steps:

Get distinct locations for all persons in XDocument

If location in XDocument exists in data context, don't insert, else insert

Insert all persons and their corresponding car.

This is what I have and it is throwing an error since the query is a mix of both Linq to Entities and Linq to XML.  I appreciate for any insight and suggestion for a better way to solve it.  No for loops as parsing XDocument with for loops is slow.

```<code>        Dim fileLocs = (From p In xmlDoc.<Header>.<Person>
                        Select New location With {.locID = Guid.NewGuid(), _
                                                  .locationID = If(p.<LocationID> Is Nothing, Nothing, p.<LocationID>.Value), _
                                                  .locLabel = If(p.<LocationName> Is Nothing, Nothing, p.<LocationName>.Value)})
        Dim filteredFileLocs = From l In fileLocs
                               Where l.locationID IsNot Nothing AndAlso l.locationID <> "" AndAlso
                                    (From loc In ctx.locations
                                      Where loc.locationID = l.locationID AndAlso loc.locLabel = l.locLabel
                                      Select loc).Count = 0
                              Select l

        Dim sysLocs = (From loc In ctx.locations Select loc)
        Dim allLocs = filteredFileLocs.Union(sysLocs)

        Dim pers As IEnumerable(Of person) = (From p In xmlDoc.<Header>.<Person>
                                            Select New Person With {.personID = Guid.NewGuid(), .ID = p.Element(XName.Get("ID")).Value, _
                                                                    .locID = If(p.<locationID> IsNot Nothing AndAlso p.<locationID>.Value <> "", CType(Nothing, Guid?), _
                                                                                (From sl In allLocs
                                                                                Where sl.locationID = p.Element(XName.Get("LocationID")).Value AndAlso
                                                                                sl.locLabel = p.Element(XName.Get("LocationName")).Value
                                                                                Select sl.locID)), _
                                                                    .Name = p.Element(XName.Get("Name")).Value})

        For Each l In filteredFileLocs
            ctx.locations.AddObject(l)
        Next
        For Each p In pers
            ctx.persons.AddObject(p)
        Next
</code>```

Error is on the line Dim pers: "Specified cast is not valid."

答:
What I noticed is that the clause where .locID is set,

```<code>(From sl In allLocs Where sl.locationID = p.Element(XName.Get("LocationID")).Value

AndAlso sl.locLabel = p.Element(XName.Get("LocationName")).Value Select sl.locID)
</code>```

is returning an ienumberable and it's assigned to .LocID which is a GUID, so that should be the error cause, you would need to add FirstOrDefault, First, SingleOrDefault or Single like this

```<code>(From sl In allLocs Where sl.locationID = p.Element(XName.Get("LocationID")).Value

AndAlso sl.locLabel = p.Element(XName.Get("LocationName")).Value _

Select sl.locID).FirstOrDefault()
</code>```

Title: Linq to Entities and Linq to XML

Body:
Given the following XML structure in form of XDocument:

<person><ID>0888-123-45</ID><Name>Joe</Name><LocationID>Loc1</LocationID><LocationName>New York</LocationName><CarName>Honda</CarName><CarYear>2000</CarYear></person><person><ID>199-20-333</ID><LocationID>My House</LocationID><LocationName>My House</LocationName><CarName>BMW</CarName><CarYear>2011</CarYear></person>

There are 3 entities involved:

Person:

GUID, ID (varchar), Name (varchar), LocationID (Location's GUID)

Car:

GUID, PersonID (Person's GUID), CarName (varchar), CarYear (varchar)

Location:

GUID, LocationID (varchar), LocatioName (varchar)

What I want to achieve is the following steps:

Get distinct locations for all persons in XDocument

If location in XDocument exists in data context, don't insert, else insert

Insert all persons and their corresponding car.

This is what I have and it is throwing an error since the query is a mix of both Linq to Entities and Linq to XML.  I appreciate for any insight and suggestion for a better way to solve it.  No for loops as parsing XDocument with for loops is slow.

        Dim fileLocs = (From p In xmlDoc..<Person>
                        Select New location With {.locID = Guid.NewGuid(), _
                                                  .locationID = If(p.<LocationID> Is Nothing, Nothing, p.<LocationID>.Value), _
                                                  .locLabel = If(p.<LocationName> Is Nothing, Nothing, p.<LocationName>.Value)})
        Dim filteredFileLocs = From l In fileLocs
                               Where l.locationID IsNot Nothing AndAlso l.locationID <> "" AndAlso
                                    (From loc In ctx.locations
                                      Where loc.locationID = l.locationID AndAlso loc.locLabel = l.locLabel
                                      Select loc).Count = 0
                              Select l

        Dim sysLocs = (From loc In ctx.locations Select loc)
        Dim allLocs = filteredFileLocs.Union(sysLocs)

        Dim pers As IEnumerable(Of person) = (From p In xmlDoc..<Person>
                                            Select New Person With {.personID = Guid.NewGuid(), .ID = p.Element(XName.Get("ID")).Value, _
                                                                    .locID = If(p.<locationID> IsNot Nothing AndAlso p.<locationID>.Value <> "", CType(Nothing, Guid?), _
                                                                                (From sl In allLocs
                                                                                Where sl.locationID = p.Element(XName.Get("LocationID")).Value AndAlso
                                                                                sl.locLabel = p.Element(XName.Get("LocationName")).Value
                                                                                Select sl.locID)), _
                                                                    .Name = p.Element(XName.Get("Name")).Value})

        For Each l In filteredFileLocs
            ctx.locations.AddObject(l)
        Next
        For Each p In pers
            ctx.persons.AddObject(p)
        Next

Error is on the line Dim pers: "Specified cast is not valid."

Body:
What I noticed is that the clause where .locID is set,

(From sl In allLocs Where sl.locationID = p.Element(XName.Get("LocationID")).Value

AndAlso sl.locLabel = p.Element(XName.Get("LocationName")).Value Select sl.locID)

is returning an ienumberable and it's assigned to .LocID which is a GUID, so that should be the error cause, you would need to add FirstOrDefault, First, SingleOrDefault or Single like this

(From sl In allLocs Where sl.locationID = p.Element(XName.Get("LocationID")).Value

AndAlso sl.locLabel = p.Element(XName.Get("LocationName")).Value _

Select sl.locID).FirstOrDefault()


问:
Java Ragged Array, trying to display multiple Arrays
I am having trouble finding out what is the issue with my code,  Everything is fine till I get to the Jagged array. I want it to display the code as a jagged array but I dont know</p>
```<code>package ajk;

public class Test2
{

    public static void main(String[] args)
        int[][] twoD = {
            {1, 2},
            {3, 4, 5},
            {6},
            {7, 8, 9},
        };
        printArray(twoD);
    }
    public static void printArray(int[][] arr) {
        System.out.println("[");

        int r = 4;
        int c = 3;
        int i, j;

        for (i=0; i < r; i++ );
            System.out.print("[");
            for (j=0; j < c; j++ ) {
                System.out.print( arr[i][j]  + " " );
            }
        }
    }
}
</code>```

答:
It' quite simple, actually. Arrays class have some static methods to print its own elements (ints, doubles, Objects, etc.). Since, here is two dimensional array, in the loop you go through every element of the arr (which is an array of int), and call this method. Arrays.toString(someArr) represents someArr as a String.</p>

```<code>for (int row = 0; row < arr.length; row++) {
    int[] arr1D = arr[row];
    System.out.println(Arrays.toString(arr1D));
}
</code>```

Body:
I am having trouble finding out what is the issue with my code,  Everything is fine till I get to the Jagged array. I want it to display the code as a jagged array but I dont know

package ajk;

public class Test2
{

    public static void main(String[] args)
        int[][] twoD = {
            {1, 2},
            {3, 4, 5},
            {6},
            {7, 8, 9},
        };
        printArray(twoD);
    }
    public static void printArray(int[][] arr) {
        System.out.println("[");

        int r = 4;
        int c = 3;
        int i, j;

        for (i=0; i < r; i++ );
            System.out.print("[");
            for (j=0; j < c; j++ ) {
                System.out.print( arr[i][j]  + " " );
            }
        }
    }
}

Body:
It' quite simple, actually. Arrays class have some static methods to print its own elements (ints, doubles, Objects, etc.). Since, here is two dimensional array, in the loop you go through every element of the arr (which is an array of int), and call this method. Arrays.toString(someArr) represents someArr as a String.

for (int row = 0; row < arr.length; row++) {
    int[] arr1D = arr[row];
    System.out.println(Arrays.toString(arr1D));
}


问:
Difference in Processing 3D Animated Graphics Shader & Same 3D animated GIF
When we develop (HLSL Language) any 3D animation using Graphics shader (may be with help of DirectX) I know the shader get compiled to Shader bytecode. These byte codes implies some intermediate shader assembly instructions. These instruction will get passed to GPU driver and the GPU driver will convert those instructions to their proprietary GPU instructions and finally GPU will render them.

Now I would like to know when we see the exact same animation in a 3D GIF (some.gif) file, how does the Operating system render the 3D animation?

Does it follow the same path to render the graphics or something different happens in case of a GIF?

Thanks,

答:
When rendering in DirectX, you eventually are converting your 3D scene into a 2D image to be displayed on your display device (eg. a monitor). This is generally done by using a projection matrix, which converts 3D coordinates into screen-space (2D) coordinates.

Usually, the operating system doesn't display image files (.gifs) directly, they are loaded an rendered through another program (which may be distributed as part of the OS, for example, the thumbnail generation in Windows Explorer). How exactly the image is displayed is dependent on the implementation of the displaying program. There are many possibilities on how it could be implemented, DirectX, OpenGL, GDI, are all possibilities.


问:
Second argument replacing first scala
I am trying to define a function in scala ( ^ ), which takes 2 values and prints them like

```<code> 2
x
</code>```

Here is what I have so far...

```<code>class $ (val text2D: Array[Array[Char]])
{
  def ^(that: $) =
  {
    " " ++ s"${this.text2D(0)(0)}" ++
    "\n" ++ s"${that.text2D(0)(0)}"
  }

  def +(that: $) = this.text2D + "+" + that.text2D

  override def toString = s"${this.text2D(0)(0)}"
}

object $ {
  val array = Array.ofDim[Char](1,1)
  def apply(x: String): $ = {
    array (0)(0) = x.charAt(0)
    new $ (array)
  }
}

val x = $("x")
println(x)

val x2 = $("x") ^ $("2")
println(x2)
</code>```

When I run this, I do not get the output I am expecting, instead I get

```<code> 2
2
</code>```

Why is it only taking the second element? Any help would be appreciated.

答:
I think what you need is something like this:

```<code>class $(val text2D: Array[String]) {
  def ^(that: $): $ = {
    if (this.text2D.length == 0)
      that
    else if (that.text2D.length == 0)
      this
    else {
      val thisW = this.text2D(0).length
      val thatW = that.text2D(0).length

      // cross-pad arrays to have the same width
      val padThisRight = " " * thatW
      val padThatLeft = " " * thisW
      val thisPaddedW = this.text2D.map(_ + padThisRight)
      val thatPaddedW = that.text2D.map(padThatLeft + _)
      // first lines comes from that!
      new $(thatPaddedW ++ thisPaddedW)
    }
  }

  def +(that: $): $ = {
    if (this.text2D.length == 0)
      that
    else if (that.text2D.length == 0)
      this
    else {
      val thisH = this.text2D.length
      val thatH = that.text2D.length
      val thisW = this.text2D(0).length
      val thatW = that.text2D(0).length

      // pad arrays to have the same height
      val emptyThis = " " * thisW
      val emptyThat = " " * thatW
      val thisPaddedH = if (thisH >= thatH) this.text2D else Array.fill(thatH - thisH)(emptyThis) ++ this.text2D
      val thatPaddedH = if (thisH <= thatH) that.text2D else Array.fill(thisH - thatH)(emptyThat) ++ that.text2D

      new $(thisPaddedH.zip(thatPaddedH).map(p => p._1 + p._2))
    }
  }

  override def toString = text2D.mkString("\n")
}

object $ {
  def apply(x: String): $ = {
    new $(Array[String](x))
  }
}
</code>```

and then

```<code>val x2 = $("x") ^ $("2")
println(s"x2:\n$x2")
println("----------------------------")

val z = x2 + $(" + ") + y2
println(s"z:\n$z")
println("----------------------------")

val zz = x2 + $(" + ") + (y2 ^ $("3"))
println(s"zz:\n$zz")
println("----------------------------")
</code>```

produces following output

```<code>x2:
 2
x
----------------------------
z:
 2    2
x  + y
----------------------------
zz:
       3
 2    2
x  + y
----------------------------
</code>```

The main idea here is that operations on $ produce another instance of $ rather than String (I use String instead of Array[Char] as it seems much easier and has no obvious drawbacks). In such way you don't have to re-parse String splitting it by new lines and have to wonder how to handle cases when the string is not well-aligned. So now operators ^ and + is just an exercise in aligning two 2d-arrays to have either the same width or the same height and then joining them.

Title: Second argument replacing first scala

Body:
I am trying to define a function in scala ( ^ ), which takes 2 values and prints them like

 2
x

Here is what I have so far...

class $ (val text2D: Array[Array[Char]])
{
  def ^(that: $) =
  {
    " " ++ s"${this.text2D(0)(0)}" ++
    "\n" ++ s"${that.text2D(0)(0)}"
  }

  def +(that: $) = this.text2D + "+" + that.text2D

  override def toString = s"${this.text2D(0)(0)}"
}

object $ {
  val array = Array.ofDim[Char](1,1)
  def apply(x: String): $ = {
    array (0)(0) = x.charAt(0)
    new $ (array)
  }
}

val x = $("x")
println(x)

val x2 = $("x") ^ $("2")
println(x2)

When I run this, I do not get the output I am expecting, instead I get

 2
2

Why is it only taking the second element? Any help would be appreciated.

Body:
I think what you need is something like this:

class $(val text2D: Array[String]) {
  def ^(that: $): $ = {
    if (this.text2D.length == 0)
      that
    else if (that.text2D.length == 0)
      this
    else {
      val thisW = this.text2D(0).length
      val thatW = that.text2D(0).length

      // cross-pad arrays to have the same width
      val padThisRight = " " * thatW
      val padThatLeft = " " * thisW
      val thisPaddedW = this.text2D.map(_ + padThisRight)
      val thatPaddedW = that.text2D.map(padThatLeft + _)
      // first lines comes from that!
      new $(thatPaddedW ++ thisPaddedW)
    }
  }

  def +(that: $): $ = {
    if (this.text2D.length == 0)
      that
    else if (that.text2D.length == 0)
      this
    else {
      val thisH = this.text2D.length
      val thatH = that.text2D.length
      val thisW = this.text2D(0).length
      val thatW = that.text2D(0).length

      // pad arrays to have the same height
      val emptyThis = " " * thisW
      val emptyThat = " " * thatW
      val thisPaddedH = if (thisH >= thatH) this.text2D else Array.fill(thatH - thisH)(emptyThis) ++ this.text2D
      val thatPaddedH = if (thisH <= thatH) that.text2D else Array.fill(thisH - thatH)(emptyThat) ++ that.text2D

      new $(thisPaddedH.zip(thatPaddedH).map(p => p._1 + p._2))
    }
  }

  override def toString = text2D.mkString("\n")
}

object $ {
  def apply(x: String): $ = {
    new $(Array[String](x))
  }
}

and then

val x2 = $("x") ^ $("2")
println(s"x2:\n$x2")
println("----------------------------")

val z = x2 + $(" + ") + y2
println(s"z:\n$z")
println("----------------------------")

val zz = x2 + $(" + ") + (y2 ^ $("3"))
println(s"zz:\n$zz")
println("----------------------------")

produces following output

x2:
 2
x
----------------------------
z:
 2    2
x  + y
----------------------------
zz:
       3
 2    2
x  + y
----------------------------

The main idea here is that operations on $ produce another instance of $ rather than String (I use String instead of Array[Char] as it seems much easier and has no obvious drawbacks). In such way you don't have to re-parse String splitting it by new lines and have to wonder how to handle cases when the string is not well-aligned. So now operators ^ and + is just an exercise in aligning two 2d-arrays to have either the same width or the same height and then joining them.


问:
Scipy.minimize not correctly minimizing
I am currently doing a project that maps the velocity of stars as you move out from the center of the galaxy(the distance to the center is denoted by r).

Essentially, I am aiming to minimize the distance between my model function and my observed function. To do this, I have to minimize the function: np.sum(((v_model-v_obs)/errors)**2) where errors is an array of the error at each different r value. v_obs is the observed velocity at each r value  (r is just an array of numbers). To minimize the function, I have to manipulate v_model which can be done via manipulating two "fixing parameters" p0 and r0 in the equation (integrand is shown below):

```<code>np.sqrt(4.302*10**(-6)*quad(integrand,0,r.all(),args=(p0,r0))[0]/r.all())
</code>```

Before I get into the problem, I want to know if r.all() is appropriate since it wouldn't allow me to put r due to it being an array. An alternative I had was to make an array of v_model via:

```<code>#am is the amount of elements in the array r
#r, v_model,v_obs, and errors all have the same size
def integrand(r,p0,r0):
    return (p0 * r0**3)/((r+r0)*((r**2)+(r0**2)))*4*3.1415926535*r**2
integrals = []
for i in r:
     integrals.append(quad(integrand, 0 ,i,args=(p0,r0)))

v_model = []

for x in range (0,am):
    k = integrals[x][0]
    i = r[x]
    v_model.append(np.sqrt((4.302*10**(-6)*k)/i))
</code>```

Regardless, to minimize the function np.sum(((v_model-v_obs)/errors)**2)
I tried to do something like this:

```<code>def chisqfunc(parameters):
    p0 = parameters[0]
    r0 = parameters[1]
    v_model = []
    for x in range(0,am):
        v_model.append(np.sqrt(4.302*10.0**(-6)*quad(integrand, 0, r[x], args=(p0,r0))[0]/r[x]))
    chisq = np.sum(((v_model-v_obs)/errors)**2)
    return chisq
x0 = np.array([10**6,24])
resolution = minimize(chisqfunc,x0)
</code>```

However, the values I get back aren't good fits at all (which is evident when I graph the observed data and my model)

In conclusion, I have two main question:

1.) Is my function taking the model minus the observed at each different r value, and if not, how do I fix this? (I think I messed up my v_model equation)

2.) Why is it returning wrong numbers for r0 and p0?

Here is my full code (By the way, to know if the minimization is working properly: r0 should be around 1.5 and p0 should be around: 3.5*10**8)

```<code>from scipy.optimize import*
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
from scipy.integrate import quad

#number of measurements
am = 18

r0 = 1.8
p0 = 3.5*10**8.62

#Observed Data
v_obs = np.array([
234.00,
192.00,
212.00,
223.00,
222.00,
224.00,
224.00,
226.00,
226.00,
227.00,
227.00,
224.00,
220.00,
218.00,
217.00,
216.00,
210.00,
208.00

]
)

r = np.array([0.92,
2.32,
3.24,
4.17,
5.10,
6.03,
6.96,
7.89,
8.80,
9.73,
10.64,
11.58,
12.52,
13.46,
14.40,
15.33,
16.27,
17.11

]
)

errors = np.array([
3.62,
4.31,
3.11,
5.5,
3.9,
3.5,
2.7,
2.5,
2.3,
2.1,
2.3,
2.6,
3.1,
3.2,
3.2,
3.1,
2.9,
2.8
    ])

#integral
def integrand(r,p0,r0):
    return (p0 * r0**3)/((r+r0)*((r**2)+(r0**2)))*4*3.1415926535*r**2
integrals = []
for i in r:
     integrals.append(quad(integrand, 0 ,i,args=(p0,r0)))

v_model = []

for x in range (0,am):
    k = integrals[x][0]
    i = r[x]
    v_model.append(np.sqrt((4.302*10**(-6)*k)/i))

def chisqfunc(parameters):
    p0 = parameters[0]
    r0 = parameters[1]
    v_model = np.sqrt(4.302*10**(-6)*quad(integrand,0,r.all(),args=(p0,r0))[0]/r.all())
    chisq = np.sum(((v_model-v_obs)/errors)**2)
    print(v_model)
    return chisq
x0 = np.array([10**6,24])
resolution = minimize(chisqfunc,x0)
print("This is the function",resolution)
</code>```

Let me know if I left out any data and thank you in advance!

Title: Scipy.minimize not correctly minimizing

Body:
I am currently doing a project that maps the velocity of stars as you move out from the center of the galaxy(the distance to the center is denoted by r).

Essentially, I am aiming to minimize the distance between my model function and my observed function. To do this, I have to minimize the function: np.sum(((v_model-v_obs)/errors)**2) where errors is an array of the error at each different r value. v_obs is the observed velocity at each r value  (r is just an array of numbers). To minimize the function, I have to manipulate v_model which can be done via manipulating two "fixing parameters" p0 and r0 in the equation (integrand is shown below):

np.sqrt(4.302*10**(-6)*quad(integrand,0,r.all(),args=(p0,r0))[0]/r.all())

Before I get into the problem, I want to know if r.all() is appropriate since it wouldn't allow me to put r due to it being an array. An alternative I had was to make an array of v_model via:

#am is the amount of elements in the array r
#r, v_model,v_obs, and errors all have the same size
def integrand(r,p0,r0):
    return (p0 * r0**3)/((r+r0)*((r**2)+(r0**2)))*4*3.1415926535*r**2
integrals = []
for i in r:
     integrals.append(quad(integrand, 0 ,i,args=(p0,r0)))

v_model = []

for x in range (0,am):
    k = integrals[x][0]
    i = r[x]
    v_model.append(np.sqrt((4.302*10**(-6)*k)/i))

Regardless, to minimize the function np.sum(((v_model-v_obs)/errors)**2)
I tried to do something like this:

def chisqfunc(parameters):
    p0 = parameters[0]
    r0 = parameters[1]
    v_model = []
    for x in range(0,am):
        v_model.append(np.sqrt(4.302*10.0**(-6)*quad(integrand, 0, r[x], args=(p0,r0))[0]/r[x]))
    chisq = np.sum(((v_model-v_obs)/errors)**2)
    return chisq
x0 = np.array([10**6,24])
resolution = minimize(chisqfunc,x0)

However, the values I get back aren't good fits at all (which is evident when I graph the observed data and my model)

In conclusion, I have two main question:

1.) Is my function taking the model minus the observed at each different r value, and if not, how do I fix this? (I think I messed up my v_model equation)

2.) Why is it returning wrong numbers for r0 and p0?

Here is my full code (By the way, to know if the minimization is working properly: r0 should be around 1.5 and p0 should be around: 3.5*10**8)

from scipy.optimize import*
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
from scipy.integrate import quad

#number of measurements
am = 18

r0 = 1.8
p0 = 3.5*10**8.62

#Observed Data
v_obs = np.array([
234.00,
192.00,
212.00,
223.00,
222.00,
224.00,
224.00,
226.00,
226.00,
227.00,
227.00,
224.00,
220.00,
218.00,
217.00,
216.00,
210.00,
208.00

]
)

r = np.array([0.92,
2.32,
3.24,
4.17,
5.10,
6.03,
6.96,
7.89,
8.80,
9.73,
10.64,
11.58,
12.52,
13.46,
14.40,
15.33,
16.27,
17.11

]
)

errors = np.array([
3.62,
4.31,
3.11,
5.5,
3.9,
3.5,
2.7,
2.5,
2.3,
2.1,
2.3,
2.6,
3.1,
3.2,
3.2,
3.1,
2.9,
2.8
    ])

#integral
def integrand(r,p0,r0):
    return (p0 * r0**3)/((r+r0)*((r**2)+(r0**2)))*4*3.1415926535*r**2
integrals = []
for i in r:
     integrals.append(quad(integrand, 0 ,i,args=(p0,r0)))

v_model = []

for x in range (0,am):
    k = integrals[x][0]
    i = r[x]
    v_model.append(np.sqrt((4.302*10**(-6)*k)/i))

def chisqfunc(parameters):
    p0 = parameters[0]
    r0 = parameters[1]
    v_model = np.sqrt(4.302*10**(-6)*quad(integrand,0,r.all(),args=(p0,r0))[0]/r.all())
    chisq = np.sum(((v_model-v_obs)/errors)**2)
    print(v_model)
    return chisq
x0 = np.array([10**6,24])
resolution = minimize(chisqfunc,x0)
print("This is the function",resolution)

Let me know if I left out any data and thank you in advance!

Body:
I have been playing with your code.  I tried various methods/solvers and they all converge to about the same answer.  I'm thinking that this is the best answer it can reach.  To test this I calculated the root sum square of differences for the answer you say is right (r0 = 1.8, p0 = 3.5*10**8.62) and the computed answer.  The computed answer seems to have a smaller error (527 vs 564).

from scipy.optimize import*
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
from scipy.integrate import quad
#-----------------------------------------------------------------------------
#number of measurements
am = 18
r0 = 1.8
p0 = 3.5*10.0**8.62
#Observed Data
v_obs = np.array([
234.00, 192.00, 212.00, 223.00, 222.00,
224.00, 224.00, 226.00, 226.00, 227.00,
227.00, 224.00, 220.00, 218.00, 217.00,
216.00, 210.00, 208.00,
])
r = np.array([
0.92, 2.32, 3.24, 4.17, 5.10,
6.03, 6.96, 7.89, 8.80, 9.73,
10.64, 11.58, 12.52, 13.46, 14.40,
15.33, 16.27, 17.11
])
errors = np.array([
3.62, 4.31, 3.11, 5.5, 3.9,
3.5, 2.7, 2.5, 2.3, 2.1,
2.3, 2.6, 3.1, 3.2, 3.2,
3.1, 2.9, 2.8
])
#-----------------------------------------------------------------------------
#integral
def integrand(r,p0,r0):
    return (p0 * r0**3)/((r+r0)*((r**2)+(r0**2)))*4.0*3.1415926535*r**2
#-----------------------------------------------------------------------------
integrals = []
for i in r:
    integrals.append(quad(integrand, 0, i, args=(p0,r0)))
#print "integrals = " + str(integrals)
v_model = []
for x in range(0,am):
    k = integrals[x][0]
    i = r[x]
    v_model.append(np.sqrt((4.302*10.0**(-6)*k)/i))
#print "v_model = " + str(v_model)
#-----------------------------------------------------------------------------
def chisqfunc(parameters):
    p0 = parameters[0]
    r0 = parameters[1]
    v_model = np.sqrt(4.302*10.0**(-6)*quad(integrand, 0, r.all(), args=(p0,r0))[0]/r.all())
    chisq = np.sum(((v_model - v_obs)/errors)**2)
    #print "chisq = " + str(chisq)
    #print "v_model = " + str(v_model)
    return chisq
#-----------------------------------------------------------------------------
x0 = np.array([10.0**6,24.0]) # initial guess
# try various methods (they all give about the same answer, they all "converged")
#resolution = minimize(chisqfunc, x0, method='Nelder-Mead', tol=0.001)
#resolution = minimize(chisqfunc, x0, method='Powell', tol=0.001)
#resolution = minimize(chisqfunc, x0, method='CG', tol=0.001)
#resolution = minimize(chisqfunc, x0, method='BFGS', tol=0.001)
# Jac required - resolution = minimize(chisqfunc, x0, method='Newton-CG', tol=0.001)
#resolution = minimize(chisqfunc, x0, method='L-BFGS-B', tol=0.001)
#
resolution = minimize(chisqfunc, x0, method='TNC', tol=0.001,
                      options={'scale':None})
# options tried
# 'gtol':1e-6, 'xtol':-1, 'rescale':0, 'ftol':0, 'accuracy':0, 'offset':None, 'scale':None
#
#resolution = minimize(chisqfunc, x0, method='COBYLA', tol=0.001)
#resolution = minimize(chisqfunc, x0, method='SLSQP', tol=0.001)
# Jac required - resolution = minimize(chisqfunc, x0, method='dogleg', tol=0.001)
# Jac required - resolution = minimize(chisqfunc, x0, method='trust-ncg', tol=0.001)
# unknown solver - resolution = minimize(chisqfunc, x0, method='trust-exact', tol=0.001)
# unknown solver - resolution = minimize(chisqfunc, x0, method='trust-krylov', tol=0.001)
print("This is the function",resolution)
print "resolution.x"
print resolution.x
print "p0 should be = " + str(3.5*10**8)
print "r0 should be = " + str(1.5)
#-----------------------------------------------------------------------------
# check answers to see which is better
for index in range(len(v_obs)):
    # declared answer---------------------------------------------------------
    p0 = 3.5*10**8
    r0 = 1.5
    integrals = []
    for i in r:
        integrals.append(quad(integrand, 0, i, args=(p0,r0)))
    #print "integrals = " + str(integrals)
    v_model_declared = []
    sum_error1 = 0.0
    for x in range(0,am):
        k = integrals[x][0]
        i = r[x]
        v_model_declared.append(np.sqrt((4.302*10.0**(-6)*k)/i))
        error1 = (v_obs[x] - v_model_declared[x])**2
        sum_error1 += error1
    #print "v_model = " + str(v_model)

    # computed answer---------------------------------------------------------
    p0 = 8.06400536e+06
    r0 = 4.27905063e+02
    integrals = []
    for i in r:
        integrals.append(quad(integrand, 0, i, args=(p0,r0)))
    #print "integrals = " + str(integrals)
    v_model_computed = []
    sum_error2 = 0.0
    for x in range(0,am):
        k = integrals[x][0]
        i = r[x]
        v_model_computed.append(np.sqrt((4.302*10.0**(-6)*k)/i))
        error2 = (v_obs[x] - v_model_computed[x])**2
        sum_error2 += error2

    print "v_obs, v_model, v_model2 = " + str(v_obs[index]) + ", " + str(v_model_declared[index])+ ", " + str(v_model_computed[index])
#
print "sum_error1 (declared answer) = " + str(sum_error1)
print "sum_error2 (computed answer) = " + str(sum_error2)
print "sqrt(sum_error1) (declared answer) = " + str(np.sqrt(sum_error1))
print "sqrt(sum_error2) (computed answer) = " + str(np.sqrt(sum_error2))
#-----------------------------------------------------------------------------