问:
Always showing video controls
Is there a way to Always show the video controls in the HTML5 video tag instead of just showing them on MouseOver?

Video code:

```<code><table cellpadding="0" cellspacing="0">
  <tr>
    <td runat="server" width="680px" height="383px" id="vContainer">
      <div style="z-index: 1;" runat="server" id="cont">
        <div runat="server" style="background: rgba(200, 200, 200, 0.6) url('/images/Play.png') no-repeat center center;" id="img">
        </div>
        <video id="player" style="z-index: 1; border: 1px solid #000000;" width="100%" height="100% "
          title="" controls runat="server">
          <source runat="server" id="ffVideo" type="video/ogg" />
          <source runat="server" id="mp4Video" type="video/mp4" />
        </video>
        <embed id="playerOld" width="680px" height="383px" autostart="false" allowfullscreen="true"
          title="" style="display: none" type="application/mp4" runat="server" />
      </div>
    </td>
  </tr>
</table
</code>```

>

答:
Update November 2017: Please note due to new changes in Safari 11, this is no longer working in that browser. I will update the post if I find a way.

Even though hiding controls is part of the HTML5 video spec. There are two ways to accomplish this one via javascript and the other via CSS.

In Javascript, you can add an event handler for the timeupdate event which changes every time the play position has changed, in other words, the event is always occurring while the video is playing.

Assuming the id for the video element is called 'player', javascript code would look like this:

JS:

```<code>//assign video element to variable vid
var vid = document.getElementById("player");

function videoTimeUpdate(e)
{
    //set controls settings to controls,this make controls show everytime this event is triggered
    vid.setAttribute("controls","controls");
}

//add event listener to video for timeupdate event
vid.addEventListener('timeupdate', videoTimeUpdate, false);
</code>```

Working sample of the above is here: https://jsfiddle.net/l33tstealth/t082bjnf/6/

The second way to do this is through CSS but this will only work for WebKit based browsers, thus limited. You can force the controls bar to always show.

The CSS for that would look like this:

CSS:

```<code>video::-webkit-media-controls-panel {
    display: flex !important;
    opacity: 1 !important;
}
</code>```

Working sample (only works in web kit based browsers):
https://jsfiddle.net/l33tstealth/t082bjnf/7/

Title: Always showing video controls

Body:
Is there a way to Always show the video controls in the HTML5 video tag instead of just showing them on MouseOver?

Video code:

        <video id="player" style="z-index: 1; border: 1px solid #000000;" width="100%" height="100% "
          title="" controls runat="server">
          <source runat="server" id="ffVideo" type="video/ogg" />
          <source runat="server" id="mp4Video" type="video/mp4" />
        </video>
        <embed id="playerOld" width="680px" height="383px" autostart="false" allowfullscreen="true"
          title="" style="display: none" type="application/mp4" runat="server" />

</table

>

Body:
Update November 2017: Please note due to new changes in Safari 11, this is no longer working in that browser. I will update the post if I find a way.

Even though hiding controls is part of the HTML5 video spec. There are two ways to accomplish this one via javascript and the other via CSS.

In Javascript, you can add an event handler for the timeupdate event which changes every time the play position has changed, in other words, the event is always occurring while the video is playing.

Assuming the id for the video element is called 'player', javascript code would look like this:

JS:

//assign video element to variable vid
var vid = document.getElementById("player");

function videoTimeUpdate(e)
{
    //set controls settings to controls,this make controls show everytime this event is triggered
    vid.setAttribute("controls","controls");
}

//add event listener to video for timeupdate event
vid.addEventListener('timeupdate', videoTimeUpdate, false);

Working sample of the above is here: https://jsfiddle.net/l33tstealth/t082bjnf/6/

The second way to do this is through CSS but this will only work for WebKit based browsers, thus limited. You can force the controls bar to always show.

The CSS for that would look like this:

CSS:

video::-webkit-media-controls-panel {
    display: flex !important;
    opacity: 1 !important;
}

Working sample (only works in web kit based browsers):
https://jsfiddle.net/l33tstealth/t082bjnf/7/


来源: stackexchange

问:
Page with multiple chart.js charts to pdf
I have used chart.js to generate a report page that has multiple charts. I need to export this report to PDF. There are many solutions available via search, but I cannot find one which has multiple canvas elements.

The only available solution seems to be to loop through all the images, and recreate the report using the images, and then download that as a pdf.

Is there any simpler/more efficient way to accomplish this?

```<code><body>
<h1> Chart 1 </h1>
<div style="width:800px; height:400px;">
<canvas id="chart_1" width="50" height="50"></canvas>
</div>

<h1> Chart 2 </h1>
<div style="width:800px; height:400px;">
<canvas id="chart_2" width="50" height="50"></canvas>
</div>

<h1> Chart 3 </h1>
<div style="width:800px; height:400px;">
<canvas id="chart_3" width="50" height="50"></canvas>
</div>
</body>
</code>```

答:
Honestly, it seems like the easiest approach would be to just provide a "download to PDF" link that pops up the browser's print page and instruct to user to select "print as pdf".

If that approach doesn't work for you (or your users), then here is a rough way to do it.

Basically, we create a new canvas element that is the size of your report page and incrementally paint the pixels from your existing chart.js canvas charts into the new canvas.  Once that is done, then you can use jsPDF to add the new canvas to a pdf document as an image and download the file.

Here is an example implementation that does just that.

```<code>$('#downloadPdf').click(function(event) {
  // get size of report page
  var reportPageHeight = $('#reportPage').innerHeight();
  var reportPageWidth = $('#reportPage').innerWidth();

  // create a new canvas object that we will populate with all other canvas objects
  var pdfCanvas = $('<canvas />').attr({
    id: "canvaspdf",
    width: reportPageWidth,
    height: reportPageHeight
  });

  // keep track canvas position
  var pdfctx = $(pdfCanvas)[0].getContext('2d');
  var pdfctxX = 0;
  var pdfctxY = 0;
  var buffer = 100;

  // for each chart.js chart
  $("canvas").each(function(index) {
    // get the chart height/width
    var canvasHeight = $(this).innerHeight();
    var canvasWidth = $(this).innerWidth();

    // draw the chart into the new canvas
    pdfctx.drawImage($(this)[0], pdfctxX, pdfctxY, canvasWidth, canvasHeight);
    pdfctxX += canvasWidth + buffer;

    // our report page is in a grid pattern so replicate that in the new canvas
    if (index % 2 === 1) {
      pdfctxX = 0;
      pdfctxY += canvasHeight + buffer;
    }
  });

  // create new pdf and add our new canvas as an image
  var pdf = new jsPDF('l', 'pt', [reportPageWidth, reportPageHeight]);
  pdf.addImage($(pdfCanvas)[0], 'PNG', 0, 0);

  // download the pdf
  pdf.save('filename.pdf');
});
</code>```

You can see it in action at this codepen.

Now let's talk about some gotchas with this approach.  First, you have to control the position of each chart.js canvas in the new canvas object.  The only way to do that is to have an understanding of how your report page is structured and implement that same structure.  In my example, my charts are in a 2x2 grid and the logic handles this accordingly.  If you had a 3x2 grid or something different then you would have to change the positioning logic.

Lastly, the final pdf output file dimensions are much larger than the original chart page (from the web).  I think the reason is because my chart "container" div stretches across the full page.  Therefore, you probably want to use a different approach for setting the size of your new canvas.

So long story short, the above example is meant to demonstrate an approach and not be your final solution.

Good luck!

ContentLicense: CC BY-SA 3.0

Body:
I have used chart.js to generate a report page that has multiple charts. I need to export this report to PDF. There are many solutions available via search, but I cannot find one which has multiple canvas elements.

The only available solution seems to be to loop through all the images, and recreate the report using the images, and then download that as a pdf.

Is there any simpler/more efficient way to accomplish this?

 Chart 1

<canvas id="chart_1" width="50" height="50"></canvas>

 Chart 2

<canvas id="chart_2" width="50" height="50"></canvas>

 Chart 3

<canvas id="chart_3" width="50" height="50"></canvas>

Body:
Honestly, it seems like the easiest approach would be to just provide a "download to PDF" link that pops up the browser's print page and instruct to user to select "print as pdf".

If that approach doesn't work for you (or your users), then here is a rough way to do it.

Basically, we create a new canvas element that is the size of your report page and incrementally paint the pixels from your existing chart.js canvas charts into the new canvas.  Once that is done, then you can use jsPDF to add the new canvas to a pdf document as an image and download the file.

Here is an example implementation that does just that.

$('#downloadPdf').click(function(event) {
  // get size of report page
  var reportPageHeight = $('#reportPage').innerHeight();
  var reportPageWidth = $('#reportPage').innerWidth();

  // create a new canvas object that we will populate with all other canvas objects
  var pdfCanvas = $('<canvas />').attr({
    id: "canvaspdf",
    width: reportPageWidth,
    height: reportPageHeight
  });

  // keep track canvas position
  var pdfctx = $(pdfCanvas)[0].getContext('2d');
  var pdfctxX = 0;
  var pdfctxY = 0;
  var buffer = 100;

  // for each chart.js chart
  $("canvas").each(function(index) {
    // get the chart height/width
    var canvasHeight = $(this).innerHeight();
    var canvasWidth = $(this).innerWidth();

    // draw the chart into the new canvas
    pdfctx.drawImage($(this)[0], pdfctxX, pdfctxY, canvasWidth, canvasHeight);
    pdfctxX += canvasWidth + buffer;

    // our report page is in a grid pattern so replicate that in the new canvas
    if (index % 2 === 1) {
      pdfctxX = 0;
      pdfctxY += canvasHeight + buffer;
    }
  });

  // create new pdf and add our new canvas as an image
  var pdf = new jsPDF('l', 'pt', [reportPageWidth, reportPageHeight]);
  pdf.addImage($(pdfCanvas)[0], 'PNG', 0, 0);

  // download the pdf
  pdf.save('filename.pdf');
});

You can see it in action at this codepen.

Now let's talk about some gotchas with this approach.  First, you have to control the position of each chart.js canvas in the new canvas object.  The only way to do that is to have an understanding of how your report page is structured and implement that same structure.  In my example, my charts are in a 2x2 grid and the logic handles this accordingly.  If you had a 3x2 grid or something different then you would have to change the positioning logic.

Lastly, the final pdf output file dimensions are much larger than the original chart page (from the web).  I think the reason is because my chart "container" div stretches across the full page.  Therefore, you probably want to use a different approach for setting the size of your new canvas.

So long story short, the above example is meant to demonstrate an approach and not be your final solution.

Good luck!


问:
How to show datetime in Django in specific timezone?
I have a Django (v1.10.6) project that has some models with datetime fields, for example:

```<code>created_at = models.DateTimeField(auto_now_add=True)
</code>```

that are stored in PostgreSQL database without timezone information:

```<code>created_at timestamp without time zone NOT NULL
</code>```

postgresql.conf:

```<code>timezone = 'UTC'
</code>```

I want all the dates of my application to be shown in America/Bogota time zone (it shouldn't depend on user's actual time zone), so my settings.py file has the following configuration:

```<code>TIME_ZONE = 'America/Bogota'
USE_I18N = False
USE_L10N = True
USE_TZ = True

SHORT_DATETIME_FORMAT = 'd-m-Y H:i:s'
SHORT_DATE_FORMAT = 'd-m-Y'
TIME_FORMAT = 'H:i:s'
</code>```

but when I write

```<code>{{ object.created_at|date:'SHORT_DATETIME_FORMAT' }}
</code>```

in templates, it still shows the date in UTC format.

Update:

I added the following middleware, but it didn't help:

```<code>class TimezoneMiddleware(MiddlewareMixin):
    def process_request(self, request):
        timezone.activate(pytz.timezone(settings.TIME_ZONE))
</code>```

Update 2:

It works the following way:

```<code>import pytz
from django.utils import timezone

timezone.is_naive(object.created_at)  # True
object.created_at.replace(tzinfo=timezone.utc)
</code>```

(forcing the date to be in UTC timezone and then passing it to template without localize filter) but I don't understand why Django still returns naive datetime when USE_TZ is set to True.

答:
Try django-datetime-widget and use configurations:

If you want to use localization:

Set USE_L10N = True, USE_TZ = True and USE_I18N = True in settings.py

Add 'django.middleware.locale.LocaleMiddleware' to MIDDLEWARE_CLASSES in settings.py

When you create the widget add usel10n = True like attribute : DateTimeWidget(usel10n=True)

Link is here:

https://github.com/asaglimbeni/django-datetime-widget

Body:
I have a Django (v1.10.6) project that has some models with datetime fields, for example:

created_at = models.DateTimeField(auto_now_add=True)

that are stored in PostgreSQL database without timezone information:

created_at timestamp without time zone NOT NULL

postgresql.conf:

timezone = 'UTC'

I want all the dates of my application to be shown in America/Bogota time zone (it shouldn't depend on user's actual time zone), so my settings.py file has the following configuration:

TIME_ZONE = 'America/Bogota'
USE_I18N = False
USE_L10N = True
USE_TZ = True

SHORT_DATETIME_FORMAT = 'd-m-Y H:i:s'
SHORT_DATE_FORMAT = 'd-m-Y'
TIME_FORMAT = 'H:i:s'

but when I write

{{ object.created_at|date:'SHORT_DATETIME_FORMAT' }}

in templates, it still shows the date in UTC format.

Update:

I added the following middleware, but it didn't help:

class TimezoneMiddleware(MiddlewareMixin):
    def process_request(self, request):
        timezone.activate(pytz.timezone(settings.TIME_ZONE))

Update 2:

It works the following way:

import pytz
from django.utils import timezone

timezone.is_naive(object.created_at)  # True
object.created_at.replace(tzinfo=timezone.utc)

(forcing the date to be in UTC timezone and then passing it to template without localize filter) but I don't understand why Django still returns naive datetime when USE_TZ is set to True.


问:
Find max value from input text file in java
Im trying to get the max number in a certain text file the user inputs. I also put it into separate methods. Heres what I have so far:

```<code>public static void FindMax(String file)throws IOException{
 int maximum = 0;
 Scanner fileScanner = new Scanner(new File(file)); {
            int big = fileScanner.nextInt();
            while (fileScanner.hasNextInt()) {
                int num = fileScanner.nextInt();
                if(num > big) {
                   maximum++;
                     System.out.println(num);;
                }
           }
  }
}
public static void main(String[] args)throws IOException{

    Scanner keyboard = new Scanner(System.in);
     String file;

      System.out.print("Enter file: ");
       file = keyboard.nextLine();

       FindMax(file);

}
</code>```

The output is printing all the content in the text file except the first value, instead of printing the maximum. For example if the text file is:

```<code>1
2
3
4
5
</code>```

It only prints 2,3,4, and 5 and I don't know why.How can I get the max value? Id appreciate any help/advice. Thanks in advance.

EDIT: All of you guys are saying similar solutions but when I try them, it just prints the same output. Im very confused.

答:
Whenever you get the any num bigger than the big then you should update the big with the `num'. like this -

```<code>while (fileScanner.hasNextInt()) {
   int num = fileScanner.nextInt();
   if(num > big) {
      big = num;
   }
}
</code>```

Then after finishing the loop you will get your max number. Just print the big -

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

Body:
Im trying to get the max number in a certain text file the user inputs. I also put it into separate methods. Heres what I have so far:

public static void FindMax(String file)throws IOException{
 int maximum = 0;
 Scanner fileScanner = new Scanner(new File(file)); {
            int big = fileScanner.nextInt();
            while (fileScanner.hasNextInt()) {
                int num = fileScanner.nextInt();
                if(num > big) {
                   maximum++;
                     System.out.println(num);;
                }
           }
  }
}
public static void main(String[] args)throws IOException{

    Scanner keyboard = new Scanner(System.in);
     String file;

      System.out.print("Enter file: ");
       file = keyboard.nextLine();

       FindMax(file);

}

The output is printing all the content in the text file except the first value, instead of printing the maximum. For example if the text file is:

1
2
3
4
5

It only prints 2,3,4, and 5 and I don't know why.How can I get the max value? Id appreciate any help/advice. Thanks in advance.

EDIT: All of you guys are saying similar solutions but when I try them, it just prints the same output. Im very confused.

Body:
Whenever you get the any num bigger than the big then you should update the big with the `num'. like this -

while (fileScanner.hasNextInt()) {
   int num = fileScanner.nextInt();
   if(num > big) {
      big = num;
   }
}

Then after finishing the loop you will get your max number. Just print the big -

System.out.println(big);


问:
Why the difference in speed between these SQL queries?
I'm currently trying to write a query to sift through our ERP DB and I noticed a very odd drop in speed when I removed a filter condition.

This is what the Query looked like before (it took less than a second to complete, typically returned anywhere from 10 to hundreds of records depending on the order and item)

```<code>SELECT TOP 1000 jobmat.job, jobmat.suffix, jobmat.item, jobmat.matl_qty,
      jobmat.ref_type, jobmat.ref_num, spec.NoteContent, spec.NoteDesc,
      job.ord_num, jobmat.RowPointer
FROM jobmat
INNER JOIN ObjectNotes AS obj ON obj.RefRowPointer = jobmat.RowPointer
INNER JOIN SpecificNotes AS spec ON obj.SpecificNoteToken = spec.SpecificNoteToken
INNER JOIN job ON job.job = jobmat.job AND job.suffix = jobmat.suffix
WHERE ord_num LIKE '%3766%' AND ref_type = 'P' AND
(spec.NoteDesc LIKE '%description%' OR spec.NoteContent LIKE '%COMPANY%DWG%1162402%')
</code>```

And this is what I changed the WHERE Statement too:

```<code>WHERE ord_num LIKE '%3766%' AND ref_type = 'P' AND
spec.NoteContent LIKE '%COMPANY%DWG%1162402%'
</code>```

Running it after having made this modifcation bumped my runtime up to like 9 seconds (returns normally 1-3 records). Is there an obvious reason that I'm missing? I would have thought that the same should have been roughly the same. Any help is greatly appreciated!

Edit: I have run both versions of this query many times to test, and the runtimes are fairly consistant; <1 second for version 1, ~9 seconds for version 2.

答:
Your original query has to find 1000 matching rows before it returns the result set.  It is doing this by creating a result set based on the JOINs and then filtering based on the WHERE clause.

The condition:

```<code>(spec.NoteDesc LIKE '%description%' OR spec.NoteContent LIKE '%COMPANY%DWG%1162402%')
</code>```

matches more rows than:

```<code>(spec.NoteContent LIKE '%COMPANY%DWG%1162402%')
</code>```

Hence, the second version has to go through and process more rows to get 1,000 matches.

That is why the second version is slower.

If you want the second version to seem faster, you can add an ORDER BY clause.  This requires reading all the data in both cases.  Because the ORDER BY then takes additional time related to the number of matching rows, you'll probably see that the second is slightly faster than the first.  One caveat:  both will then take at least 9 seconds.

EDIT:

I like the above explanation, but if all the rows are processed in both cases, then it might not be correct.  Here is another explanation, but it is more speculative.

It depends on NoteContent being very long, so the LIKE has a noticeable effect on query performance.  The second version might be "optimized" by pushing the filtering clauses to the node in the processing that reads the data.  This is something that SQL Server regularly does.  That means that the LIKE is being processed on all the data in the second case.

Because of the OR condition, the first example cannot push the filtering down to that level.  Then, the condition on NoteDescription is short-circuited in multiple ways:

The join conditions.

The other WHERE conditions.

The first LIKE condition.

Because of all this filtering, the second condition is run on many fewer rows, and the code runs faster.  Usually filtering before joining is a good idea, but there are definitely exceptions to this rule.

Body:
I'm currently trying to write a query to sift through our ERP DB and I noticed a very odd drop in speed when I removed a filter condition.

This is what the Query looked like before (it took less than a second to complete, typically returned anywhere from 10 to hundreds of records depending on the order and item)

SELECT TOP 1000 jobmat.job, jobmat.suffix, jobmat.item, jobmat.matl_qty,
      jobmat.ref_type, jobmat.ref_num, spec.NoteContent, spec.NoteDesc,
      job.ord_num, jobmat.RowPointer
FROM jobmat
INNER JOIN ObjectNotes AS obj ON obj.RefRowPointer = jobmat.RowPointer
INNER JOIN SpecificNotes AS spec ON obj.SpecificNoteToken = spec.SpecificNoteToken
INNER JOIN job ON job.job = jobmat.job AND job.suffix = jobmat.suffix
WHERE ord_num LIKE '%3766%' AND ref_type = 'P' AND
(spec.NoteDesc LIKE '%description%' OR spec.NoteContent LIKE '%COMPANY%DWG%1162402%')

And this is what I changed the WHERE Statement too:

WHERE ord_num LIKE '%3766%' AND ref_type = 'P' AND
spec.NoteContent LIKE '%COMPANY%DWG%1162402%'

Running it after having made this modifcation bumped my runtime up to like 9 seconds (returns normally 1-3 records). Is there an obvious reason that I'm missing? I would have thought that the same should have been roughly the same. Any help is greatly appreciated!

Edit: I have run both versions of this query many times to test, and the runtimes are fairly consistant; <1 second for version 1, ~9 seconds for version 2.

Body:
Your original query has to find 1000 matching rows before it returns the result set.  It is doing this by creating a result set based on the JOINs and then filtering based on the WHERE clause.

The condition:

(spec.NoteDesc LIKE '%description%' OR spec.NoteContent LIKE '%COMPANY%DWG%1162402%')

matches more rows than:

(spec.NoteContent LIKE '%COMPANY%DWG%1162402%')

Hence, the second version has to go through and process more rows to get 1,000 matches.

That is why the second version is slower.

If you want the second version to seem faster, you can add an ORDER BY clause.  This requires reading all the data in both cases.  Because the ORDER BY then takes additional time related to the number of matching rows, you'll probably see that the second is slightly faster than the first.  One caveat:  both will then take at least 9 seconds.

EDIT:

I like the above explanation, but if all the rows are processed in both cases, then it might not be correct.  Here is another explanation, but it is more speculative.

It depends on NoteContent being very long, so the LIKE has a noticeable effect on query performance.  The second version might be "optimized" by pushing the filtering clauses to the node in the processing that reads the data.  This is something that SQL Server regularly does.  That means that the LIKE is being processed on all the data in the second case.

Because of the OR condition, the first example cannot push the filtering down to that level.  Then, the condition on NoteDescription is short-circuited in multiple ways:

The join conditions.

The other WHERE conditions.

The first LIKE condition.

Because of all this filtering, the second condition is run on many fewer rows, and the code runs faster.  Usually filtering before joining is a good idea, but there are definitely exceptions to this rule.


问:
Connection to DB via PHP not working
Im sure this is very trivial, but I just can´t figure it out. I used part of my code that works on another server but not on my new web.
In separate file I got this:

```<code><?php
define('MYSQL_HOST','c236um.forpsi.com');
define('MYSQL_USER','abcd');
define('MYSQL_PASSWORD','xyz');
define('MYSQL_DB','abcd');

$db = mysqli_connect (MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die("failed to connect");
mysqli_select_db(MYSQL_DB, $db) or die(mysqli_error($db));
mysqli_query("SET NAMES UTF8");
?>
</code>```

and in index.php I simply include that file in body:

```<code>include "protected/_mysql.php";
</code>```

With this the contents of the body isn´t displaying, there is just blank white page. If I put some text as error notification instead of variable in

```<code>mysqli_select_db(MYSQL_DB, $db) or die(mysqli_error($db));
</code>```

it will display that error text.
I tried to put localhost as MYSQL_HOST, but that displays the first "failed to connect" error.
What am I doing wrong?

答:
First of all I would look into PHP -> PDO

That's a very nice library shipped with PHP that can talk to mysql servers (and others) and abstracts the engine a bit.

It's a lot more relaxing to work through PDO than through mysqli imho.

The next suggestions would be error_reporting(), if you see a white page you likely have an error in your PHP code (in this case inside that PHP include, or a missing file).

You can enable error reporting and you can take a look in the apache log files to see if your error was logged.

http://php.net/manual/de/book.pdo.php

http://php.net/manual/de/function.error-reporting.php

Title: Connection to DB via PHP not working

Body:
Im sure this is very trivial, but I just can´t figure it out. I used part of my code that works on another server but not on my new web.
In separate file I got this:

<?php
define('MYSQL_HOST','c236um.forpsi.com');
define('MYSQL_USER','abcd');
define('MYSQL_PASSWORD','xyz');
define('MYSQL_DB','abcd');

$db = mysqli_connect (MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die("failed to connect");
mysqli_select_db(MYSQL_DB, $db) or die(mysqli_error($db));
mysqli_query("SET NAMES UTF8");
?>

and in index.php I simply include that file in body:

include "protected/_mysql.php";

With this the contents of the body isn´t displaying, there is just blank white page. If I put some text as error notification instead of variable in

mysqli_select_db(MYSQL_DB, $db) or die(mysqli_error($db));

it will display that error text.
I tried to put localhost as MYSQL_HOST, but that displays the first "failed to connect" error.
What am I doing wrong?


答:
While there are many errors in your code. I think the problem that you asked for is why it is printing multiple numbers.

Just put the System.out.println(num); this line outside of while loop. And fix the other errors to make it work.

Title: Find max value from input text file in java


问:
Moving cells to last row without erasing over existing
The following code checks to see if any of my rows on the main page contain a date from a year ago or older. If it does, it copies it to the "Archive" worksheet and deletes it from the main page. However, what it's doing now is just copying from the main page and overriding what already exists on the archive page instead of adding to the last row. I've tried subbing in LastRow from a function, but I was getting an error with how I was using it. Anyone have a better solution?</p>

```<code>Sub TestDateTransfer()
With Application
PrevCalc = .Calculation
.Calculation = xlCalculationManual
.Cursor = xlWait
.Calculate
.EnableEvents = False
.ScreenUpdating = False
End With
Application.DisplayAlerts = False
Worksheets("Archive").Activate
Range("A3:I1000").Select
Selection.ClearContents
Worksheets("Main Page").Activate
Dim MyDate As Date
MyDate = "03/27/2017"
Set i = Sheets("Main Page")
Set E = Sheets("Archive")
Dim d
Dim j
d = 2
j = 2

Do Until IsEmpty(i.Range("C" & j))

  If i.Range("C" & j) <= MyDate - 365 Then
  d = d + 1
  E.rows(d).Value = i.rows(j).Value

  End If
  j = j + 1
 Loop
 Worksheets("Archive").Activate
 ActiveSheet.Range("H1").Select 'To unselect the page
 Worksheets("Main Page").Activate
 MyDate = "03/27/2017"
 Dim y
 Dim z
 y = 2
 z = 2
 Do Until IsEmpty(i.Range("C" & z))

  If i.Range("C" & z) <= MyDate - 365 Then
  y = y + 1
  i.rows(z).Delete

  End If
  z = z + 1
  Loop
 With Application
.Cursor = xlDefault
.Calculate
.Calculation = PrevCalc
'.ScreenUpdating = True 'Not Needed...
.EnableEvents = True
 End With
 ActiveSheet.Range("H1").Select
 End Sub
</code>```

答:
```<code> Worksheets("Archive").Cells(Sheet1.Rows.Count, 1).End(xlUp).Offset(1, 0).Value = "hai"
</code>```

I have written a small piece of code that shows you how to use this. My code is different than yours b/c it loops through the range and checks each cell if the value of the difference between it and NOW is greater than or equal to 1 (which is how to tell if its from lats year or not). Its not how you approach it but it does seem to be more simplified in the approach. Alsoe I soted a bucnh of dates in a spreadsheet and tested this out. just apply to your needs. I hope this helps more?

```<code>Private Sub this()
    Dim rng As Range
    Dim rcell As Range

    Set rng = ThisWorkbook.Sheets("Sheet1").Range("A1:A20")

    For Each rcell In rng.Cells
        'note that if you dont put a handler in here to deal with blank cells values this code will run forever. most peop-le do a check with "if rcell.valeu <> vbNullString then etc etc
        If DateDiff("yyyy", rcell.Value, Now()) >= 1 Then
            Worksheets("Sheet2").Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(1, 0).Value = rcell.Value
            rcell.Value = vbNullString
        End If
    Next rcell
End Sub
</code>```

Body:
The following code checks to see if any of my rows on the main page contain a date from a year ago or older. If it does, it copies it to the "Archive" worksheet and deletes it from the main page. However, what it's doing now is just copying from the main page and overriding what already exists on the archive page instead of adding to the last row. I've tried subbing in LastRow from a function, but I was getting an error with how I was using it. Anyone have a better solution?

Sub TestDateTransfer()
With Application
PrevCalc = .Calculation
.Calculation = xlCalculationManual
.Cursor = xlWait
.Calculate
.EnableEvents = False
.ScreenUpdating = False
End With
Application.DisplayAlerts = False
Worksheets("Archive").Activate
Range("A3:I1000").Select
Selection.ClearContents
Worksheets("Main Page").Activate
Dim MyDate As Date
MyDate = "03/27/2017"
Set i = Sheets("Main Page")
Set E = Sheets("Archive")
Dim d
Dim j
d = 2
j = 2

Do Until IsEmpty(i.Range("C" & j))

  If i.Range("C" & j) <= MyDate - 365 Then
  d = d + 1
  E.rows(d).Value = i.rows(j).Value

  End If
  j = j + 1
 Loop
 Worksheets("Archive").Activate
 ActiveSheet.Range("H1").Select 'To unselect the page
 Worksheets("Main Page").Activate
 MyDate = "03/27/2017"
 Dim y
 Dim z
 y = 2
 z = 2
 Do Until IsEmpty(i.Range("C" & z))

  If i.Range("C" & z) <= MyDate - 365 Then
  y = y + 1
  i.rows(z).Delete

  End If
  z = z + 1
  Loop
 With Application
.Cursor = xlDefault
.Calculate
.Calculation = PrevCalc
'.ScreenUpdating = True 'Not Needed...
.EnableEvents = True
 End With
 ActiveSheet.Range("H1").Select
 End Sub

Body:
 Worksheets("Archive").Cells(Sheet1.Rows.Count, 1).End(xlUp).Offset(1, 0).Value = "hai"

I have written a small piece of code that shows you how to use this. My code is different than yours b/c it loops through the range and checks each cell if the value of the difference between it and NOW is greater than or equal to 1 (which is how to tell if its from lats year or not). Its not how you approach it but it does seem to be more simplified in the approach. Alsoe I soted a bucnh of dates in a spreadsheet and tested this out. just apply to your needs. I hope this helps more?

Private Sub this()
    Dim rng As Range
    Dim rcell As Range

    Set rng = ThisWorkbook.Sheets("Sheet1").Range("A1:A20")

    For Each rcell In rng.Cells
        'note that if you dont put a handler in here to deal with blank cells values this code will run forever. most peop-le do a check with "if rcell.valeu <> vbNullString then etc etc
        If DateDiff("yyyy", rcell.Value, Now()) >= 1 Then
            Worksheets("Sheet2").Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(1, 0).Value = rcell.Value
            rcell.Value = vbNullString
        End If
    Next rcell
End Sub


问:
Vue 2 + Element UI + Laravel 5.3 Starter
Anyone who is experienced to install Element UI on Laravel 5.3

http://element.eleme.io/#/en-US/component/quickstart

Can anyone please help on the steps of installing it on Laravel 5.3? I am pretty new to it and not familiar with npm. Below is what I have done so far:

```<code>npm update vue
npm i element-ui -S
</code>```

package.json

```<code>{
  "private": true,
  "scripts": {
    "prod": "gulp --production",
    "dev": "gulp watch"
  },
  "devDependencies": {
    "babel-plugin-component": "^0.8.0",
    "bootstrap": "^4.0.0-alpha.5",
    "gulp": "^3.9.1",
    "jquery": "^3.1.0",
    "laravel-elixir": "^6.0.0-11",
    "laravel-elixir-vue-2": "^0.2.0",
    "laravel-elixir-webpack-official": "^1.0.2",
    "lodash": "^4.16.2",
    "vue": "^2.0.1",
    "vue-loader": "^9.5.1",
    "vue-resource": "^1.0.3"
  },
  "dependencies": {
    "element-ui": "^1.1.2",
    "toastr": "^2.1.2",
    "vue-html-loader": "^1.2.3",
    "vue-timeago": "^3.1.2",
    "vue2.x-core-image-upload": "^0.9.2"
  }
}
</code>```

In the component that I need to use element UI, for example:

Product-show.vue

```<code><template>
  <el-select v-model="value" placeholder="Select">
    <el-option
      v-for="item in options"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
</template>

<script>

import 'element-ui/lib/theme-default/index.css';
import { Button, Select } from 'element-ui';
  export default {
    components:{
      'el-button': Button,
      'el-select': Select
    },
    data(){
      return{
        product:[],
        productChoiceSelected:{},
        productChoices:[],
        img1:false,
        img2:false,
        img3:false,
        bxslider:{},
        options: [{
          value: 'Option1',
          label: 'Option1'
        }, {
          value: 'Option2',
          label: 'Option2'
        }, {
          value: 'Option3',
          label: 'Option3'
        }, {
          value: 'Option4',
          label: 'Option4'
        }, {
          value: 'Option5',
          label: 'Option5'
        }],
        value: ''
      }
    }
.....
.....
.....
  }
</script>
</code>```

This is what I imagine I should do but of course it does not work for this newbie. Can someone help please?

EDIT#1

Console Log Error:

```<code>    1:1 Uncaught Error: Module parse failed: C:\xampp\htdocs\soyegg\node_modules\element-ui\lib\theme-default\index.css Unexpected character '@' (1:0)
    You may need an appropriate loader to handle this file type.
    | @charset "UTF-8";.el-breadcrumb:after,.el-breadcrumb:before,.el-form-item:after,.el-form-item:before,.el-form-item__content:after,.el-form-item__content:before{display:table;content:""}.el-slider__button,.el-slider__button-wrapper{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none}.el-alert,.el-dialog,.el-notification,.el-radio__inner,.el-switch__core{box-sizing:border-box}.el-pagination--small .arrow.disabled,.el-table td.is-hidden>*,.el-table th.is-hidden>*{visibility:hidden}.el-breadcrumb:after,.el-button-group:after,.el-form-item:after,.el-form-item__content:after,.el-menu:after,.el-pagination:after,.el-picker-panel__body-wrapper::after,.el-picker-panel__body::after,.el-row:after,.el-tabs__header:after{clear:both}.el-autocomplete__suggestions.is-loading li:after{display:inline-block;content:"";height:100%;vertical-align:middle}.el-button-group:after,.el-button-group:before{display:table;content:""}@font-face{font-family:element-icons;src:url(fonts/element-icons.eot?
........
........
........
........
l-collapse-item.is-active .el-collapse-item__header__arrow{-ms-transform:rotate(90deg);transform:rotate(90deg)}.el-collapse-item__header{height:43px;line-height:43px;padding-left:15px;background-color:#fff;color:#475669;cursor:pointer;border-bottom:1px solid #e0e6ed;font-size:13px}.el-collapse-item__header__arrow{margin-right:8px;transition:transform .3s}.el-collapse-item__wrap{will-change:height;background-color:#f9fafc;transition:height .3s cubic-bezier(.215,.61,.355,1);overflow:hidden;box-sizing:border-box;border-bottom:1px solid #e0e6ed}.el-collapse-item__content{padding:10px 15px;font-size:13px;color:#1f2d3d;line-height:1.769230769230769}
        at eval (eval at <anonymous> (app.js:655), <anonymous>:1:7)
        at Object.<anonymous> (app.js:655)
        at __webpack_require__ (app.js:20)
        at eval (eval at <anonymous> (app.js:187), <anonymous>:1:97)
        at Object.<anonymous> (app.js:187)
        at __webpack_require__ (app.js:20)
        at eval (eval at <anonymous> (app.js:125), <anonymous>:4:19)
        at Object.<anonymous> (app.js:125)
        at __webpack_require__ (app.js:20)
        at eval (eval at <anonymous> (app.js:273), <anonymous>:28:31)
    cdn.fontawesome.com/js/stats.js:1 Font Awesome CDN reporting has been enabled
</code>```

答: Try  npm install --save-dev css-loader and  npm install --save-dev style-loader

Body:
Anyone who is experienced to install Element UI on Laravel 5.3

http://element.eleme.io/#/en-US/component/quickstart

Can anyone please help on the steps of installing it on Laravel 5.3? I am pretty new to it and not familiar with npm. Below is what I have done so far:

npm update vue
npm i element-ui -S

package.json

{
  "private": true,
  "scripts": {
    "prod": "gulp --production",
    "dev": "gulp watch"
  },
  "devDependencies": {
    "babel-plugin-component": "^0.8.0",
    "bootstrap": "^4.0.0-alpha.5",
    "gulp": "^3.9.1",
    "jquery": "^3.1.0",
    "laravel-elixir": "^6.0.0-11",
    "laravel-elixir-vue-2": "^0.2.0",
    "laravel-elixir-webpack-official": "^1.0.2",
    "lodash": "^4.16.2",
    "vue": "^2.0.1",
    "vue-loader": "^9.5.1",
    "vue-resource": "^1.0.3"
  },
  "dependencies": {
    "element-ui": "^1.1.2",
    "toastr": "^2.1.2",
    "vue-html-loader": "^1.2.3",
    "vue-timeago": "^3.1.2",
    "vue2.x-core-image-upload": "^0.9.2"
  }
}

In the component that I need to use element UI, for example:

Product-show.vue

<template>
  <el-select v-model="value" placeholder="Select">
    <el-option
      v-for="item in options"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
</template>

This is what I imagine I should do but of course it does not work for this newbie. Can someone help please?

EDIT#1

Console Log Error:

    1:1 Uncaught Error: Module parse failed: C:\xampp\htdocs\soyegg\node_modules\element-ui\lib\theme-default\index.css Unexpected character '@' (1:0)
    You may need an appropriate loader to handle this file type.
    | @charset "UTF-8";.el-breadcrumb:after,.el-breadcrumb:before,.el-form-item:after,.el-form-item:before,.el-form-item__content:after,.el-form-item__content:before{display:table;content:""}.el-slider__button,.el-slider__button-wrapper{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none}.el-alert,.el-dialog,.el-notification,.el-radio__inner,.el-switch__core{box-sizing:border-box}.el-pagination--small .arrow.disabled,.el-table td.is-hidden>*,.el-table th.is-hidden>*{visibility:hidden}.el-breadcrumb:after,.el-button-group:after,.el-form-item:after,.el-form-item__content:after,.el-menu:after,.el-pagination:after,.el-picker-panel__body-wrapper::after,.el-picker-panel__body::after,.el-row:after,.el-tabs__header:after{clear:both}.el-autocomplete__suggestions.is-loading li:after{display:inline-block;content:"";height:100%;vertical-align:middle}.el-button-group:after,.el-button-group:before{display:table;content:""}@font-face{font-family:element-icons;src:url(fonts/element-icons.eot?
........
........
........
........
l-collapse-item.is-active .el-collapse-item__header__arrow{-ms-transform:rotate(90deg);transform:rotate(90deg)}.el-collapse-item__header{height:43px;line-height:43px;padding-left:15px;background-color:#fff;color:#475669;cursor:pointer;border-bottom:1px solid #e0e6ed;font-size:13px}.el-collapse-item__header__arrow{margin-right:8px;transition:transform .3s}.el-collapse-item__wrap{will-change:height;background-color:#f9fafc;transition:height .3s cubic-bezier(.215,.61,.355,1);overflow:hidden;box-sizing:border-box;border-bottom:1px solid #e0e6ed}.el-collapse-item__content{padding:10px 15px;font-size:13px;color:#1f2d3d;line-height:1.769230769230769}
        at eval (eval at <anonymous> (app.js:655), <anonymous>:1:7)
        at Object.<anonymous> (app.js:655)
        at __webpack_require__ (app.js:20)
        at eval (eval at <anonymous> (app.js:187), <anonymous>:1:97)
        at Object.<anonymous> (app.js:187)
        at __webpack_require__ (app.js:20)
        at eval (eval at <anonymous> (app.js:125), <anonymous>:4:19)
        at Object.<anonymous> (app.js:125)
        at __webpack_require__ (app.js:20)
        at eval (eval at <anonymous> (app.js:273), <anonymous>:28:31)
    cdn.fontawesome.com/js/stats.js:1 Font Awesome CDN reporting has been enabled


问:
Xamarin - When try to deploy the build never ending
I'm developing xamarin application for both IOS and Androaid, when I'm try to publish the Ios appliaction to my iphone the build never ends and no error appear, I tring to upgrade my Xcode but this didn't help.
When I'm using the IOS simulator everything works fine, the build ends and the app run as expected. I tried all the solutions that I found on the internet but none of them help.

Is anybody encounter this problem and have solution for this issue??
enter image description here

答:
Xamarin frameworks are updated as latest stable version on both of Visual Studio and MacOs?

Did you accept Apple New License Agreement on your apple account?

You can check logs. (Help->Xamarin->Open Logs)


问:
Excel Sheet SQL Table
I have an Excel sheet. The top row corresponds to column names while successive rows each represent an entry.

How can I convert this Excel sheet into a SQL Table?

I am using SQL Server 2005.

答:
Use MS Access

Create a new MDB

Import the Excel file as a new table

Use the SQL Server upsizing wizard to transfer the table to SQL Server

ContentLicense: CC BY-SA 2.5

Title: Excel Sheet SQL Table


问:
Android - How to set visibility in xml depending on device?
I have a TextView in my activity that should be visible normally, but gone for tablet devices.

I know I can create a new layout file for the tablet, but that seems like a lot of duplication, so what I am trying to do is set in my (single) layout file something like...

android:visibility="@string/my_textview_visibility"

...for the TextView. And then, in my strings resources files, set...

<string name="my_textview_visibility">gone</string> (in values/strings.xml)

...and...

<string name="my_textview_visibility">visible</string> (in values-sw720dp/strings.xml)

...to hide the TextView for tablets.

However, when I try this, the app crashes when trying to show that activity.

Do I need to use the constant values instead of the above string values - e.g.,

"visible" -> 0

"gone" -> 8

..and, if so, what is the correct way to add/reference those values to/from my XML files?

Or is there another/better way of doing it?

NB - I do not want to show/hide the TextView programatically in my Java code.

答: ChrisStillwell's answer is correct. But the values are incorrect according to the Android Documentation


问:
How to keep the height of an outer div equal to the inner div?
I have an inner div used for overlay, set to a min-height property. When the height of the overlay changes, the height of the outer div will not be affected.

#outer {
  width: 70px;
  height: 70px;
  background-color: #000;
  position: relative;
}
#inner {
  min-height: 100%;
  min-width: 100%;
  background-color: #000;
  opacity: 0.5;
  position: absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>

  <div id = "outer">
    <div id = "inner">
      <br><br><br><br><br><br><br>
    </div>
  </div>

</body>
</html></code>```

Update:

The problem seems to be with the absolute positioning. What other ways to do an overlay while keeping the outer div's height equal to it?

答:
As I wrote in my comments, there's no way if you use absolute position. But if you change the code as follows, it works (still depending on the actual situation):

#outer {
  width: 70px;
  min-height: 70px;
  background-color: #000;
}
#inner {
  height: 100%;
  min-width: 100%;
  background-color: #fff;
  opacity: 0.5;
  overflow: visible;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>

  <div id = "outer">
    <div id = "inner">
      <br>1<br>2<br>3<br>4<br>5<br>6<br>
    </div>
  </div>

</body>
</html></code>```

Body:
I have an inner div used for overlay, set to a min-height property. When the height of the overlay changes, the height of the outer div will not be affected.

#outer {
  width: 70px;
  height: 70px;
  background-color: #000;
  position: relative;
}
#inner {
  min-height: 100%;
  min-width: 100%;
  background-color: #000;
  opacity: 0.5;
  position: absolute;
}

<!DOCTYPE html>

  <title></title>

Update:

The problem seems to be with the absolute positioning. What other ways to do an overlay while keeping the outer div's height equal to it?

Body:
As I wrote in my comments, there's no way if you use absolute position. But if you change the code as follows, it works (still depending on the actual situation):

#outer {
  width: 70px;
  min-height: 70px;
  background-color: #000;
}
#inner {
  height: 100%;
  min-width: 100%;
  background-color: #fff;
  opacity: 0.5;
  overflow: visible;
}

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>

  <div id = "outer">
    <div id = "inner">
      <br>1<br>2<br>3<br>4<br>5<br>6<br>
    </div>
  </div>

</body>
</html>


问:
Display an image in an object though html. JQuery
I am displaying information taken from an object in local storage on a html page. the H2, H5 and p are all pulling through but i cannot get the image though. Any ideas? the code shows the Jquery and the html that i am using to pull the information into the page.</p>

```<code>//JQuery
    function displayPageContent(object){
                if(object){
                    $('#bar-info h2').html(object.barname);
                    $('#bar-info h5').html(object.address);
                    $('#bar-info p').html(object.description);
                    $('#bar-info img src').html(object.image);

                }
            }
            displayPageContent(pageBar);

    //HTML
     <div class="content">
                <div id="bar-info">
                    <center><h2></h2></center>
                    <h5></h5>
                    <p></p>
                    <img scr="">
                </div>
</code>```

答:
You need to set the  src with .attr(). Like this:

$('img').attr('src', 'image-src');

Body:
I am displaying information taken from an object in local storage on a html page. the H2, H5 and p are all pulling through but i cannot get the image though. Any ideas? the code shows the Jquery and the html that i am using to pull the information into the page.

//JQuery
    function displayPageContent(object){
                if(object){
                    $('#bar-info h2').html(object.barname);
                    $('#bar-info h5').html(object.address);
                    $('#bar-info p').html(object.description);
                    $('#bar-info img src').html(object.image);

                }
            }
            displayPageContent(pageBar);

    //HTML

Body:
You need to set the <img> src with .attr(). Like this:

$('img').attr('src', 'image-src');


答:
Your code isn't actually finding the maximum, it's printing out every number that is bigger than the first number it reads in. Notice that you never assign big a new value. Also, maximum is purely keeping track of the numbers larger than big (the first number in the file).

This should do it:

```<code>while (fileScanner.hasNextInt()) {
    int num = fileScanner.nextInt();
    if (num > big)
       big = num;
}
</code>```

Body:
Your code isn't actually finding the maximum, it's printing out every number that is bigger than the first number it reads in. Notice that you never assign big a new value. Also, maximum is purely keeping track of the numbers larger than big (the first number in the file).

This should do it:

while (fileScanner.hasNextInt()) {
    int num = fileScanner.nextInt();
    if (num > big)
       big = num;
}


答:
$('#bar-info img src').html(object.image); would select an element named src and set its html.

You want to set the img's src attribute: $('#bar-info img').attr('src', object.image);

Title: Display an image in an object though html. JQuery


问:
Counting preceding/succeeding cell values in a range in Excel
I am trying to figure out how to write a formula to count preceding and succeeding cell values of a specific value in a range. Here is an example:

For this column, how many times does "black" come before "red", how many times does "green" come before "yellow", etc?

Color List

答:
If you merely want to count the occurrence of one color before the 1-st occurrence of another color then you might be done with the following formula:

```<code>=COUNTIF($A$2:INDEX(A2:A16,MATCH(E2,A2:A16,0)),C2)
</code>```

But if you wish to cound the occurrence of one color before the n-th occurrence of another color then you are probably looking for the following solution:

```<code>=COUNTIF($A$2:INDEX(A2:A16,SMALL(IF(A2:A16=E2,ROW(A2:A16)-ROW(INDEX(A2:A16,1,1))+1),D2)),C2)
</code>```

Note, that the second formula is an array formula and must be entered using Ctrl + Shift + Enter.

Body:
If you merely want to count the occurrence of one color before the 1-st occurrence of another color then you might be done with the following formula:

=COUNTIF($A$2:INDEX(A2:A16,MATCH(E2,A2:A16,0)),C2)

But if you wish to cound the occurrence of one color before the n-th occurrence of another color then you are probably looking for the following solution:

=COUNTIF($A$2:INDEX(A2:A16,SMALL(IF(A2:A16=E2,ROW(A2:A16)-ROW(INDEX(A2:A16,1,1))+1),D2)),C2)

Note, that the second formula is an array formula and must be entered using Ctrl + Shift + Enter.


问:
Onclick an element, sliding toggle of div
I am trying to do an accordian style opening/closing of div using jquery. But for some reason the next() in jquery doesn't seem to be working. I want when a title is clicked, all other div should be closed except the clicked one.

Html code --

```<code><div class="office-row">
  <h3 class="office-title">Title</h3>
</div>
<div class="office">sadasd</div>
<div class="office-row">
  <h3 class="office-title">Title</h3>
</div>
<div class="office">sadasd</div>
<div class="office-row">
  <h3 class="office-title">Title</h3>
</div>
</code>```

Demo -- https://jsfiddle.net/v3hc19np/1/

Any help is highly appreciated.

答:
Like others said, there is no $.next('div') adjacent to the titles, so I moved .office in so that that element is now adjacent to it. Updated with your original HTML.

$(function() {
  var $titles = $('.office-title'),
      $offices = $('.office');
  $titles.on('click', function() {
    var $target = $(this).parent('.office-row').next('.office');
    $target.slideToggle();
    $offices.not($target).slideUp();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.office {
  display: none;
}</code>```

Title

sadasd

Title

sadasd

Title

sadasd
```

Body:
I am trying to do an accordian style opening/closing of div using jquery. But for some reason the next() in jquery doesn't seem to be working. I want when a title is clicked, all other div should be closed except the clicked one.

Html code --

Title

sadasd

Title

sadasd

Title

Demo -- https://jsfiddle.net/v3hc19np/1/

Any help is highly appreciated.

Body:
Like others said, there is no $.next('div') adjacent to the titles, so I moved .office in so that that element is now adjacent to it. Updated with your original HTML.

$(function() {
  var $titles = $('.office-title'),
      $offices = $('.office');
  $titles.on('click', function() {
    var $target = $(this).parent('.office-row').next('.office');
    $target.slideToggle();
    $offices.not($target).slideUp();
  });
});

.office {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="office-row">
  <h3 class="office-title">Title</h3>
</div>
<div class="office">sadasd</div>
<div class="office-row">
  <h3 class="office-title">Title</h3>
</div>
<div class="office">sadasd</div>
<div class="office-row">
  <h3 class="office-title">Title</h3>
</div>
<div class="office">sadasd</div>


问:
How to save all items listed on listbox with my.settings
I Try to save all the items from a list box with MY.SETTINGS
And Retrieved again on load
But it seems i made an error but i cannot figure out what.

its give 2 error

This is the errors

Error   3   'itemmd5' is not a member of 'MediaAdsAntivirus.My.MySettings'.

Error   2   'myitems' is not a member of 'MediaAdsAntivirus.My.MySettings'.

For this errors i just figure out i forgot to add it on settings

but now i just have a new error
This Is My New Error
Error   2   Value of type 'System.Windows.Forms.ListBox.ObjectCollection' cannot be converted to 'String'.

And i need to load them on loadfrom
How Can I List All Items Again In To It

This Is My Code:

```<code>Imports System.IO
Imports System.Security
Imports System.Security.Cryptography
Imports System.Text
Imports System.Net

Public Class form15
Dim md5hashindexer = 1
Dim md5namesave = "Hashes"

#Region "Atalhos para o principal hash_generator função"

Function md5_hash(ByVal file_name As String)

    Return hash_generator("md5", file_name)

End Function

Function sha_1(ByVal file_name As String)

    Return hash_generator("sha1", file_name)

End Function

Function sha_256(ByVal file_name As String)

    Return hash_generator("sha256", file_name)

End Function

#End Region

Function hash_generator(ByVal hash_type As String, ByVal file_name As String)

    Dim hash
    If hash_type.ToLower = "md5" Then

        hash = MD5.Create
    ElseIf hash_type.ToLower = "sha1" Then

        hash = SHA1.Create()
    ElseIf hash_type.ToLower = "sha256" Then

        hash = SHA256.Create()
    Else
        MsgBox("Type de hash inconnu : " & hash_type, MsgBoxStyle.Critical)
        Return False
    End If

    Dim hashValue() As Byte

    Dim fileStream As FileStream = File.OpenRead(file_name)

    fileStream.Position = 0

    hashValue = hash.ComputeHash(fileStream)

    Dim hash_hex = PrintByteArray(hashValue)

    fileStream.Close()

    Return hash_hex

End Function

Public Function PrintByteArray(ByVal array() As Byte)

    Dim hex_value As String = ""

    Dim i As Integer
    For i = 0 To array.Length - 1

        hex_value += array(i).ToString("X2")

    Next i

    Return hex_value.ToLower

End Function

Private Sub BT_Parcourir_Click(sender As System.Object, e As System.EventArgs) Handles BT_Parcourir.Click

    If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then

        Dim path As String = OpenFileDialog1.FileName

        TB_path.Text = path

        LB_md5.Text = md5_hash(path)
        LB_sha1.Text = sha_1(path)
        LB_sha256.Text = sha_256(path)
        ListBox1.Items.Add(LB_md5.Text)
        ListBox1.SelectedIndex += 1
        Dim itemmd5 = LB_sha256.Text
        Dim itemname = md5namesave + md5hashindexer
        For Each line As String In ListBox1.Items
            itemmd5 = My.Settings.myitems
            My.Settings.itemmd5 = ListBox1.Items

        Next
    End If

End Sub

Private Sub LB_sha256_Click(sender As Object, e As EventArgs) Handles LB_sha256.Click

End Sub

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs)

End Sub

Private Sub form15_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub
End Class
</code>```

答:
I finally decide to save in txt file and load The data again from it
This Is The Working Code</p>

```<code>Imports System.IO
Imports System.Security
Imports System.Security.Cryptography
Imports System.Text
Imports System.Net

Public Class form15
Dim md5hashindexer = 1

#Region "Atalhos para o principal hash_generator função"

Function md5_hash(ByVal file_name As String)

    Return hash_generator("md5", file_name)

End Function

Function sha_1(ByVal file_name As String)

    Return hash_generator("sha1", file_name)

End Function

Function sha_256(ByVal file_name As String)

    Return hash_generator("sha256", file_name)

End Function

#End Region

Function hash_generator(ByVal hash_type As String, ByVal file_name As String)

    Dim hash
    If hash_type.ToLower = "md5" Then

        hash = MD5.Create
    ElseIf hash_type.ToLower = "sha1" Then

        hash = SHA1.Create()
    ElseIf hash_type.ToLower = "sha256" Then

        hash = SHA256.Create()
    Else
        MsgBox("Type de hash inconnu : " & hash_type, MsgBoxStyle.Critical)
        Return False
    End If

    Dim hashValue() As Byte

    Dim fileStream As FileStream = File.OpenRead(file_name)

    fileStream.Position = 0

    hashValue = hash.ComputeHash(fileStream)

    Dim hash_hex = PrintByteArray(hashValue)

    fileStream.Close()

    Return hash_hex

End Function

Public Function PrintByteArray(ByVal array() As Byte)

    Dim hex_value As String = ""

    Dim i As Integer
    For i = 0 To array.Length - 1

        hex_value += array(i).ToString("X2")

    Next i

    Return hex_value.ToLower

End Function

Private Sub BT_Parcourir_Click(sender As System.Object, e As System.EventArgs) Handles BT_Parcourir.Click

    If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then

        Dim path As String = OpenFileDialog1.FileName

        TB_path.Text = path

        LB_md5.Text = md5_hash(path)
        LB_sha1.Text = sha_1(path)
        LB_sha256.Text = sha_256(path)
        ListBox1.Items.Add(LB_md5.Text)
        ListBox1.SelectedIndex += 1
        Dim itemmd5 = LB_sha256.Text

        'For Each line As String In ListBox1.Items

        'My.Settings.itemsmd5 = itemmd5
        'md5hashindexer += 1
        'Next
    End If

    Dim sb As New System.Text.StringBuilder()

    For Each o As Object In ListBox1.Items
        sb.AppendLine(o)
    Next

    System.IO.File.WriteAllText("c:\checkedfilesmd5.txt", sb.ToString())

End Sub

Private Sub LB_sha256_Click(sender As Object, e As EventArgs) Handles LB_sha256.Click

End Sub

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs)

End Sub

Private Sub form15_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim lines() As String = IO.File.ReadAllLines("c:\checkedfilesmd5.txt")
    ListBox1.Items.AddRange(lines)
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim sb As New System.Text.StringBuilder()

    For Each o As Object In ListBox1.Items
        sb.AppendLine(o)
    Next

    System.IO.File.WriteAllText("c:\checkedfilesmd5.txt", sb.ToString())
    MsgBox("Dados Guardados")
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim lines() As String = IO.File.ReadAllLines("c:\checkedfilesmd5.txt")
    ListBox1.Items.AddRange(lines)
End Sub

Private Sub Label6_Click(sender As Object, e As EventArgs) Handles Label6.Click
    ListBox1.Items.Clear()
End Sub

Private Sub Label7_Click(sender As Object, e As EventArgs) Handles Label7.Click
    MsgBox("Atençao Voce Vai Apagar Todos Os Dados Ja Escaneados")
    ListBox1.Items.Clear()
    System.IO.File.Delete("c:\checkedfilesmd5.txt")
End Sub
End Class
</code>```

Body:
I Try to save all the items from a list box with MY.SETTINGS
And Retrieved again on load
But it seems i made an error but i cannot figure out what.

its give 2 error

This is the errors

Error   3   'itemmd5' is not a member of 'MediaAdsAntivirus.My.MySettings'.

Error   2   'myitems' is not a member of 'MediaAdsAntivirus.My.MySettings'.

For this errors i just figure out i forgot to add it on settings

but now i just have a new error
This Is My New Error
Error   2   Value of type 'System.Windows.Forms.ListBox.ObjectCollection' cannot be converted to 'String'.

And i need to load them on loadfrom
How Can I List All Items Again In To It

This Is My Code:

Imports System.IO
Imports System.Security
Imports System.Security.Cryptography
Imports System.Text
Imports System.Net

Public Class form15
Dim md5hashindexer = 1
Dim md5namesave = "Hashes"

#Region "Atalhos para o principal hash_generator função"

Function md5_hash(ByVal file_name As String)

    Return hash_generator("md5", file_name)

End Function

Function sha_1(ByVal file_name As String)

    Return hash_generator("sha1", file_name)

End Function

Function sha_256(ByVal file_name As String)

    Return hash_generator("sha256", file_name)

End Function

#End Region

Function hash_generator(ByVal hash_type As String, ByVal file_name As String)

    Dim hash
    If hash_type.ToLower = "md5" Then

        hash = MD5.Create
    ElseIf hash_type.ToLower = "sha1" Then

        hash = SHA1.Create()
    ElseIf hash_type.ToLower = "sha256" Then

        hash = SHA256.Create()
    Else
        MsgBox("Type de hash inconnu : " & hash_type, MsgBoxStyle.Critical)
        Return False
    End If

    Dim hashValue() As Byte

    Dim fileStream As FileStream = File.OpenRead(file_name)

    fileStream.Position = 0

    hashValue = hash.ComputeHash(fileStream)

    Dim hash_hex = PrintByteArray(hashValue)

    fileStream.Close()

    Return hash_hex

End Function

Public Function PrintByteArray(ByVal array() As Byte)

    Dim hex_value As String = ""

    Dim i As Integer
    For i = 0 To array.Length - 1

        hex_value += array(i).ToString("X2")

    Next i

    Return hex_value.ToLower

End Function

Private Sub BT_Parcourir_Click(sender As System.Object, e As System.EventArgs) Handles BT_Parcourir.Click

    If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then

        Dim path As String = OpenFileDialog1.FileName

        TB_path.Text = path

        LB_md5.Text = md5_hash(path)
        LB_sha1.Text = sha_1(path)
        LB_sha256.Text = sha_256(path)
        ListBox1.Items.Add(LB_md5.Text)
        ListBox1.SelectedIndex += 1
        Dim itemmd5 = LB_sha256.Text
        Dim itemname = md5namesave + md5hashindexer
        For Each line As String In ListBox1.Items
            itemmd5 = My.Settings.myitems
            My.Settings.itemmd5 = ListBox1.Items

        Next
    End If

End Sub

Private Sub LB_sha256_Click(sender As Object, e As EventArgs) Handles LB_sha256.Click

End Sub

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs)

End Sub

Private Sub form15_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub
End Class

Body:
I finally decide to save in txt file and load The data again from it
This Is The Working Code

Imports System.IO
Imports System.Security
Imports System.Security.Cryptography
Imports System.Text
Imports System.Net

Public Class form15
Dim md5hashindexer = 1

#Region "Atalhos para o principal hash_generator função"

Function md5_hash(ByVal file_name As String)

    Return hash_generator("md5", file_name)

End Function

Function sha_1(ByVal file_name As String)

    Return hash_generator("sha1", file_name)

End Function

Function sha_256(ByVal file_name As String)

    Return hash_generator("sha256", file_name)

End Function

#End Region

Function hash_generator(ByVal hash_type As String, ByVal file_name As String)

    Dim hash
    If hash_type.ToLower = "md5" Then

        hash = MD5.Create
    ElseIf hash_type.ToLower = "sha1" Then

        hash = SHA1.Create()
    ElseIf hash_type.ToLower = "sha256" Then

        hash = SHA256.Create()
    Else
        MsgBox("Type de hash inconnu : " & hash_type, MsgBoxStyle.Critical)
        Return False
    End If

    Dim hashValue() As Byte

    Dim fileStream As FileStream = File.OpenRead(file_name)

    fileStream.Position = 0

    hashValue = hash.ComputeHash(fileStream)

    Dim hash_hex = PrintByteArray(hashValue)

    fileStream.Close()

    Return hash_hex

End Function

Public Function PrintByteArray(ByVal array() As Byte)

    Dim hex_value As String = ""

    Dim i As Integer
    For i = 0 To array.Length - 1

        hex_value += array(i).ToString("X2")

    Next i

    Return hex_value.ToLower

End Function

Private Sub BT_Parcourir_Click(sender As System.Object, e As System.EventArgs) Handles BT_Parcourir.Click

    If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then

        Dim path As String = OpenFileDialog1.FileName

        TB_path.Text = path

        LB_md5.Text = md5_hash(path)
        LB_sha1.Text = sha_1(path)
        LB_sha256.Text = sha_256(path)
        ListBox1.Items.Add(LB_md5.Text)
        ListBox1.SelectedIndex += 1
        Dim itemmd5 = LB_sha256.Text

        'For Each line As String In ListBox1.Items

        'My.Settings.itemsmd5 = itemmd5
        'md5hashindexer += 1
        'Next
    End If

    Dim sb As New System.Text.StringBuilder()

    For Each o As Object In ListBox1.Items
        sb.AppendLine(o)
    Next

    System.IO.File.WriteAllText("c:\checkedfilesmd5.txt", sb.ToString())

End Sub

Private Sub LB_sha256_Click(sender As Object, e As EventArgs) Handles LB_sha256.Click

End Sub

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs)

End Sub

Private Sub form15_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim lines() As String = IO.File.ReadAllLines("c:\checkedfilesmd5.txt")
    ListBox1.Items.AddRange(lines)
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim sb As New System.Text.StringBuilder()

    For Each o As Object In ListBox1.Items
        sb.AppendLine(o)
    Next

    System.IO.File.WriteAllText("c:\checkedfilesmd5.txt", sb.ToString())
    MsgBox("Dados Guardados")
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim lines() As String = IO.File.ReadAllLines("c:\checkedfilesmd5.txt")
    ListBox1.Items.AddRange(lines)
End Sub

Private Sub Label6_Click(sender As Object, e As EventArgs) Handles Label6.Click
    ListBox1.Items.Clear()
End Sub

Private Sub Label7_Click(sender As Object, e As EventArgs) Handles Label7.Click
    MsgBox("Atençao Voce Vai Apagar Todos Os Dados Ja Escaneados")
    ListBox1.Items.Clear()
    System.IO.File.Delete("c:\checkedfilesmd5.txt")
End Sub
End Class


问:
how to use the gcc preprocessor macro __FAST_MATH__?
man gcc(1) says: the option -ffast-math causes the preprocessor macro __FAST_MATH__ to be defined. Is there any further documentation of that macro?

I would expect that code like

```<code>#define __FAST_MATH__ blabla
y = pow(x,a);
#undef __FAST_MATH__
</code>```

allows control of math optimization, fine grained down to single statements.

However, my tests rather indicate that

```<code>#define __FAST_MATH__
#define __FAST_MATH__ on
</code>```

are all ignored, regardless where they are placed.

[EDIT] They are ignored even if they are placed before

```<code>#include <math.h>
</code>```

"Ignored" means: have no measurable effect. Whereas -ffast-math accelerates my test code by a factor of 3.

答:
I believe that you have it backwards. The macro is defined in order for the standard library to use different implementations of the math functions.

Defining it yourself has no effect and might actually be dangerously buggy because the program would be using those alternate implementations when the compiler is not generating the expected code.

Body:
man gcc(1) says: the option -ffast-math causes the preprocessor macro __FAST_MATH__ to be defined. Is there any further documentation of that macro?

I would expect that code like

#define __FAST_MATH__ blabla
y = pow(x,a);
#undef __FAST_MATH__

allows control of math optimization, fine grained down to single statements.

However, my tests rather indicate that

#define __FAST_MATH__
#define __FAST_MATH__ on

are all ignored, regardless where they are placed.

[EDIT] They are ignored even if they are placed before

#include <math.h>

"Ignored" means: have no measurable effect. Whereas -ffast-math accelerates my test code by a factor of 3.


问:
PHP and Python static methods in objects, two different worlds...?
i'm php coder, trying to get into python world, and it's very hard for me.

Biggest enjoy of static methods in php is automatic builder of instance. No need to declare object, if you needed it once, in every file (or with different constructor params , in one line)

```<code><?php
class Foo {
    function __constructor__(){
        $this->var = 'blah';
    }
   public static function aStaticMethod() {
       return $this->var;
   }
}

echo Foo::aStaticMethod();
?>
</code>```

we can call constructor from static method don't we? and we can access everything in class as it would be simple method ... we can even have STATIC CONSTRUCTOR in php class and call it like so: Object::construct()->myMethod(); (to pass different params every time)

but not in python???? @staticmethod makes method in class a simple function that doesn't see totally anything ??

```<code>class socket(object):

def __init__(self):
    self.oclass = otherclass()
    print 'test' # does this constructor called at all when calling static method??

@staticmethod
def ping():
    return self.oclass.send('PING') # i can't access anything!!!

print Anidb.ping()
</code>```

I can't access anything from that god damned static method, it's like a standalone function or something like this..??

Maybe I'm using the wrong decorator? Maybe there's something like php offers with static methods in python?

1) Please tell why static methods is isolated
2) Please tell me how to make the same behavior like php static methods have.
3) Please tell me alternative practical use of this, if php static methods behavior is a bad thing

P.s. the goal of all this to write totally less code as much as possible.
P.p.s Heavy commenting of sample code is appreciated

Thank you.

答:
You want classmethod instead. That provides the class as the first argument.

EDIT:

```<code>class C(object):
  foo = 42

  @classmethod
  def printfoo(cls):
    print cls.foo

C.printfoo()
</code>```

Body:
i'm php coder, trying to get into python world, and it's very hard for me.

Biggest enjoy of static methods in php is automatic builder of instance. No need to declare object, if you needed it once, in every file (or with different constructor params , in one line)

<?php
class Foo {
    function __constructor__(){
        $this->var = 'blah';
    }
   public static function aStaticMethod() {
       return $this->var;
   }
}

echo Foo::aStaticMethod();
?>

we can call constructor from static method don't we? and we can access everything in class as it would be simple method ... we can even have STATIC CONSTRUCTOR in php class and call it like so: Object::construct()->myMethod(); (to pass different params every time)

but not in python???? @staticmethod makes method in class a simple function that doesn't see totally anything ??

class socket(object):

def __init__(self):
    self.oclass = otherclass()
    print 'test' # does this constructor called at all when calling static method??

@staticmethod
def ping():
    return self.oclass.send('PING') # i can't access anything!!!

print Anidb.ping()

I can't access anything from that god damned static method, it's like a standalone function or something like this..??

Maybe I'm using the wrong decorator? Maybe there's something like php offers with static methods in python?

1) Please tell why static methods is isolated
2) Please tell me how to make the same behavior like php static methods have.
3) Please tell me alternative practical use of this, if php static methods behavior is a bad thing

P.s. the goal of all this to write totally less code as much as possible.
P.p.s Heavy commenting of sample code is appreciated

Thank you.

Body:
You want classmethod instead. That provides the class as the first argument.

EDIT:

class C(object):
  foo = 42

  @classmethod
  def printfoo(cls):
    print cls.foo

C.printfoo()


问:
Is it dangerous to create pure virtual function of a virtual function?
Let us suppose that we have an abstract class NonEditableSuperBase from which we create another abstract class MyBase.

The first class NonEditableSuperBase has a virtual function (non pure virtual). However, I want to force that if someone creates a class that derives from MyBase, he/she must provide an implementation to the mentioned function.

Hence, my idea is to define the function as pure virtual in MyBase.

My question: Is it a bad idea given that it was just virtual in NonEditableSuperBase?

Example:

```<code>//NonEditableSuperBase.h
class NonEditableSuperBase
{
  ...
  public:
    virtual int someMethod(); //It has an implementation, suppose {return 42;}
};

//MyBase.h
class MyBase: public NonEditableSuperBase
{
  public:
     explicit MyBase();
     virtual ~MyBase() = default;
     virtual int someMethod() = 0;  //I make it pure virtual
};

//MyBase.cpp
MyBase::MyBase() : NonEditableSuperBase() { }

//Now someone creates a derived class from MyBase.
class SuperDerived : public MyBase
{
  public:
    explicit SuperDerived();
    int someMethod(); //The user must create an implementation of the function
};
</code>```

Update:
As an example, in my case I want to create some derived classes from the QAbstractTableModel class of the Qt framework. To reuse some code I want to create an intermediate abstract class.

```<code>QAbstractTableModel <- MyAbstractModel <- MyModelA (or MyModelB ... etc).
</code>```

However, I want to ensure that the models (MyModelA, MyModelB) re-implement some of the virtual functions of QAbstractTableModel (like the ::index() function) because some of the additional methods of MyAbstractModel requires specific implementations of the primer functions.

答:
From ISO IEC 14882 2014:

§ 10.4 says:

5  [ Note: An abstract class can be derived from a class that is not abstract, and a pure virtual function may
override a virtual function which is not pure. —end note ]

So It's perfectly possible to do that.

Example of use case:

You can have a basic type, that is implemented as a concrete type (base class). Now, for subtypes, we might be in a need of further additional information. So, we can have an abstract intermediate object to meet our needs.

Body:
Let us suppose that we have an abstract class NonEditableSuperBase from which we create another abstract class MyBase.

The first class NonEditableSuperBase has a virtual function (non pure virtual). However, I want to force that if someone creates a class that derives from MyBase, he/she must provide an implementation to the mentioned function.

Hence, my idea is to define the function as pure virtual in MyBase.

My question: Is it a bad idea given that it was just virtual in NonEditableSuperBase?

Example:

//NonEditableSuperBase.h
class NonEditableSuperBase
{
  ...
  public:
    virtual int someMethod(); //It has an implementation, suppose {return 42;}
};

//MyBase.h
class MyBase: public NonEditableSuperBase
{
  public:
     explicit MyBase();
     virtual ~MyBase() = default;
     virtual int someMethod() = 0;  //I make it pure virtual
};

//MyBase.cpp
MyBase::MyBase() : NonEditableSuperBase() { }

//Now someone creates a derived class from MyBase.
class SuperDerived : public MyBase
{
  public:
    explicit SuperDerived();
    int someMethod(); //The user must create an implementation of the function
};

Update:
As an example, in my case I want to create some derived classes from the QAbstractTableModel class of the Qt framework. To reuse some code I want to create an intermediate abstract class.

QAbstractTableModel <- MyAbstractModel <- MyModelA (or MyModelB ... etc).

However, I want to ensure that the models (MyModelA, MyModelB) re-implement some of the virtual functions of QAbstractTableModel (like the ::index() function) because some of the additional methods of MyAbstractModel requires specific implementations of the primer functions.


问:
Creating self-executable node.js server
I would like to create an executable bash file that will execute the command
node app.js - the goal is to have an executable file that can be opened on a local machine on which node is already installed and the executable is inside the project directory (It's an express.js app).

I'm trying to do it on a mac, I've written a .command file, made it executable and added the command.
Problem is, the process immediately closes, as the terminal seems to automatically add exit; after the last command.
I would like to do it on Windows machines also.

I don't need the entire app in an executable file, only the option to double click a file instead of opening the terminal and manually writing that simple command.

Any idea how to achieve this?

答:
.command run in the User folder, so you have to enter the project folder to run the node script

```<code>cd /something/project
node app.js
</code>```

it worked for me on mac.

windows i think you just need to make it a .bat and it should work

you could use npm start instead of node app.js

Title: Creating self-executable node.js server

Body:
.command run in the User folder, so you have to enter the project folder to run the node script

cd /something/project
node app.js

it worked for me on mac.

windows i think you just need to make it a .bat and it should work

you could use npm start instead of node app.js


问:
RoboFile composer autoload trait not found
I'm trying to use a Parameter file writer package in my RoboFile, loading it via composer.

RoboClass:

```<code><?php
use Symfony\Component\Finder\Finder;
use Robo\Result;
use Robo\Collection\CollectionBuilder;
use Nordcode\RoboParameters\loadTasks;

  class RoboFile extends \Robo\Tasks
  {
    use loadTasks;

    public function sometask()
    {
       //something
    }
</code>```

when trying to call sometask()
I get the following error:

```<code>PHP Fatal error: Trait 'Nordcode\RoboParameters\loadTasks' not found in /projects/Robo/RoboFile.php on line 9
</code>```

while I can find it in composers autoload_classmap.php

```<code>'NordCode\\RoboParameters\\loadTasks' => $vendorDir . '/nordcode/robo-parameters/src/loadTasks.php',
</code>```

Am I missing something?

Edit 12.02.16:
Fixed "\" in at the beginning of the namespace, doesn't seem to make a difference

Also fixed lower case trait name :)

The contents of what appears to be the bootstrap.php

```<code><?php

if (strpos(basename(__FILE__), 'phar')) {
    require_once 'phar://robo.phar/vendor/autoload.php';
} else {
    if (file_exists(__DIR__.'/vendor/autoload.php')) {
        require_once __DIR__.'/vendor/autoload.php';
    } elseif (file_exists(__DIR__.'/../../autoload.php')) {
        require_once __DIR__ . '/../../autoload.php';
    } else {
        require_once 'phar://robo.phar/vendor/autoload.php';
    }
}
$runner = new \Robo\Runner();
$statusCode = $runner->execute($_SERVER['argv']);
exit($statusCode);
</code>```

contents of LoadTasks

```<code><?php

namespace NordCode\RoboParameters;

use NordCode\RoboParameters\Task\Parameters;
use NordCode\RoboParameters\Task\SymfonyParameters;

trait LoadTasks
{
   //functions
}
</code>```

答:
I am working with Tobias and it worked for me now...
I did not exactly change anything. Just re-setup it on my machine.</p>

Body:
I'm trying to use a Parameter file writer package in my RoboFile, loading it via composer.

RoboClass:

<?php
use Symfony\Component\Finder\Finder;
use Robo\Result;
use Robo\Collection\CollectionBuilder;
use Nordcode\RoboParameters\loadTasks;

  class RoboFile extends \Robo\Tasks
  {
    use loadTasks;

    public function sometask()
    {
       //something
    }

when trying to call sometask()
I get the following error:

PHP Fatal error: Trait 'Nordcode\RoboParameters\loadTasks' not found in /projects/Robo/RoboFile.php on line 9

while I can find it in composers autoload_classmap.php

'NordCode\\RoboParameters\\loadTasks' => $vendorDir . '/nordcode/robo-parameters/src/loadTasks.php',

Am I missing something?

Edit 12.02.16:
Fixed "\" in at the beginning of the namespace, doesn't seem to make a difference

Also fixed lower case trait name :)

The contents of what appears to be the bootstrap.php

<?php

if (strpos(basename(__FILE__), 'phar')) {
    require_once 'phar://robo.phar/vendor/autoload.php';
} else {
    if (file_exists(__DIR__.'/vendor/autoload.php')) {
        require_once __DIR__.'/vendor/autoload.php';
    } elseif (file_exists(__DIR__.'/../../autoload.php')) {
        require_once __DIR__ . '/../../autoload.php';
    } else {
        require_once 'phar://robo.phar/vendor/autoload.php';
    }
}
$runner = new \Robo\Runner();
$statusCode = $runner->execute($_SERVER['argv']);
exit($statusCode);

contents of LoadTasks

<?php

namespace NordCode\RoboParameters;

use NordCode\RoboParameters\Task\Parameters;
use NordCode\RoboParameters\Task\SymfonyParameters;

trait LoadTasks
{
   //functions
}


答:
This way works for me:
Example (MySQLi Procedural)

```<code>$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 results";
}

mysqli_close($conn);
?>
</code>```

Example (MySQLi Object-oriented)

```<code> <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    echo "<table><tr><th>ID</th><th>Name</th></tr>";
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>".$row["id"]."</td><td>".$row["firstname"]." ".$row["lastname"]."</td></tr>";
    }
    echo "</table>";
} else {
    echo "0 results";
}
$conn->close();
?>
</code>```

Example (PDO)

```<code> <?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";

class TableRows extends RecursiveIteratorIterator {
    function __construct($it) {
        parent::__construct($it, self::LEAVES_ONLY);
    }

    function current() {
        return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
    }

    function beginChildren() {
        echo "<tr>";
    }

    function endChildren() {
        echo "</tr>" . "\n";
    }
}

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
        echo $v;
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
</code>```

These examples are from w3schools.

https://www.w3schools.com

Title: Connection to DB via PHP not working

Body:
Im sure this is very trivial, but I just can´t figure it out. I used part of my code that works on another server but not on my new web.
In separate file I got this:

<?php
define('MYSQL_HOST','c236um.forpsi.com');
define('MYSQL_USER','abcd');
define('MYSQL_PASSWORD','xyz');
define('MYSQL_DB','abcd');

$db = mysqli_connect (MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die("failed to connect");
mysqli_select_db(MYSQL_DB, $db) or die(mysqli_error($db));
mysqli_query("SET NAMES UTF8");
?>

and in index.php I simply include that file in body:

include "protected/_mysql.php";

With this the contents of the body isn´t displaying, there is just blank white page. If I put some text as error notification instead of variable in

mysqli_select_db(MYSQL_DB, $db) or die(mysqli_error($db));

it will display that error text.
I tried to put localhost as MYSQL_HOST, but that displays the first "failed to connect" error.
What am I doing wrong?

Body:
This way works for me:
Example (MySQLi Procedural)

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 results";
}

mysqli_close($conn);
?>

Example (MySQLi Object-oriented)

 <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    echo "<table><tr><th>ID</th><th>Name</th></tr>";
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>".$row["id"]."</td><td>".$row["firstname"]." ".$row["lastname"]."</td></tr>";
    }
    echo "</table>";
} else {
    echo "0 results";
}
$conn->close();
?>

Example (PDO)

 <?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";

class TableRows extends RecursiveIteratorIterator {
    function __construct($it) {
        parent::__construct($it, self::LEAVES_ONLY);
    }

    function current() {
        return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
    }

    function beginChildren() {
        echo "<tr>";
    }

    function endChildren() {
        echo "</tr>" . "\n";
    }
}

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
        echo $v;
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>

These examples are from w3schools.

https://www.w3schools.com


问:
Find max value from input text file in java
Im trying to get the max number in a certain text file the user inputs. I also put it into separate methods. Heres what I have so far:

```<code>public static void FindMax(String file)throws IOException{
 int maximum = 0;
 Scanner fileScanner = new Scanner(new File(file)); {
            int big = fileScanner.nextInt();
            while (fileScanner.hasNextInt()) {
                int num = fileScanner.nextInt();
                if(num > big) {
                   maximum++;
                     System.out.println(num);;
                }
           }
  }
}
public static void main(String[] args)throws IOException{

    Scanner keyboard = new Scanner(System.in);
     String file;

      System.out.print("Enter file: ");
       file = keyboard.nextLine();

       FindMax(file);

}
</code>```

The output is printing all the content in the text file except the first value, instead of printing the maximum. For example if the text file is:

```<code>1
2
3
4
5
</code>```

It only prints 2,3,4, and 5 and I don't know why.How can I get the max value? Id appreciate any help/advice. Thanks in advance.

EDIT: All of you guys are saying similar solutions but when I try them, it just prints the same output. Im very confused.

答:
What you want to do is inside while loop:

```<code>if(num > big) {
    big = num;
}
</code>```

Then when you finish with while loop you just print big:

    System.out.println(big);

You don't need that maximum since you are not using it for anything, but if you should first fix syntax errors(wrong placed and missing brackets) or maybe you didnt copy code properly.

Body:
Im trying to get the max number in a certain text file the user inputs. I also put it into separate methods. Heres what I have so far:

public static void FindMax(String file)throws IOException{
 int maximum = 0;
 Scanner fileScanner = new Scanner(new File(file)); {
            int big = fileScanner.nextInt();
            while (fileScanner.hasNextInt()) {
                int num = fileScanner.nextInt();
                if(num > big) {
                   maximum++;
                     System.out.println(num);;
                }
           }
  }
}
public static void main(String[] args)throws IOException{

    Scanner keyboard = new Scanner(System.in);
     String file;

      System.out.print("Enter file: ");
       file = keyboard.nextLine();

       FindMax(file);

}

The output is printing all the content in the text file except the first value, instead of printing the maximum. For example if the text file is:

1
2
3
4
5

It only prints 2,3,4, and 5 and I don't know why.How can I get the max value? Id appreciate any help/advice. Thanks in advance.

EDIT: All of you guys are saying similar solutions but when I try them, it just prints the same output. Im very confused.

Body:
What you want to do is inside while loop:

if(num > big) {
    big = num;
}

Then when you finish with while loop you just print big:

    System.out.println(big);

You don't need that maximum since you are not using it for anything, but if you should first fix syntax errors(wrong placed and missing brackets) or maybe you didnt copy code properly.