问:
rails application to download youtube video
How can I create a rails application that will have code to download the video from youtube ?

Is there any API that can be used or any gem available in rails.

Thanks,
gsoni

答:
Create scaffold for storing url and result:

```<code>link:string
data:text
</code>```

You need store hash inside "data", so in your model:

```<code>  serialize :data, Hash
</code>```

Install wrapper for this lib

```<code>gem 'youtube-dl.rb'
</code>```

In your controller after saving link from your form

```<code>  @hash = YoutubeDL.get "#{@link.link}", {skip_download: true}
  @link.data = @hash.information
  @link.save!
</code>```

After that you can get some keys from your data hash. For example:

```<code>@link.data[:title]
</code>```

Body:
Create scaffold for storing url and result:

link:string
data:text

You need store hash inside "data", so in your model:

  serialize :data, Hash

Install wrapper for this lib

gem 'youtube-dl.rb'

In your controller after saving link from your form

  @hash = YoutubeDL.get "#{@link.link}", {skip_download: true}
  @link.data = @hash.information
  @link.save!

After that you can get some keys from your data hash. For example:

@link.data[:title]


来源: stackexchange

问:
running SocketServer as Isolate in dart
I am trying to control dart script via socket, running within isolate
I came up with some (spoiler warning) not working code:

```<code>import "dart:io";
import "dart:convert";
import "dart:isolate";

reader(SendPort sendPort) async {
  var serverSocket = await ServerSocket.bind("127.0.0.1", 83);
  print('connected');
  await for (var socket in serverSocket) {
    socket.transform(UTF8.decoder).listen((msg) => sendPort.send(msg));
  }
}

main() {
  bool start = false;
  bool stop = false;
  listener (message)
  {
    print ("message from isolate: $message");
    stop = start;
    start = true;
  }
  ReceivePort receive = new ReceivePort();
  receive.listen(listener);
Isolate.spawn(reader, receive.sendPort).then((Isolate) => print("Isolate started"));
  print("Waiting to start");
  while (!start) {}
  print("Waiting to stop");
  while (!stop) {}
  print("Ended");
}
</code>```

But isolate does not even seem to be launched. Only output of script is "Waiting to start"

答:
This worked for me:</p>

```<code>import 'dart:async';
import "dart:io";
import "dart:convert";
import "dart:isolate";

reader(SendPort sendPort) async {
  print('isolate started');
  var serverSocket = await ServerSocket.bind("127.0.0.1", 8123);
  sendPort.send('bound');
  await for (var socket in serverSocket) {
    socket.transform(UTF8.decoder).listen((msg) {
      print('server received $msg');
      sendPort.send(msg);
      if (msg == 'close') {
        socket.close();
        serverSocket.close();
      }
    });
  }
}

StreamSubscription subscription;
Isolate isolate;
ReceivePort receive;

main() async {
  listener(message) async {
    print("message from isolate: $message");
    if (message == 'bound') {
      final socket = await Socket.connect("127.0.0.1", 8123);
      print('client connected');
      socket.add('close'.codeUnits);
      socket.destroy();
    }
    if (message == 'close') {
      subscription.cancel();
      // exits application
    }
  }

  receive = new ReceivePort();
  subscription = receive.listen(listener);
  isolate = await Isolate.spawn(reader, receive.sendPort);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: running SocketServer as Isolate in dart

Body:
I am trying to control dart script via socket, running within isolate
I came up with some (spoiler warning) not working code:

import "dart:io";
import "dart:convert";
import "dart:isolate";

reader(SendPort sendPort) async {
  var serverSocket = await ServerSocket.bind("127.0.0.1", 83);
  print('connected');
  await for (var socket in serverSocket) {
    socket.transform(UTF8.decoder).listen((msg) => sendPort.send(msg));
  }
}

main() {
  bool start = false;
  bool stop = false;
  listener (message)
  {
    print ("message from isolate: $message");
    stop = start;
    start = true;
  }
  ReceivePort receive = new ReceivePort();
  receive.listen(listener);
Isolate.spawn(reader, receive.sendPort).then((Isolate) => print("Isolate started"));
  print("Waiting to start");
  while (!start) {}
  print("Waiting to stop");
  while (!stop) {}
  print("Ended");
}

But isolate does not even seem to be launched. Only output of script is "Waiting to start"

Body:
This worked for me:

import 'dart:async';
import "dart:io";
import "dart:convert";
import "dart:isolate";

reader(SendPort sendPort) async {
  print('isolate started');
  var serverSocket = await ServerSocket.bind("127.0.0.1", 8123);
  sendPort.send('bound');
  await for (var socket in serverSocket) {
    socket.transform(UTF8.decoder).listen((msg) {
      print('server received $msg');
      sendPort.send(msg);
      if (msg == 'close') {
        socket.close();
        serverSocket.close();
      }
    });
  }
}

StreamSubscription subscription;
Isolate isolate;
ReceivePort receive;

main() async {
  listener(message) async {
    print("message from isolate: $message");
    if (message == 'bound') {
      final socket = await Socket.connect("127.0.0.1", 8123);
      print('client connected');
      socket.add('close'.codeUnits);
      socket.destroy();
    }
    if (message == 'close') {
      subscription.cancel();
      // exits application
    }
  }

  receive = new ReceivePort();
  subscription = receive.listen(listener);
  isolate = await Isolate.spawn(reader, receive.sendPort);
}


问:
Practice of saving a singleton instance of an angular-service
When I first learned about the angular-redux library, I think the most inviting part of the library was the @select decorator, which meant I wouldn't have to inject the store service every time I want to select from the store.

It made me wonder - how does the decorator get access to that service?

I researched the source code, and stumbled upon the @select and NgRedux (the store service) code.

Apparently, a static instance of the service is saved when the service is initialized, and the decorator accesses this instance.

I wanted to know how acceptable this practice is, since I've liked the idea and I've used it myself to create decorators and rxjs operators for my services, but the idea of saving a singleton is still rather peculiar for me, it feels like a weird hack.

Again, I would love your opinion of how acceptable this practice is, and whether there is a way to use Angular's Dependency Injection to avoid this.

Thanks for reading!

答:
Services that are defined in NgModules are lazy singletons by definition. It means that if you are not going to override service using providers section of component, then you are safe to save references to the service instance.

Main disadvantage is testability problems, it this case you have to pay this price for convenient usage.


问:
Create InternetExplorer object in VB6 that is not a child process
We are creating an InternetExplorer window like this:

```<code>Dim Browser As InternetExplorer
Set Browser = CreateObject("InternetExplorer.Application")
</code>```

We've noticed that if there is an external IE window already opened, then the browser created in our application is created as a child process of that IE process.  If there is no IE window already opened, then the browser our application creates is it's own parent process.

We need to ensure that the browser our application creates is always a top-level parent process, and not the child of another IE process.  Anyone know of a way to do that?

To add a little more information, this first image shows the IE processes that are present if we:

First start our application, which in turn creates a browser window.

Then start another browser (IE) externally.

So there are two browsers running.  Each has two processes (the *32 processes are child processes of the other ones).

Then, if we do things in the other order:

Start external browser.

Start our application, which then creates another browser window.

The picture then looks like this:

In this case, the browser our application creates has been created as a child process of the first (external) browser.  This is what we need to avoid.

答:
First of all, when you use CreateObject(...) then you should use:

```<code>Dim Browser As Object ' not As InternetExplorer
</code>```

Second, the answer is NOT, because it's your application it self that create the child process (Browser).

If you want a top-level process, then dont'use your application, but in this case you can't 'manage' the process, from your application.

Body:
We are creating an InternetExplorer window like this:

Dim Browser As InternetExplorer
Set Browser = CreateObject("InternetExplorer.Application")

We've noticed that if there is an external IE window already opened, then the browser created in our application is created as a child process of that IE process.  If there is no IE window already opened, then the browser our application creates is it's own parent process.

We need to ensure that the browser our application creates is always a top-level parent process, and not the child of another IE process.  Anyone know of a way to do that?

To add a little more information, this first image shows the IE processes that are present if we:

First start our application, which in turn creates a browser window.

Then start another browser (IE) externally.

So there are two browsers running.  Each has two processes (the *32 processes are child processes of the other ones).

Then, if we do things in the other order:

Start external browser.

Start our application, which then creates another browser window.

The picture then looks like this:

In this case, the browser our application creates has been created as a child process of the first (external) browser.  This is what we need to avoid.

Body:
First of all, when you use CreateObject(...) then you should use:

Dim Browser As Object ' not As InternetExplorer

Second, the answer is NOT, because it's your application it self that create the child process (Browser).

If you want a top-level process, then dont'use your application, but in this case you can't 'manage' the process, from your application.


问:
X Path into NVP XML
Can someone please tell me the xpath to select the value for the "FPPRNO" pair in the following doc - I need to select "ABC123":</p>

```<code><lcc:Request Version="1" xmlns:lcc="http://LCC.Integration.Corporate.Schemas.MvcForms.MvcFormsRequestOrResponse">
         <lcc:FormType>HMORenewal</lcc:FormType>
         <lcc:Data>
            <lcc:Pair>
               <lcc:Name>LicenseRefNo</lcc:Name>
               <lcc:Value>16/XXX31/HMO</lcc:Value>
            </lcc:Pair>
            <lcc:Pair>
               <lcc:Name>FPPRNO</lcc:Name>
               <lcc:Value>ABC123</lcc:Value>
            </lcc:Pair>
                                <lcc:Pair>
               <lcc:Name>ApplyAccreditationDiscount</lcc:Name>
               <lcc:Value>False</lcc:Value>
            </lcc:Pair>
                                <lcc:Pair>
               <lcc:Name>NumberOfTenants</lcc:Name>
               <lcc:Value>5</lcc:Value>
            </lcc:Pair>
         </lcc:Data>
      </lcc:Request>
</code>```

答:
I got it!</p>

```<code>//*[lcc:Name = 'FPPRNO']/lcc:Value/text()
</code>```

Title: X Path into NVP XML

Body:
Can someone please tell me the xpath to select the value for the "FPPRNO" pair in the following doc - I need to select "ABC123":

<lcc:Request Version="1" xmlns:lcc="http://LCC.Integration.Corporate.Schemas.MvcForms.MvcFormsRequestOrResponse">
         <lcc:FormType>HMORenewal</lcc:FormType>
         <lcc:Data>
            <lcc:Pair>
               <lcc:Name>LicenseRefNo</lcc:Name>
               <lcc:Value>16/XXX31/HMO</lcc:Value>
            </lcc:Pair>
            <lcc:Pair>
               <lcc:Name>FPPRNO</lcc:Name>
               <lcc:Value>ABC123</lcc:Value>
            </lcc:Pair>
                                <lcc:Pair>
               <lcc:Name>ApplyAccreditationDiscount</lcc:Name>
               <lcc:Value>False</lcc:Value>
            </lcc:Pair>
                                <lcc:Pair>
               <lcc:Name>NumberOfTenants</lcc:Name>
               <lcc:Value>5</lcc:Value>
            </lcc:Pair>
         </lcc:Data>
      </lcc:Request>

Body:
I got it!

//*[lcc:Name = 'FPPRNO']/lcc:Value/text()


问:
Possible values for R resources
I am using the R.drawable.x values as keys in a hashmap, but I need a value that means the absence of a drawable. For this I need to know what the possible values for R resources are. Does anybody know this or is it defined somewhere?</p>

答:
Accordind to the Ressources documentation there is a method getIdentifier() to get the int value of a ressource and they precise :

Returns 0 if no such resource was found. (0 is not a valid resource
  ID.)

So 0 seem to work.

Hope this helps.
Sorry for my english.

Title: Possible values for R resources


问:
Is it possible to modify code generated by PhoneGap and how would this effect apps market application process?
Is it possible to modify/supplement code generated by PhoneGap to modify/add functionality? And how does this effect the application's likelihood of being accepted into the apps market?

The reason I am asking is because there are certain components of the desired iPhone application that we would like to have that we can not achieve with our converted CakePHP web application. These desired items include QR code scanning and augmented reality.

答:
Yes, you can do that.

https://github.com/phonegap/phonegap-plugins

You can look there for already written (and validated) plugins.

If I remember correctly, a qrscanner plugin already exists.

Augmented reality it not really possible with phonegap. (At least not as far as I know) As you can't manipulate the camera view with phonegap.

Maby if you would write a plugin for it. But that would mean writing almost the whole application in objective-C.

ContentLicense: CC BY-SA 2.5


问:
How to set margin for Vertical Scrollbar from the right edge in ListView?
For Android Platform:

I need to put margin on right side of the vertical scrollbar in listview (it is customized). Please see the attached image. Default scrollbar sticks to the extream right side of the listview.

Need your hand. Thanks.

答:
Try enabling fast scroll, it does the job most of the time:</p>

```<code><ListView
    android:id="@+id/chapter_list"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fastScrollEnabled="true"/>
</code>```

Body:
Try enabling fast scroll, it does the job most of the time:

<ListView
    android:id="@+id/chapter_list"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fastScrollEnabled="true"/>


问:
AngularJS: templateUrl works for a HTML template file, but it doesn't with a .JSP
Im building a controller-template in angularJS as simple as:

```<code>var maintest = angular.module("mainTest", []);
angular.module("mainTest")
        .component('mainscreen', {
        templateUrl: './services/fakeService.html',
        controller: function example(){
                    this.userData = 'Jospeh';
                }
        } );
</code>```

If the template is a HTML file as shown above, it works fine. But if you try to use a .JSP template, it doesn't at all (code of fakeService.jsp below).

HTML (fakeService.html):

```<code><!DOCTYPE html>
<div>
    Data to show: {{$ctrl.userData}}
</div>
</code>```

Output of HTML (called from component mainscreen):

Data to show: Jospeh

JSP (fakeService.jsp):

```<code><%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
out.print("Test if JSP code is processed.");
%>
<div>
    Data to show: {{$ctrl.userData}}
</div>
</code>```

Output of JSP (called from component mainscreen):

Test if JSP code is processed. Data to show: {{$ctrl.userData}}

Can I use AngularJS + JSP? If I can, how it comes this simple example doesn't work?

Thank you all.

答:
I am not sure how you are implementing the server side. I recommend to follow MVC deign approach and make the templates extension agnostic. Here is a sample from my project,

```<code> // route for the home page
 .when('/home', {
     templateUrl : 'home',
     controller  : 'homeController'
 })
</code>```

On the server side, I have an MVC controller, which captures the uri "/home", resolves the view  (it is up to the logic in the view resolver, whether it is going to be a jsp, or html or whatever) and passes the results back. This case, angular has no clue what is on the server side, which also promotes loose coupling.

Body:
Im building a controller-template in angularJS as simple as:

var maintest = angular.module("mainTest", []);
angular.module("mainTest")
        .component('mainscreen', {
        templateUrl: './services/fakeService.html',
        controller: function example(){
                    this.userData = 'Jospeh';
                }
        } );

If the template is a HTML file as shown above, it works fine. But if you try to use a .JSP template, it doesn't at all (code of fakeService.jsp below).

HTML (fakeService.html):

<!DOCTYPE html>

    Data to show: {{$ctrl.userData}}

Output of HTML (called from component mainscreen):

Data to show: Jospeh

JSP (fakeService.jsp):

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
out.print("Test if JSP code is processed.");
%>

    Data to show: {{$ctrl.userData}}

Output of JSP (called from component mainscreen):

Test if JSP code is processed. Data to show: {{$ctrl.userData}}

Can I use AngularJS + JSP? If I can, how it comes this simple example doesn't work?

Thank you all.

Body:
I am not sure how you are implementing the server side. I recommend to follow MVC deign approach and make the templates extension agnostic. Here is a sample from my project,

 // route for the home page
 .when('/home', {
     templateUrl : 'home',
     controller  : 'homeController'
 })

On the server side, I have an MVC controller, which captures the uri "/home", resolves the view  (it is up to the logic in the view resolver, whether it is going to be a jsp, or html or whatever) and passes the results back. This case, angular has no clue what is on the server side, which also promotes loose coupling.


问:
Unknown Slot types
I have just started looking into making a basic Alexa skill.

I want to create a skill that repeats what a user says. For example "Alexa, repeat 'hello'".

What slot type would I use for hello as I am unaware of what the user will say?

答:
@Josep Valls answer is false:

The Amazon.LITERAL Slot-Type can still be used. Amazon planned on removing it, but due to developer feedback reverted that decision. Here is the documentation.

Even without the literal type you can catch everything an user says. This includes values that are not pre-defined. Quoting this:

"When you create a custom slot type, a key concept to understand is
  that this is training data for Alexa’s NLP (natural language
  processing). The values you provide are NOT a strict enum or array
  that limit what the user can say. This has two implications 1) words
  and phrases not in your slot values will be passed to you, 2) your
  code needs to perform any validation you require if what’s said is
  unknown."

ContentLicense: CC BY-SA 4.0

Title: Unknown Slot types


问:
Can't resolve symbol 'thisActivity'
I'm a new android developer.  I'm trying to get my app to check permissions and I found this bit of code here

```<code>int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
            Manifest.permission.ACCESS_NOTIFICATION_POLICY);
</code>```

The problem I'm having is that thisActivityis showing up with the error "Can't resolve symbol 'thisActivity'.

答:
thisActivity is nothing but the refrence of your current activity.

Call it like this,

In case of activity:

```<code>ContextCompat.checkSelfPermission(MyActivity.this,
        Manifest.permission.ACCESS_NOTIFICATION_POLICY);
</code>```

In case of fragment:

```<code>ContextCompat.checkSelfPermission(getActivity(),
        Manifest.permission.ACCESS_NOTIFICATION_POLICY);
</code>```

Title: Can't resolve symbol 'thisActivity'

Body:
I'm a new android developer.  I'm trying to get my app to check permissions and I found this bit of code here

int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
            Manifest.permission.ACCESS_NOTIFICATION_POLICY);

The problem I'm having is that thisActivityis showing up with the error "Can't resolve symbol 'thisActivity'.

Body:
thisActivity is nothing but the refrence of your current activity.

Call it like this,

In case of activity:

ContextCompat.checkSelfPermission(MyActivity.this,
        Manifest.permission.ACCESS_NOTIFICATION_POLICY);

In case of fragment:

ContextCompat.checkSelfPermission(getActivity(),
        Manifest.permission.ACCESS_NOTIFICATION_POLICY);


问:
How can I display two lists with each li element vertically under each other?
I have two separate lists (however I'm open for an example on how to just have one). The first list is information (such as 'title', 'length' 'release date') and the second list is the answers to the information (such as '50 Shades of Grey', '50 minutes' and '2015').

Here is my desired output and as you can see, the answers to the information is vertically centered under the information:

(Note there could be more information such as members of the cast, the budget e.g)

I have tried using Flex however the two lists are displayed separately on top of each other:

ul {
   white-space:nowrap;
}

li {
   display: flex;
   justify-content: center;
   flex-direction: column;
   text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
<li>Title</li>
<li>Length</li>
<li>Release Date</li>
</ul>
<ul>
<li>50 Shades of Grey</li>
<li>50 minutes</li>
<li>2015</li>
</ul></code>```

答:
Assuming you want each line to align even if content in one of the items would be higher, you need to have one (in this case) ul and then size the items so they wrap per, in this case, every 3.

To also make sure each item has the same width, I use flex-basis.

ul {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;       /*  create space between columns  */
  list-style: none;
  padding: 0;
}

li:nth-child(-n+3) {                    /*  first 3 items  */
  font-size: 24px;
  font-weight: bold;
}

li {
  flex-basis: calc(33.333% - 10px);     /*  1/3 minus 10px for a gutter  */
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  text-align: flex-start;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Title</li>
  <li>Length</li>
  <li>Release Date</li>

  <li>50 Shades of Grey</li>
  <li>50 minutes</li>
  <li>2015</li>

  <li>50 Shades of Black, and a longer text so it breaks line</li>
  <li>50 minutes</li>
  <li>2015</li>

  <li>50 Shades of Grey</li>
  <li>50 minutes</li>
  <li>2015</li>

</ul></code>```

Body:
I have two separate lists (however I'm open for an example on how to just have one). The first list is information (such as 'title', 'length' 'release date') and the second list is the answers to the information (such as '50 Shades of Grey', '50 minutes' and '2015').

Here is my desired output and as you can see, the answers to the information is vertically centered under the information:

(Note there could be more information such as members of the cast, the budget e.g)

I have tried using Flex however the two lists are displayed separately on top of each other:

ul {
   white-space:nowrap;
}

li {
   display: flex;
   justify-content: center;
   flex-direction: column;
   text-align: center;
}

Title

Length

Release Date

50 Shades of Grey

50 minutes

2015

Body:
Assuming you want each line to align even if content in one of the items would be higher, you need to have one (in this case) ul and then size the items so they wrap per, in this case, every 3.

To also make sure each item has the same width, I use flex-basis.

ul {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;       /*  create space between columns  */
  list-style: none;
  padding: 0;
}

li:nth-child(-n+3) {                    /*  first 3 items  */
  font-size: 24px;
  font-weight: bold;
}

li {
  flex-basis: calc(33.333% - 10px);     /*  1/3 minus 10px for a gutter  */
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  text-align: flex-start;
}

<ul>
  <li>Title</li>
  <li>Length</li>
  <li>Release Date</li>

  <li>50 Shades of Grey</li>
  <li>50 minutes</li>
  <li>2015</li>

  <li>50 Shades of Black, and a longer text so it breaks line</li>
  <li>50 minutes</li>
  <li>2015</li>

  <li>50 Shades of Grey</li>
  <li>50 minutes</li>
  <li>2015</li>

</ul>


问:
How to set maxDate in jquery datepicker based on certain value
I am trying to set maxDate based on user selection of given input date, suppose if user select today date then the maxDate should be set to 3 or 4 days from today or even a week upto max.But i am using the following logic to set minDate automatically based on user input selection

```<code> $(checkIn).datepicker(
           {
                changeMonth:false,
                changeYear:false,
                dateFormat: 'dd/mm/yy',
                minDate:0
           });
           var temp;
           $(checkIn).on("change",function()
           {
               var select = $(this).datepicker("getDate");
               temp=select;
               $(checkOut).datepicker('option','minDate',temp)

           })
</code>```

This logic work fines here but when i am trying to set maxDate based on this logic i am getting certain error here is the code

```<code>$(checkOut).datepicker({
               changeMonth:false,
                changeYear:false,
                dateFormat: 'dd/mm/yy',
                maxDate: new Date($(checkIn).val()) + "1w"
    })
</code>```

When i run this code what happen is if i select today's date for instance it gives correct maxDate till upto 7 days but if i again change the date in checkIn input the maxDate is one day less and thus as i keep selecting forward date ahead from current date a point will come where all the date in checkOut input are disabled and i cant select any of it.

答:
You can remove the change event and use the beforeShow callback in order to set the maxDate for the second datepicker like in:

$('#checkIn').val($.datepicker.formatDate('dd/mm/yy', new Date()));
$('#checkIn').datepicker({
    changeMonth: false,
    changeYear: false,
    dateFormat: 'dd/mm/yy',
    minDate: 0,
});

$('#checkOut').datepicker({
    changeMonth:false,
    changeYear:false,
    dateFormat: 'dd/mm/yy',
    beforeShow: function(input, inst) {
        var minDate = $('#checkIn').datepicker('getDate');
        $('#checkOut').datepicker('option', 'minDate', minDate);
        var maxDate = new Date(minDate.valueOf());
        maxDate.setDate(maxDate.getDate() + 7);
        $('#checkOut').datepicker('option', 'maxDate', maxDate);
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

<p>Chack In date: <input type="text" id="checkIn"></p>

<p>Check Out date: <input type="text" id="checkOut"></p></code>```

Body:
I am trying to set maxDate based on user selection of given input date, suppose if user select today date then the maxDate should be set to 3 or 4 days from today or even a week upto max.But i am using the following logic to set minDate automatically based on user input selection

 $(checkIn).datepicker(
           {
                changeMonth:false,
                changeYear:false,
                dateFormat: 'dd/mm/yy',
                minDate:0
           });
           var temp;
           $(checkIn).on("change",function()
           {
               var select = $(this).datepicker("getDate");
               temp=select;
               $(checkOut).datepicker('option','minDate',temp)

           })

This logic work fines here but when i am trying to set maxDate based on this logic i am getting certain error here is the code

$(checkOut).datepicker({
               changeMonth:false,
                changeYear:false,
                dateFormat: 'dd/mm/yy',
                maxDate: new Date($(checkIn).val()) + "1w"
    })

When i run this code what happen is if i select today's date for instance it gives correct maxDate till upto 7 days but if i again change the date in checkIn input the maxDate is one day less and thus as i keep selecting forward date ahead from current date a point will come where all the date in checkOut input are disabled and i cant select any of it.

Body:
You can remove the change event and use the beforeShow callback in order to set the maxDate for the second datepicker like in:

$('#checkIn').val($.datepicker.formatDate('dd/mm/yy', new Date()));
$('#checkIn').datepicker({
    changeMonth: false,
    changeYear: false,
    dateFormat: 'dd/mm/yy',
    minDate: 0,
});

$('#checkOut').datepicker({
    changeMonth:false,
    changeYear:false,
    dateFormat: 'dd/mm/yy',
    beforeShow: function(input, inst) {
        var minDate = $('#checkIn').datepicker('getDate');
        $('#checkOut').datepicker('option', 'minDate', minDate);
        var maxDate = new Date(minDate.valueOf());
        maxDate.setDate(maxDate.getDate() + 7);
        $('#checkOut').datepicker('option', 'maxDate', maxDate);
    }
});

<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

<p>Chack In date: <input type="text" id="checkIn"></p>

<p>Check Out date: <input type="text" id="checkOut"></p>


问:
webpack-dev-server get blank screen
Greetings I'm building a MERN stack for the first time and using Webpack  as my build tool. The goal is to have the API's of the app served by Express and the static content(my static dir) and bundles served by webpack-dev-server.

```<code>Here is my build:
Project is running at http://localhost:8000/
webpack output is served from /
Content not from webpack is served from static
Hash: 0f82642b68722fddb0c7
Version: webpack 3.1.0
Time: 3941ms
           Asset     Size  Chunks                    Chunk Names
   app.bundle.js  15.4 kB       0  [emitted]         app
vendor.bundle.js  1.35 MB       1  [emitted]  [big]  vendor
  [10] (webpack)/buildin/global.js 509 bytes {1} [built]
  [80] ./node_modules/react/react.js 56 bytes {1} [built]
 [153] (webpack)-dev-server/client?http://localhost:8000 5.59 kB {1} [built]
 [171] (webpack)/hot/dev-server.js 1.61 kB {1} [built]
 [173] ./node_modules/babel-polyfill/lib/index.js 833 bytes {1} [built]
 [209] ./node_modules/react-dom/index.js 59 bytes {1} [built]
 [235] ./node_modules/whatwg-fetch/fetch.js 12.7 kB {1} [built]
 [236] multi (webpack)-dev-server/client?http://localhost:8000 webpack/hot/dev-server ./src/App.jsx 52 bytes {0} [built]
 [237] ./node_modules/url/url.js 23.3 kB {1} [built]
 [243] ./node_modules/strip-ansi/index.js 161 bytes {1} [built]
 [245] (webpack)-dev-server/client/socket.js 856 bytes {1} [built]
 [284] ./src/App.jsx 655 bytes {0} [built]
 [482] ./node_modules/react-dom/lib/ReactDOM.js 5.17 kB {1} [built]
 [567] ./src/IssueList.jsx 8.32 kB {0} [built]
 [570] multi (webpack)-dev-server/client?http://localhost:8000 webpack/hot/dev-server react react-dom whatwg-fetch babel-polyfill 88 bytes {1} [built]
    + 556 hidden modules
webpack: Compiled successfully.

My dependencies:
"dependencies": {
    "body-parser": "^1.17.2",
    "express": "^4.15.3",
    "mongodb": "^2.2.29"
  },
"devDependencies": {
    "babel-cli": "^6.24.1",
    "babel-core": "^6.25.0",
    "babel-loader": "^7.1.1",
    "babel-polyfill": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "nodemon": "^1.11.0",
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "webpack": "^3.0.0",
    "webpack-dev-server": "^2.5.1",
    "whatwg-fetch": "^2.0.3"
  }

My webpack.config.js file:

    const webpack = require('webpack');
    const path = require('path');

    module.exports = {
        entry: {
            app: './src/App.jsx',
            vendor:['react', 'react-dom', 'whatwg-fetch'],
        },
        output: {
            path: path.resolve(__dirname, './static'),
            filename: "app.bundle.js"
        },
        plugins: [
          new webpack.optimize.CommonsChunkPlugin({name: 'vendor',filename: 'vendor.bundle.js'})
        ],
        module: {
            rules:[
                {
                    test:/\.jsx$/,
                    use: {
                        loader: 'babel-loader',
                        options: {
                            presets: ['react','es2015']
                        }
                    }
                },
            ]
        },

        devServer:{
            port: 8000,
                contentBase: '/Users/Angel/WebstormProjects/myMern/static',
                proxy: {
                '/api/*':{
                    target: 'http://localhost:3000',
                }
            }
        }

    };
</code>```

When I open port: 8000 I get a blank screen but all the network traffic is good.... I'm I missing something?

Thank you.

答: You need to add an index.html to your webpak config, so it can work with it. Try to use html-webpack-plugin and/or html-loader.</p>

Title: webpack-dev-server get blank screen

Body:
Greetings I'm building a MERN stack for the first time and using Webpack  as my build tool. The goal is to have the API's of the app served by Express and the static content(my static dir) and bundles served by webpack-dev-server.

Here is my build:
Project is running at http://localhost:8000/
webpack output is served from /
Content not from webpack is served from static
Hash: 0f82642b68722fddb0c7
Version: webpack 3.1.0
Time: 3941ms
           Asset     Size  Chunks                    Chunk Names
   app.bundle.js  15.4 kB       0  [emitted]         app
vendor.bundle.js  1.35 MB       1  [emitted]  [big]  vendor
  [10] (webpack)/buildin/global.js 509 bytes {1} [built]
  [80] ./node_modules/react/react.js 56 bytes {1} [built]
 [153] (webpack)-dev-server/client?http://localhost:8000 5.59 kB {1} [built]
 [171] (webpack)/hot/dev-server.js 1.61 kB {1} [built]
 [173] ./node_modules/babel-polyfill/lib/index.js 833 bytes {1} [built]
 [209] ./node_modules/react-dom/index.js 59 bytes {1} [built]
 [235] ./node_modules/whatwg-fetch/fetch.js 12.7 kB {1} [built]
 [236] multi (webpack)-dev-server/client?http://localhost:8000 webpack/hot/dev-server ./src/App.jsx 52 bytes {0} [built]
 [237] ./node_modules/url/url.js 23.3 kB {1} [built]
 [243] ./node_modules/strip-ansi/index.js 161 bytes {1} [built]
 [245] (webpack)-dev-server/client/socket.js 856 bytes {1} [built]
 [284] ./src/App.jsx 655 bytes {0} [built]
 [482] ./node_modules/react-dom/lib/ReactDOM.js 5.17 kB {1} [built]
 [567] ./src/IssueList.jsx 8.32 kB {0} [built]
 [570] multi (webpack)-dev-server/client?http://localhost:8000 webpack/hot/dev-server react react-dom whatwg-fetch babel-polyfill 88 bytes {1} [built]
    + 556 hidden modules
webpack: Compiled successfully.

My dependencies:
"dependencies": {
    "body-parser": "^1.17.2",
    "express": "^4.15.3",
    "mongodb": "^2.2.29"
  },
"devDependencies": {
    "babel-cli": "^6.24.1",
    "babel-core": "^6.25.0",
    "babel-loader": "^7.1.1",
    "babel-polyfill": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "nodemon": "^1.11.0",
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "webpack": "^3.0.0",
    "webpack-dev-server": "^2.5.1",
    "whatwg-fetch": "^2.0.3"
  }

My webpack.config.js file:

    const webpack = require('webpack');
    const path = require('path');

    module.exports = {
        entry: {
            app: './src/App.jsx',
            vendor:['react', 'react-dom', 'whatwg-fetch'],
        },
        output: {
            path: path.resolve(__dirname, './static'),
            filename: "app.bundle.js"
        },
        plugins: [
          new webpack.optimize.CommonsChunkPlugin({name: 'vendor',filename: 'vendor.bundle.js'})
        ],
        module: {
            rules:[
                {
                    test:/\.jsx$/,
                    use: {
                        loader: 'babel-loader',
                        options: {
                            presets: ['react','es2015']
                        }
                    }
                },
            ]
        },

        devServer:{
            port: 8000,
                contentBase: '/Users/Angel/WebstormProjects/myMern/static',
                proxy: {
                '/api/*':{
                    target: 'http://localhost:3000',
                }
            }
        }

    };

When I open port: 8000 I get a blank screen but all the network traffic is good.... I'm I missing something?

Thank you.


问:
Custom popup/login screen when people connect to wifi network
I have a belkin router. When people connect to this via wifi to access the internet I want to display a custom popup window similar to when you go to a coffee shop and connect to free public wifi connections.

How does one go about this?

答:
You can use http://www.hotspotsystem.com/hotspot-software

You'll also require a compatible router, a router which can be flashed with the DD-WRT custom firmware will do the job.


问:
How to search locations by given a name in iPhone SDK?
I want to search by a name (String) and then get at least 10 matching locations with their longitude and latitude.

Let's say I type 'Jaipur' in my search bar, i need to request some map service and get 10 locations that start with 'Jaipur'.

It seems we cannot do this with Map Kit.

Could someone point me few little tips to get started. It seems Yahoo Maps return JSON with one value. Any API that I could use easily with JSON parsing and example request would be really helpful.

Thanks and Kind Regards,

答: What about using something like foursquare? They offer a developer API found here.</p>


问:
C# naming convention for extension methods for interface
I typically name my C# interfaces as IThing.  I'm creating an extension method class for IThing, but I don't know what to name it.  On one hand, calling it ThingExtensions seems to imply it is an extension class to some Thing class instead of to the IThing interface.  It also makes the extension class be sorted away from the interface it extends, when viewing files alphabetically.  On the other hand, naming it IThingExtensions makes it look like it is an interface itself, instead of an extension class for an interface.  What would you suggest?

Edit:  there is not a Thing class that implements IThing, in response to some of the comments.

答:
I've taken a slightly different approach, and rather than suffix with Extension reversed the naming strategy to prefix the class containing the extension methods with Extend; my rationale is as follows:

As pointed out in Reed Copsey's answer, very (very) seldom will client code reference the containing class directly as the very point of extension methods is to emulate reference methods. They won't see the classes, so your class naming convention choice should have insignificant impact.

The classes must be static, and thus you'll never instantiate them. Therefore you never end up with the semantic oddity of new ExtendThing() as far as naming is concerned.

All of your Extend* classes are visually grouped with alpha file sorting.

And with respect to your question specifically, there isn't any interface naming prefix confusion; you can have ExtendThing and ExtendIThing and (IMO) their intent and target is clear.

```<code>namespace MyCompany.Extensions
{
    public static class ExtendObject { }

    public static class ExtendDateTime { }

    public static class ExtendIEnumerable { }
}
</code>```

Body:
I've taken a slightly different approach, and rather than suffix with Extension reversed the naming strategy to prefix the class containing the extension methods with Extend; my rationale is as follows:

As pointed out in Reed Copsey's answer, very (very) seldom will client code reference the containing class directly as the very point of extension methods is to emulate reference methods. They won't see the classes, so your class naming convention choice should have insignificant impact.

The classes must be static, and thus you'll never instantiate them. Therefore you never end up with the semantic oddity of new ExtendThing() as far as naming is concerned.

All of your Extend* classes are visually grouped with alpha file sorting.

And with respect to your question specifically, there isn't any interface naming prefix confusion; you can have ExtendThing and ExtendIThing and (IMO) their intent and target is clear.

namespace MyCompany.Extensions
{
    public static class ExtendObject { }

    public static class ExtendDateTime { }

    public static class ExtendIEnumerable { }
}


问:
Update only time in a SQL Server DateTime column from another DateTime column in the same table
I have a table that contains two DateTime columns. I would like to update my table so that it would copy the time only from column A and update that time only in column B without changing the actual date itself. Here is my data:

```<code>Column A                   | Column B
---------------------------+-------------------------
2017-07-07 16:30:00.000    | 2017-08-30 22:05:00.000
</code>```

The desired output is:

```<code>Column A                  | Column B
--------------------------+------------------------
2017-07-07 16:30:00.000   | 2017-08-30 16:30:00.000
</code>```

I tried to get this done but I cannot figure out the correct syntax or if it is even possible. Thank you all in advance for your help and direction.

Body:
I have a table that contains two DateTime columns. I would like to update my table so that it would copy the time only from column A and update that time only in column B without changing the actual date itself. Here is my data:

Column A                   | Column B
---------------------------+-------------------------
2017-07-07 16:30:00.000    | 2017-08-30 22:05:00.000

The desired output is:

Column A                  | Column B
--------------------------+------------------------
2017-07-07 16:30:00.000   | 2017-08-30 16:30:00.000

I tried to get this done but I cannot figure out the correct syntax or if it is even possible. Thank you all in advance for your help and direction.

Body:
Adding the time from a to b after truncating the time portion of b:

select
    a
  , b = dateadd(second,datediff(second,convert(date,a),a),convert(datetime,convert(date,b)))
from t

rextester demo: http://rextester.com/IRTP42230

returns:

+---------------------+---------------------+
|          a          |          b          |
+---------------------+---------------------+
| 2017-07-07 16:30:00 | 2017-08-30 16:30:00 |
+---------------------+---------------------+


答:
Once quick option is</p>

```<code>Update YourTable
   set [Column B] = cast(cast([Column B] as date) as datetime)+cast(cast([Column A] as time) as datetime)
</code>```

Title: Update only time in a SQL Server DateTime column from another DateTime column in the same table

Body:
Once quick option is

Update YourTable
   set [Column B] = cast(cast([Column B] as date) as datetime)+cast(cast([Column A] as time) as datetime)


问:
bash getopts ignores options unless they are specified in a certain way
Bash getopts should allow for options and arguments not to depend on position, as stated in tutorials and docs.

The following snippet of code could receive two options:

a debug -d option which requires an argument

a force -f option, without arguments.

I am seeing the strange behavior that only the first option listed gets processed correctly.

```<code>#!/bin/bash

## Defaults
DEBUG=INFO
forceOption=FALSE

## Usage
printUsage() {
    echo "  "
    echo "USAGE: $0 [-d <DEBUG_LEVEL>] [ -f ]"
    echo "  "
    exit 1
}

#
## Manage options before start
#

while getopts "hfd:" OPT
do
    case $OPT in
        h) printUsage ;;
        f) forceOption="TRUE" ;;
        d) debugLevel="$OPTARG" ;;
        *) printUsage ;;
    esac
    shift `expr $OPTIND - 1`
done

if [ -n "$debugLevel" ] ; then
    DEBUG="$debugLevel"
fi

echo "DEBUG : $DEBUG"
echo "Force : $forceOption"
</code>```

You can see the faulty behavior below:

```<code>[rgulia$ ~] ./getopts.sh -d WARNING -f
DEBUG : WARNING
Force : FALSE
[rgulia$ ~] ./getopts.sh -f -d WARNING
DEBUG : INFO
Force : TRUE
</code>```

The code parses correctly when the options are used separately or if -f precedes -d in the list of options and they are attached to each other

```<code>[rgulia$ ~] ./getopts.sh -f
DEBUG : INFO
Force : TRUE
[rgulia$ ~] ./getopts.sh -d WARNING
DEBUG : WARNING
Force : FALSE
[rgulia$ ~] ./getopts.sh -fd WARNING
DEBUG : WARNING
Force : TRUE
</code>```

My impression is that the loop exits too early because it fails to compute OPTIND correctly when an option is passed an argument.

I did some tracing with printf statements for the values of OPT, OPTARG and OPTIND confirms such theory, but I still do not understand why it is happening and how to fix it.

Any suggestions?

答: Take the shift out of the loop. OPTIND is an absolute index into the original arg vector. Do the shift once after the loop </p>

Body:
Bash getopts should allow for options and arguments not to depend on position, as stated in tutorials and docs.

The following snippet of code could receive two options:

a debug -d option which requires an argument

a force -f option, without arguments.

I am seeing the strange behavior that only the first option listed gets processed correctly.

#!/bin/bash

## Defaults
DEBUG=INFO
forceOption=FALSE

## Usage
printUsage() {
    echo "  "
    echo "USAGE: $0 [-d <DEBUG_LEVEL>] [ -f ]"
    echo "  "
    exit 1
}

#
## Manage options before start
#

while getopts "hfd:" OPT
do
    case $OPT in
        h) printUsage ;;
        f) forceOption="TRUE" ;;
        d) debugLevel="$OPTARG" ;;
        *) printUsage ;;
    esac
    shift `expr $OPTIND - 1`
done

if [ -n "$debugLevel" ] ; then
    DEBUG="$debugLevel"
fi

echo "DEBUG : $DEBUG"
echo "Force : $forceOption"

You can see the faulty behavior below:

[rgulia$ ~] ./getopts.sh -d WARNING -f
DEBUG : WARNING
Force : FALSE
[rgulia$ ~] ./getopts.sh -f -d WARNING
DEBUG : INFO
Force : TRUE

The code parses correctly when the options are used separately or if -f precedes -d in the list of options and they are attached to each other

[rgulia$ ~] ./getopts.sh -f
DEBUG : INFO
Force : TRUE
[rgulia$ ~] ./getopts.sh -d WARNING
DEBUG : WARNING
Force : FALSE
[rgulia$ ~] ./getopts.sh -fd WARNING
DEBUG : WARNING
Force : TRUE

My impression is that the loop exits too early because it fails to compute OPTIND correctly when an option is passed an argument.

I did some tracing with printf statements for the values of OPT, OPTARG and OPTIND confirms such theory, but I still do not understand why it is happening and how to fix it.

Any suggestions?


问:
why the scrapy yield.Request() did not Recursive？
here is my code?

```<code>class QuotesSpider(scrapy.Spider):
name = 'quotes'
allowed_domains = ['quotes.toscrape.com/']
start_urls = ['http://quotes.toscrape.com//']

def parse(self, response):
    quotes = response.css('.quote')
    for quote in quotes:
        item = QuoteItem()
        text = quote.css('.text::text').extract_first()
        author = quote.css('.author::text').extract_first()
        tags = quote.css('.tags .tag::text').extract()
        item['text'] = text
        item['author'] = author
        item['tags'] = tags
        yield item

    next = response.css('.pager .next a::attr(href)').extract_first()
    url = response.urljoin(next)
    yield scrapy.Request(url=url, callback=self.parse)
</code>```

I am new to scrapy. I think this will always Recursive.But actually it didn't.That's why?

答:
the problem here is that scrapy uses allowed_domains as a regex for determining if the links passing through belong to the specified domain.

just change the string quotes.toscrape.com/ to quotes.toscrape.com if you only want to allow requests from that specific subdomain.

You can also remove that entire variable if you want to allow requests from every domain.

Body:
here is my code?

class QuotesSpider(scrapy.Spider):
name = 'quotes'
allowed_domains = ['quotes.toscrape.com/']
start_urls = ['http://quotes.toscrape.com//']

def parse(self, response):
    quotes = response.css('.quote')
    for quote in quotes:
        item = QuoteItem()
        text = quote.css('.text::text').extract_first()
        author = quote.css('.author::text').extract_first()
        tags = quote.css('.tags .tag::text').extract()
        item['text'] = text
        item['author'] = author
        item['tags'] = tags
        yield item

    next = response.css('.pager .next a::attr(href)').extract_first()
    url = response.urljoin(next)
    yield scrapy.Request(url=url, callback=self.parse)

I am new to scrapy. I think this will always Recursive.But actually it didn't.That's why?


问:
Enforcing newlines separating code blocks in eslint
I've been scouring the Eslint rule docs and cannot figure out how to enforce newlines between blocks.

For example, in jscs I can reject these for having no separating new line:

```<code>if (!rows.length) {
  // code
}
var pagination;
if (something) {
  // code
}
</code>```

"space-before-blocks" sounded like it's what I wanted but it applies only to spaces, not newlines.

答:
Response is a bit late but you can now use the padding-line-between-statements rule for this: http://eslint.org/docs/rules/padding-line-between-statements

I think the config you'd want would be something like

```<code>"padding-line-between-statements": [
  "warn",
  { blankLine: 'always', prev: '*', next: 'block' },
  { blankLine: 'always', prev: 'block', next: '*' },
  { blankLine: 'always', prev: '*', next: 'block-like' },
  { blankLine: 'always', prev: 'block-like', next: '*' },
]
</code>```

Body:
I've been scouring the Eslint rule docs and cannot figure out how to enforce newlines between blocks.

For example, in jscs I can reject these for having no separating new line:

if (!rows.length) {
  // code
}
var pagination;
if (something) {
  // code
}

"space-before-blocks" sounded like it's what I wanted but it applies only to spaces, not newlines.

Body:
Response is a bit late but you can now use the padding-line-between-statements rule for this: http://eslint.org/docs/rules/padding-line-between-statements

I think the config you'd want would be something like

"padding-line-between-statements": [
  "warn",
  { blankLine: 'always', prev: '*', next: 'block' },
  { blankLine: 'always', prev: 'block', next: '*' },
  { blankLine: 'always', prev: '*', next: 'block-like' },
  { blankLine: 'always', prev: 'block-like', next: '*' },
]


问:
Function that Inserts a node into a linked list sorted
```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_MODEL 25
#define MAX_LINE 50
typedef struct car{
    char* model;
    char* color;
    int year;
    struct car* next;
}car;
car* readFromFile(FILE*);
car* insertInSortedOrder(car*, char*, char*, int);
car* createCar(char*, char*, int);
void printCars(car*);

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

    //creating a file pointer, opening file
    FILE* fptr;
    fptr = fopen(*(argv+1), "r");
    car* head = NULL;

    //this first reads cars from files, puts it into linked list and prints
    head = readFromFile(fptr);
    puts("do we get here");
    printCars(head);
    return 0;
}
///this function reads information from a text file, sends it to insertInSortedOrder function
car* readFromFile(FILE* fptr){

    char *M, *C, *year;
    char *readLine= malloc(sizeof(car)*MAX_MODEL);
    int yr;

    car *head=NULL;
    while(fgets(readLine,MAX_LINE,fptr)!= NULL){
            M = strtok(readLine,"|");
            C = strtok(NULL,"|");
            year = strtok(NULL,"|");
            yr = atoi(year);
            head = insertInSortedOrder(head,M,C,yr);
    }
    return head;
}
//this function sends new info to createCar to put it into a list, gets it and puts it
//into sorted order according to alphabetical order by model
car* insertInSortedOrder(car* head, char* model, char* color, int year){

    //if list is emppty
    if(head == NULL){
            head = createCar(model,color,year);
    }
    else{
            car *new = createCar(model,color,year);
            car *current,*previous;
            current = head;
            previous = NULL;
            puts("here?");
            //compares new car model to next model, if  next is greater than new, move onto next pair
            while(strcmp(new->model,current->model) < 0){
            puts("here2");
            previous = current;
            current = current->next;
            puts("here2.5");
            }
            puts("here3");
            //if only one thing in the list
            if(previous->next == NULL){
                    //new car is next on list
                    if(strcmp(previous->model,new->model) > 0){
                            previous->next = new;
                    }
                    //new car goes into top of list
                    else{
                            head = new;
                            head->next = previous;
                    }
            }
            //doing stuff at middle or end
            //if new is greater than current
            else{
          puts("here4");
                    previous->next = new;
                    new->next = current;
            }
    }
    return head;
}
//this function creates a new "node" for the list, returns pointer
car* createCar(char* model, char* color, int year){

    car *newCar = malloc(sizeof(car));
    newCar->color = malloc(sizeof(char)*MAX_MODEL);
    newCar->model = malloc(sizeof(char)*MAX_MODEL);

    strcpy(newCar->model,model);
    strcpy(newCar->color,color);
    newCar->year = year;
    newCar->next = NULL;

    return newCar;
 }
//this function prints out all of things in linked list
void printCars(car* head){

    if(head == NULL)
            printf("List is empty\n");

    else{
            printf("The list of cars in inventory are:\n");
            while(head!=NULL){
            printf("%-5d %-25s %-13s",head->year,head->model,head->color);
            printf("\n");
            head = head->next;
            }
    }
}
</code>```

The purpose of this program is to read in a file that has a list of cars with their model name, color name, and year in it.  Once its read in, it will be put into a linked list in ascending order by the type of model of the car. Here is the file being read in:

```<code>Tesla S|royal|2015|
GMC Yukon|white|2005|
Dodge Charger|lime|2010|
Honda Civic|cobalt|1996|
Nissan Titan|saddlewood|2008|
Chevrolet Silverado|saddlewood|1999|
Ford Focus|lime|2000|
Toyota Tacoma|gunmetal|2009|
Tesla X|black|2016|
Nissan Maxima|white|2013|
Ford Explorer|forest|1996|
Chevrolet Corvette|cherry|1982|
Tesla 3|cherry|2017|
Nissan 370Z|royal|2011|
Ford F150|cherry|2006|
Honda Accord|white|2004|
Mitsubishi Eclipse|black|2002|
Toyota Tundra|cobalt|2017|
Dodge Challenger|lemon|1970|
Chevrolet Camaro|black|1966|
</code>```

After putting "./a.out cars.txt" in the command prompt, the output is

```<code>here?
here2
here2.5
Segmentation fault
</code>```

Because of my puts statements, I know the seg fault is happening somewhere within my while loop in the "insertInSortedOrder" function.  Any help with getting this function to work will be greatly appreciated, thanks

alright I have changed the insert function to:

```<code>car* insertInSortedOrder(car* head, char* model, char* color, int year){

    //if list is emppty
    if(head == NULL){
            head = createCar(model,color,year);
    }
    else{
            car *new = createCar(model,color,year);
            car *current,*previous;
            current = head;
            previous = NULL;
            //compares new car model to next model, if  next is greater than new, move onto next pair
            while( strcmp(new->model,current->model)  <  0){
                    //if current is only node in list or end of list
                    if(current->next == NULL){
                            current->next = new;
                            return head;
                    }
                    else{
                            //move forward to compare new
                            previous = current;
                            current = current->next;
                    }
            }
            //when new is greater than current, put new on top of it
            previous = new;
            previous->next = current;
    }
    return head;
}
</code>```

now it prints:

```<code>The list of cars in inventory are:
2015  Tesla S                   royal
2005  GMC Yukon                 white
2010  Dodge Charger             lime
1999  Chevrolet Silverado       saddlewood
1982  Chevrolet Corvette        cherry
1966  Chevrolet Camaro          black
</code>```

So yay! No more seg fault, but now I think I just have not good algorithm

答:
After analyzing your function insertInSortedOrder() and reading the warning of @JonathanLeffler, I have localized the problem of missing items in your sorted list.

Error in the case of 'new is greater than current'

Unconditional overwrite of the previous pointer

Using the code previous = new; without checking if previous is pointing to a node will directly overwrite a part of the list by the new item.

Not changing head when previous == NULL

When previous == NULL, the new item shall replace the head.

Use the following code:

```<code>if (previous==NULL) {
    // new becomes the first node
    new->next = head;
    head = new;
}
else {
    // new is inserted between previous and current
    new->next = previous->next;
    previous->next = new;
}
</code>```

Instead of the code:

```<code>previous = newitem;
previous->next = current;
</code>```

Body:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_MODEL 25
#define MAX_LINE 50
typedef struct car{
    char* model;
    char* color;
    int year;
    struct car* next;
}car;
car* readFromFile(FILE*);
car* insertInSortedOrder(car*, char*, char*, int);
car* createCar(char*, char*, int);
void printCars(car*);

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

    //creating a file pointer, opening file
    FILE* fptr;
    fptr = fopen(*(argv+1), "r");
    car* head = NULL;

    //this first reads cars from files, puts it into linked list and prints
    head = readFromFile(fptr);
    puts("do we get here");
    printCars(head);
    return 0;
}
///this function reads information from a text file, sends it to insertInSortedOrder function
car* readFromFile(FILE* fptr){

    char *M, *C, *year;
    char *readLine= malloc(sizeof(car)*MAX_MODEL);
    int yr;

    car *head=NULL;
    while(fgets(readLine,MAX_LINE,fptr)!= NULL){
            M = strtok(readLine,"|");
            C = strtok(NULL,"|");
            year = strtok(NULL,"|");
            yr = atoi(year);
            head = insertInSortedOrder(head,M,C,yr);
    }
    return head;
}
//this function sends new info to createCar to put it into a list, gets it and puts it
//into sorted order according to alphabetical order by model
car* insertInSortedOrder(car* head, char* model, char* color, int year){

    //if list is emppty
    if(head == NULL){
            head = createCar(model,color,year);
    }
    else{
            car *new = createCar(model,color,year);
            car *current,*previous;
            current = head;
            previous = NULL;
            puts("here?");
            //compares new car model to next model, if  next is greater than new, move onto next pair
            while(strcmp(new->model,current->model) < 0){
            puts("here2");
            previous = current;
            current = current->next;
            puts("here2.5");
            }
            puts("here3");
            //if only one thing in the list
            if(previous->next == NULL){
                    //new car is next on list
                    if(strcmp(previous->model,new->model) > 0){
                            previous->next = new;
                    }
                    //new car goes into top of list
                    else{
                            head = new;
                            head->next = previous;
                    }
            }
            //doing stuff at middle or end
            //if new is greater than current
            else{
          puts("here4");
                    previous->next = new;
                    new->next = current;
            }
    }
    return head;
}
//this function creates a new "node" for the list, returns pointer
car* createCar(char* model, char* color, int year){

    car *newCar = malloc(sizeof(car));
    newCar->color = malloc(sizeof(char)*MAX_MODEL);
    newCar->model = malloc(sizeof(char)*MAX_MODEL);

    strcpy(newCar->model,model);
    strcpy(newCar->color,color);
    newCar->year = year;
    newCar->next = NULL;

    return newCar;
 }
//this function prints out all of things in linked list
void printCars(car* head){

    if(head == NULL)
            printf("List is empty\n");

    else{
            printf("The list of cars in inventory are:\n");
            while(head!=NULL){
            printf("%-5d %-25s %-13s",head->year,head->model,head->color);
            printf("\n");
            head = head->next;
            }
    }
}

The purpose of this program is to read in a file that has a list of cars with their model name, color name, and year in it.  Once its read in, it will be put into a linked list in ascending order by the type of model of the car. Here is the file being read in:

Tesla S|royal|2015|
GMC Yukon|white|2005|
Dodge Charger|lime|2010|
Honda Civic|cobalt|1996|
Nissan Titan|saddlewood|2008|
Chevrolet Silverado|saddlewood|1999|
Ford Focus|lime|2000|
Toyota Tacoma|gunmetal|2009|
Tesla X|black|2016|
Nissan Maxima|white|2013|
Ford Explorer|forest|1996|
Chevrolet Corvette|cherry|1982|
Tesla 3|cherry|2017|
Nissan 370Z|royal|2011|
Ford F150|cherry|2006|
Honda Accord|white|2004|
Mitsubishi Eclipse|black|2002|
Toyota Tundra|cobalt|2017|
Dodge Challenger|lemon|1970|
Chevrolet Camaro|black|1966|

After putting "./a.out cars.txt" in the command prompt, the output is

here?
here2
here2.5
Segmentation fault

Because of my puts statements, I know the seg fault is happening somewhere within my while loop in the "insertInSortedOrder" function.  Any help with getting this function to work will be greatly appreciated, thanks

alright I have changed the insert function to:

car* insertInSortedOrder(car* head, char* model, char* color, int year){

    //if list is emppty
    if(head == NULL){
            head = createCar(model,color,year);
    }
    else{
            car *new = createCar(model,color,year);
            car *current,*previous;
            current = head;
            previous = NULL;
            //compares new car model to next model, if  next is greater than new, move onto next pair
            while( strcmp(new->model,current->model)  <  0){
                    //if current is only node in list or end of list
                    if(current->next == NULL){
                            current->next = new;
                            return head;
                    }
                    else{
                            //move forward to compare new
                            previous = current;
                            current = current->next;
                    }
            }
            //when new is greater than current, put new on top of it
            previous = new;
            previous->next = current;
    }
    return head;
}

now it prints:

The list of cars in inventory are:
2015  Tesla S                   royal
2005  GMC Yukon                 white
2010  Dodge Charger             lime
1999  Chevrolet Silverado       saddlewood
1982  Chevrolet Corvette        cherry
1966  Chevrolet Camaro          black

So yay! No more seg fault, but now I think I just have not good algorithm

Body:
After analyzing your function insertInSortedOrder() and reading the warning of @JonathanLeffler, I have localized the problem of missing items in your sorted list.

Error in the case of 'new is greater than current'

Unconditional overwrite of the previous pointer

Using the code previous = new; without checking if previous is pointing to a node will directly overwrite a part of the list by the new item.

Not changing head when previous == NULL

When previous == NULL, the new item shall replace the head.

Use the following code:

if (previous==NULL) {
    // new becomes the first node
    new->next = head;
    head = new;
}
else {
    // new is inserted between previous and current
    new->next = previous->next;
    previous->next = new;
}

Instead of the code:

previous = newitem;
previous->next = current;


问:
I'm not getting EditText Value in another class
MainActivity.java (First Class)

```<code>package com.example.we.reportcardjavaclass;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    public EditText one, two, three, four, five, six;
    public String bang1, bang2, bang3, bang4, bang5, bang6;
    public Button results;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Find the View that shows the numbers category

    }

    public void getResult(View view){
        results = (Button) findViewById(R.id.result);
        Intent numbersIntent = new Intent(MainActivity.this, result.class);
        startActivity(numbersIntent);
        one = (EditText) findViewById(R.id.name);
        bang1 = one.getText().toString();

        two = (EditText) findViewById(R.id.Class);
        bang2 = two.getText().toString();

        three = (EditText) findViewById(R.id.English);
        bang3 = three.getText().toString();

        four = (EditText) findViewById(R.id.Hindi);
        bang4 = four.getText().toString();

        five = (EditText) findViewById(R.id.Maths);
        bang5 = five.getText().toString();

        six = (EditText) findViewById(R.id.Science);
        bang6 = six.getText().toString();

    }

}
</code>```

activity_main.xml (First Layout File)

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

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.we.reportcardjavaclass.MainActivity"
    android:padding="16dp">

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Student's Name"
        android:id="@+id/name"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Class"
        android:id="@+id/Class"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="64dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Grade in English"
        android:id="@+id/English"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="128dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Grade in Hindi"
        android:id="@+id/Hindi"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="192dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Grade in Maths"
        android:id="@+id/Maths"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="256dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Grade in Science"
        android:id="@+id/Science"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="320dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <Button
        android:text="Get result"
        android:id="@+id/result"
        android:onClick="getResult"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="384dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"/>

</android.support.constraint.ConstraintLayout>
</ScrollView>

## result.xml (Second Layout File) ##

<?xml version="1.0" encoding="utf-8"?>

<ScrollView android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="32dp">

    <android.support.v7.widget.CardView
        android:id="@+id/resultCard"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardElevation="2dp"
        android:layout_gravity="center_vertical"
        card_view:cardUseCompatPadding="true">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingBottom="20dp"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            android:paddingTop="20dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                >

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="20dp"
                    android:text="Student's Name"
                    android:textAllCaps="true"
                    android:textSize="20sp"
                    android:textStyle="bold"/>

                <TextView
                    android:id="@+id/one"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="20dp"

                    android:textAllCaps="false"
                    android:textSize="15sp"
                    android:textStyle="normal"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="20dp"
                    android:text="Class"
                    android:textAllCaps="true"
                    android:textSize="20sp"
                    android:textStyle="bold"/>

                <TextView
                    android:id="@+id/two"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="40dp"
                    android:textAllCaps="false"
                    android:textSize="15sp"
                    android:textStyle="normal"/>

            </LinearLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="160dp"
                android:background="@color/cardview_dark_background"
                android:padding="20dp"
                >

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:text="English"
                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="bold"
                    />

                <TextView
                    android:id="@+id/three"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"

                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="normal"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_marginTop="40dp"
                    android:text="Hindi"
                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="bold"
                    />

                <TextView
                    android:id="@+id/four"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_marginTop="40dp"

                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="normal"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_marginTop="80dp"
                    android:text="Maths"
                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="bold"
                    />

                <TextView
                    android:id="@+id/five"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_marginTop="80dp"

                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="normal"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_marginTop="120dp"
                    android:text="Science"
                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="bold"
                    />
                <TextView
                    android:id="@+id/six"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_marginTop="120dp"

                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="normal"/>

            </RelativeLayout>
            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="350dp"
                android:text="BACK TO HOME"
                />
        </FrameLayout>
    </android.support.v7.widget.CardView>
</LinearLayout></ScrollView>
</code>```

Second Class

```<code>package com.example.we.reportcardjavaclass;

import android.os.Bundle;
import android.widget.TextView;

/**
 * Created by we on 08-07-2017.
 */

public class result extends MainActivity{

    public TextView one, two, three, four, five, six;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result);
        setTitle(bang1+"s Result");
        one = (TextView) findViewById(R.id.one);
        one.setText(bang1);
        two = (TextView) findViewById(R.id.two);
        two.setText(bang2);
        three = (TextView) findViewById(R.id.three);
        three.setText(bang3);
        four = (TextView) findViewById(R.id.four);
        four.setText(bang4);
        five = (TextView) findViewById(R.id.five);
        five.setText(bang5);
        six = (TextView) findViewById(R.id.six);
        six.setText(bang6);
    }
}
</code>```

EditText values are getting stored MainActivity.java in variables bang - 123456. I added public modifier while declaring them so I can access these in second class too. In second class I want to use these variable values to set in into Textviews but while running it is not showing the value.

I have also attached the screenshots of both layouts after running in my emulator.

Screenshot 1

Screenshot 2

In second layout it is supposed to show name and other values.

答:
If you want to use these values in another activity then simply pass these values along with the intent that is used to start a new activity.

MainActivity.java

```<code>Intent i = new Intent(MainActivity.this,SecondActivity.class);
i.putExtra("Bang1",bang1);
i.putExtra("Bang2",bang2);
i.putExtra("Bang3",bang3);
...
</code>```

And you can get them in the SecondActivity.java file as:

```<code>Intent i =getIntent();
int bang1 = i.getIntExtra("Bang1");
...
</code>```

But instead so choosing the string names as shown i would suggest to create a new class to store the the string names as final string constants in order to avoid any kind of mistake.

Or you can directly declare these variables as static and access them in the SecondActivity by referring to their names as :

```<code> int bang1 = MainActivity.bang1;
</code>```

Body:
MainActivity.java (First Class)

package com.example.we.reportcardjavaclass;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    public EditText one, two, three, four, five, six;
    public String bang1, bang2, bang3, bang4, bang5, bang6;
    public Button results;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Find the View that shows the numbers category

    }

    public void getResult(View view){
        results = (Button) findViewById(R.id.result);
        Intent numbersIntent = new Intent(MainActivity.this, result.class);
        startActivity(numbersIntent);
        one = (EditText) findViewById(R.id.name);
        bang1 = one.getText().toString();

        two = (EditText) findViewById(R.id.Class);
        bang2 = two.getText().toString();

        three = (EditText) findViewById(R.id.English);
        bang3 = three.getText().toString();

        four = (EditText) findViewById(R.id.Hindi);
        bang4 = four.getText().toString();

        five = (EditText) findViewById(R.id.Maths);
        bang5 = five.getText().toString();

        six = (EditText) findViewById(R.id.Science);
        bang6 = six.getText().toString();

    }

}

activity_main.xml (First Layout File)

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

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.we.reportcardjavaclass.MainActivity"
    android:padding="16dp">

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Student's Name"
        android:id="@+id/name"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Class"
        android:id="@+id/Class"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="64dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Grade in English"
        android:id="@+id/English"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="128dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Grade in Hindi"
        android:id="@+id/Hindi"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="192dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Grade in Maths"
        android:id="@+id/Maths"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="256dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Grade in Science"
        android:id="@+id/Science"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="320dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <Button
        android:text="Get result"
        android:id="@+id/result"
        android:onClick="getResult"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="384dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"/>

</android.support.constraint.ConstraintLayout>
</ScrollView>

## result.xml (Second Layout File) ##

<?xml version="1.0" encoding="utf-8"?>

<ScrollView android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="32dp">

    <android.support.v7.widget.CardView
        android:id="@+id/resultCard"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardElevation="2dp"
        android:layout_gravity="center_vertical"
        card_view:cardUseCompatPadding="true">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingBottom="20dp"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            android:paddingTop="20dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                >

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="20dp"
                    android:text="Student's Name"
                    android:textAllCaps="true"
                    android:textSize="20sp"
                    android:textStyle="bold"/>

                <TextView
                    android:id="@+id/one"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="20dp"

                    android:textAllCaps="false"
                    android:textSize="15sp"
                    android:textStyle="normal"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="20dp"
                    android:text="Class"
                    android:textAllCaps="true"
                    android:textSize="20sp"
                    android:textStyle="bold"/>

                <TextView
                    android:id="@+id/two"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="40dp"
                    android:textAllCaps="false"
                    android:textSize="15sp"
                    android:textStyle="normal"/>

            </LinearLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="160dp"
                android:background="@color/cardview_dark_background"
                android:padding="20dp"
                >

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:text="English"
                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="bold"
                    />

                <TextView
                    android:id="@+id/three"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"

                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="normal"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_marginTop="40dp"
                    android:text="Hindi"
                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="bold"
                    />

                <TextView
                    android:id="@+id/four"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_marginTop="40dp"

                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="normal"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_marginTop="80dp"
                    android:text="Maths"
                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="bold"
                    />

                <TextView
                    android:id="@+id/five"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_marginTop="80dp"

                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="normal"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_marginTop="120dp"
                    android:text="Science"
                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="bold"
                    />
                <TextView
                    android:id="@+id/six"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_marginTop="120dp"

                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="normal"/>

            </RelativeLayout>
            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="350dp"
                android:text="BACK TO HOME"
                />
        </FrameLayout>
    </android.support.v7.widget.CardView>
</LinearLayout></ScrollView>

Second Class

package com.example.we.reportcardjavaclass;

import android.os.Bundle;
import android.widget.TextView;

/**
 * Created by we on 08-07-2017.
 */

public class result extends MainActivity{

    public TextView one, two, three, four, five, six;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result);
        setTitle(bang1+"s Result");
        one = (TextView) findViewById(R.id.one);
        one.setText(bang1);
        two = (TextView) findViewById(R.id.two);
        two.setText(bang2);
        three = (TextView) findViewById(R.id.three);
        three.setText(bang3);
        four = (TextView) findViewById(R.id.four);
        four.setText(bang4);
        five = (TextView) findViewById(R.id.five);
        five.setText(bang5);
        six = (TextView) findViewById(R.id.six);
        six.setText(bang6);
    }
}

EditText values are getting stored MainActivity.java in variables bang - 123456. I added public modifier while declaring them so I can access these in second class too. In second class I want to use these variable values to set in into Textviews but while running it is not showing the value.

I have also attached the screenshots of both layouts after running in my emulator.

Screenshot 1

Screenshot 2

In second layout it is supposed to show name and other values.

Body:
If you want to use these values in another activity then simply pass these values along with the intent that is used to start a new activity.

MainActivity.java

Intent i = new Intent(MainActivity.this,SecondActivity.class);
i.putExtra("Bang1",bang1);
i.putExtra("Bang2",bang2);
i.putExtra("Bang3",bang3);
...

And you can get them in the SecondActivity.java file as:

Intent i =getIntent();
int bang1 = i.getIntExtra("Bang1");
...

But instead so choosing the string names as shown i would suggest to create a new class to store the the string names as final string constants in order to avoid any kind of mistake.

Or you can directly declare these variables as static and access them in the SecondActivity by referring to their names as :

 int bang1 = MainActivity.bang1;


问:
where to call main function (dev c++)
I'm very new to c++. I have a standard dev c++ windows application winapi, but it doesnt get formatted well here on stackoverflow.
So here you can see it:
 see here

but my question is, where am i supposed to do the main function? if i just create a new int main(), the window doesn't come up at all.
am i supposed to do it in the WinMain() function?

any suggestions?

EDIT: I just found out dev c++ doesnt have a compiler.

答:
Notice that Dev-C++ is not a compiler, but an IDE (that is, a glorified source code editor). Your compiler is probably some variant of GCC (a free software compiler) like MINGW.

In standard C99 (or C11) or C++11, the entry point of your (command line) program is main.

You need to define such a function, and the runtime system (e.g. crt0 on Unix) will call it.

You should not call that main function. Its prefered signature should be

```<code>int main(int argc, char**argv);
</code>```

You probably should run your program in some terminal emulator. Here are some properties of argc and argv (imposed by the C or C++ standards).

Any other entry point (e.g. WinMain) could be Windows specific and might require some specific compiler options.

You would compile a C program using gcc, and a C++ program using g++. I strongly recommend enabling all warnings & debug info by using -Wall -Wextra -g flags to that gcc or g++ compiler. You may want to use some build automation tool like GNU make.

For GUI programs in C++, I would recommend Qt (it is free software, and multi-platform).

Title: where to call main function (dev c++)

Body:
Notice that Dev-C++ is not a compiler, but an IDE (that is, a glorified source code editor). Your compiler is probably some variant of GCC (a free software compiler) like MINGW.

In standard C99 (or C11) or C++11, the entry point of your (command line) program is main.

You need to define such a function, and the runtime system (e.g. crt0 on Unix) will call it.

You should not call that main function. Its prefered signature should be

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

You probably should run your program in some terminal emulator. Here are some properties of argc and argv (imposed by the C or C++ standards).

Any other entry point (e.g. WinMain) could be Windows specific and might require some specific compiler options.

You would compile a C program using gcc, and a C++ program using g++. I strongly recommend enabling all warnings & debug info by using -Wall -Wextra -g flags to that gcc or g++ compiler. You may want to use some build automation tool like GNU make.

For GUI programs in C++, I would recommend Qt (it is free software, and multi-platform).