问:
Drupal 8 break apart page.content not working
Trying to utilize fields in a template and break apart page.content

The {{ content.field_machine_name }} does not work in my particular content type.

Is there something I am missing here? I read the documentation:

https://www.drupal.org/docs/8/theming/twig/using-custom-content-types-and-fields-with-twig

From my understanding you should be able to use {{ content.whatever }} and it display that particular field.

答: I found the answer. I was looking in the wrong place.</p>


来源: stackexchange

问:
How to sum all n-th rows of arrays in array (numpy)?
Let's say I have the array:

```<code> import numpy as np
 a = np.array([[[1], [3], [5]], [[2], [8], [6]]]
</code>```

How can I sum all first rows together, all second rows together and so so? So, I the result I want is something like this

```<code> [3, 11, 11] or [[3], [11], [11]]
</code>```

It seems to be so simple but I can't find solution which doesn't require loops...

答:
I think what you're looking for is np.sum where you sum over the 0th axis.

```<code>import numpy as np
a = np.array([[[1], [3], [5]], [[2], [8], [6]]])
b = a.sum(0)
# b = array([[3],[11],[11]])
</code>```

Though your initial addition was off 1 + 2 = 3, 3 + 8 = 11, and 5 + 6 = 11 leaves us with 3, 11, 11

Alternatively, as NAN pointed out

```<code>np.sum(a, axis=(0,2))
# array([ 3, 11, 11])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Let's say I have the array:

 import numpy as np
 a = np.array([[[1], [3], [5]], [[2], [8], [6]]]

How can I sum all first rows together, all second rows together and so so? So, I the result I want is something like this

 [3, 11, 11] or [[3], [11], [11]]

It seems to be so simple but I can't find solution which doesn't require loops...

Body:
I think what you're looking for is np.sum where you sum over the 0th axis.

import numpy as np
a = np.array([[[1], [3], [5]], [[2], [8], [6]]])
b = a.sum(0)
# b = array([[3],[11],[11]])

Though your initial addition was off 1 + 2 = 3, 3 + 8 = 11, and 5 + 6 = 11 leaves us with 3, 11, 11

Alternatively, as NAN pointed out

np.sum(a, axis=(0,2))
# array([ 3, 11, 11])


问:
tm combine list of corpora
I have a list of URL for which i have fetched the webcontent, and included that into tm corpora:

```<code>library(tm)
library(XML)

link <- c(
"http://www.r-statistics.com/tag/hadley-wickham/",
"http://had.co.nz/",
"http://vita.had.co.nz/articles.html",
"http://blog.revolutionanalytics.com/2010/09/the-r-files-hadley-wickham.html",
"http://www.analyticstory.com/hadley-wickham/"
)

create.corpus <- function(url.name){
doc=htmlParse(url.name)
parag=xpathSApply(doc,'//p',xmlValue)
if (length(parag)==0){
  parag="empty"
}
cc=Corpus(VectorSource(parag))
meta(cc,"link")=url.name
return(cc)
}

link=catch$url
cc <- lapply(link, create.corpus)
</code>```

This gives me a "large list" of corpora, one for each URL.
Combining them one by one works:

```<code>x=cc[[1]]
y=cc[[2]]
z=c(x,y,recursive=T) # preserved metadata
x;y;z
# A corpus with 8 text documents
# A corpus with 2 text documents
# A corpus with 10 text documents
</code>```

But this becomes unfeasible for a list with a few thousand corpora.
So how can a list of corpora be merged into one corpus while maintaining the meta data?

答:
Your code does not work because catch is not defined, so I don't know exactly what that is supposed to do.

But now tm corpora can just be put into a vector to make one big corpora: https://www.rdocumentation.org/packages/tm/versions/0.7-1/topics/tm_combine

So maybe c(unlist(cc)) would work.  I have no way to test if that would work though because your code doesn't run.

Title: tm combine list of corpora

Body:
I have a list of URL for which i have fetched the webcontent, and included that into tm corpora:

library(tm)
library(XML)

link <- c(
"http://www.r-statistics.com/tag/hadley-wickham/",
"http://had.co.nz/",
"http://vita.had.co.nz/articles.html",
"http://blog.revolutionanalytics.com/2010/09/the-r-files-hadley-wickham.html",
"http://www.analyticstory.com/hadley-wickham/"
)

create.corpus <- function(url.name){
doc=htmlParse(url.name)
parag=xpathSApply(doc,'//p',xmlValue)
if (length(parag)==0){
  parag="empty"
}
cc=Corpus(VectorSource(parag))
meta(cc,"link")=url.name
return(cc)
}

link=catch$url
cc <- lapply(link, create.corpus)

This gives me a "large list" of corpora, one for each URL.
Combining them one by one works:

x=cc[[1]]
y=cc[[2]]
z=c(x,y,recursive=T) # preserved metadata
x;y;z
# A corpus with 8 text documents
# A corpus with 2 text documents
# A corpus with 10 text documents

But this becomes unfeasible for a list with a few thousand corpora.
So how can a list of corpora be merged into one corpus while maintaining the meta data?


问:
Vista 64-bit Development Caveats
I'm migrating my development workstation from 32-bit Vista to 64-bit Vista.

The production platform is 32-bit Windows Server and SQL Server 2008.

Does anyone know of any issues with migrating the code base?

EDIT:

the system consists of web forms, c# code, stored procedures.

there is also ajax.net, ssrs, ssis, and dynamic reports/graphs from dundas.

however, i think other users might appreciate any lessons learned or feedback in general regarding this move.

FINDINGS:

As of Jan 24, 2009

Checkpoint VPN does not support Vista 64 (actually it seems that very few do)

Cropper utility required special download and rebuild to work on Vista 64 (Cropper looks very nice, but it lacks scrollable window capture)

The lack of support for Vista 64 made it not worth while for me.  I wish someone would have mentioned the lack of VPN support, but there is currently no vpn vendor that supports 64 bit clients....  So be forwarned - as of 1/28/2009 - using Vista 64 is not a good option for those of us who need vpn.

答:
Don't use hard coded names for system folders.

(a bad idea anyway)

OwnerDisplayName: mson

ContentLicense: CC BY-SA 2.5

Title: Vista 64-bit Development Caveats

LastEditorDisplayName: mson

OwnerDisplayName: idstam


问:
Vinkla instagram in Laravel 5.5 and Show some Error
I am trying to integrate vinkla/instagram in Laravel 5.5.

I use php version is 7.0.

But it is showing some error. I tried the following steps:

1.Run composer require vinkla/instagram

2.Added the service provider to config/app.php

```<code>Vinkla\Instagram\InstagramServiceProvider::class
</code>```

3.Added to config/app.php in aliases

```<code>'Instagram' => Vinkla\Instagram\Facades\Instagram::class
</code>```

4.When I run some command (php artisan vendor:publish,composer dump-autoload,php artisan config:clear and php artisan cache:clear),it shows the following error:
enter image description here

```<code> Class 'Vinkla\Instagram\InstagramServiceProvider' not found.
</code>```

How can I solve it? Thanks.

答: Please note as of version 8.0.0 Public feed was removed Link</p>

Body:
I am trying to integrate vinkla/instagram in Laravel 5.5.

I use php version is 7.0.

But it is showing some error. I tried the following steps:

1.Run composer require vinkla/instagram

2.Added the service provider to config/app.php

Vinkla\Instagram\InstagramServiceProvider::class

3.Added to config/app.php in aliases

'Instagram' => Vinkla\Instagram\Facades\Instagram::class

4.When I run some command (php artisan vendor:publish,composer dump-autoload,php artisan config:clear and php artisan cache:clear),it shows the following error:
enter image description here

 Class 'Vinkla\Instagram\InstagramServiceProvider' not found.

How can I solve it? Thanks.


问:
Basic writing to a CSV file in python?
i was looking for help writing to a csv file in python 3. I have the code below but it only seems to write to the first line, whenever i run the code again it overwrites the first line. </p>

```<code>import csv

with open("scores1.csv", "w") as csvfile:
    fieldnames = ["score", "username","topic","difficulty",]
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    score = int(input("score" ))
    user = input("user: ")
    topic = input("topic: ")
    difficulty = input("difficulty: ")

    writer.writerow({"score": score, "username": user, "topic": topic, "difficulty": difficulty})

print ()

csvfile.close()
</code>```

答: writerow(), unsurprisingly writes a single row. So it needs to be enclosed in a for loop iterating over each record to be written to the file.

Title: Basic writing to a CSV file in python?

Body:
i was looking for help writing to a csv file in python 3. I have the code below but it only seems to write to the first line, whenever i run the code again it overwrites the first line.

import csv

with open("scores1.csv", "w") as csvfile:
    fieldnames = ["score", "username","topic","difficulty",]
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    score = int(input("score" ))
    user = input("user: ")
    topic = input("topic: ")
    difficulty = input("difficulty: ")

    writer.writerow({"score": score, "username": user, "topic": topic, "difficulty": difficulty})

print ()

csvfile.close()


问:
Install intl PHP extension OSX High Sierra
How can I install intl PHP extension in PHP 7.1.7, which is delivered with osx high sierra?</p>

答:
In addition to what L. Grolleau says (run brew install php71-intl), paste the int.so path to the /php.ini at the end of the file:

```<code>extension=/usr/local/Cellar/php71-intl/7.1.11_20/intl.so
</code>```

Body:
In addition to what L. Grolleau says (run brew install php71-intl), paste the int.so path to the /php.ini at the end of the file:

extension=/usr/local/Cellar/php71-intl/7.1.11_20/intl.so


问:
Why do I need to dispose of subscriptions after completion?
The Intro To RX book describes the return value on OnSubscribe as IDisposible and notes that subscriptions should be disposed of when OnError and OnCompleted are called.

An interesting thing to consider is that when a sequence completes or
  errors, you should still dispose of your subscription.

From Intro to RX: Lifetime Management, OnError and OnCompleted

Why is this?

For reference, this is the class I'm currently working on. I'm probably going to submit it to code review at some point.

```<code>using System;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Subjects;

/// <summary>
/// Provides a timeout mechanism that will not timeout if it is signalled often enough
/// </summary>
internal class TrafficTimeout
{
    private readonly Action onTimeout;
    private object signalLock = new object();
    private IObserver<Unit> signals;

    /// <summary>
    /// Initialises a new instance of the <see cref="TrafficTimeout"/> class.
    /// </summary>
    /// <param name="timeout">The duration to wait after receiving signals before timing out.</param>
    /// <param name="onTimeout">The <see cref="Action"/> to perform when the the timeout duration expires.</param>
    public TrafficTimeout(TimeSpan timeout, Action onTimeout)
    {
        // Subscribe to a throttled observable to trigger the expirey
        var messageQueue = new BehaviorSubject<Unit>(Unit.Default);
        IDisposable subscription = null;
        subscription = messageQueue.Throttle(timeout).Subscribe(
        p =>
        {
            messageQueue.OnCompleted();
            messageQueue.Dispose();
        });

        this.signals = messageQueue.AsObserver();
        this.onTimeout = onTimeout;
    }

    /// <summary>
    /// Signals that traffic has been received.
    /// </summary>
    public void Signal()
    {
        lock (this.signalLock)
        {
            this.signals.OnNext(Unit.Default);
        }
    }
}
</code>```

答:
Firstly, here's an example of the trouble you can run into:

```<code>void Main()
{
    Console.WriteLine(GC.GetTotalMemory(true));
    for (int i = 0; i < 1000; i++)
    {
        DumbSubscription();
        Console.WriteLine(GC.GetTotalMemory(true));
    }
    Console.WriteLine(GC.GetTotalMemory(true));
}

public void DumbSubscription()
{
    Observable.Interval(TimeSpan.FromMilliseconds(50))
        .Subscribe(i => {});
}
</code>```

You will see your memory usage go up forever. Active Rx subscriptions do not get garbage collected and this observable is infinite. Therefore, if you increase the loop limit, or add a delay, and you'll simply have more wasted memory: Nothing will help you except for disposing of those subscriptions.

However, let's say we change the definition of DumbSubscription to this:

```<code>public void DumbSubscription()
{
    Observable.Interval(TimeSpan.FromMilliseconds(50))
        .Take(1)
        .Subscribe(i => {});
}
</code>```

The .Take(1) addition means that the observable will complete after one interval, so it's no longer infinite. You'll see that your memory usage stabilizes: Subscriptions tend to properly dispose of themselves upon completion or exception.

However, that doesn't change the fact that, like any other IDisposable, it's a best practice to call Dispose (either manually or via using) to make sure resources are properly disposed of. Additionally, if you tweak your observable, you can easily run into the memory leak problem pointed out at the beginning.

Body:
The Intro To RX book describes the return value on OnSubscribe as IDisposible and notes that subscriptions should be disposed of when OnError and OnCompleted are called.

An interesting thing to consider is that when a sequence completes or
  errors, you should still dispose of your subscription.

From Intro to RX: Lifetime Management, OnError and OnCompleted

Why is this?

For reference, this is the class I'm currently working on. I'm probably going to submit it to code review at some point.

using System;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Subjects;

///
/// Provides a timeout mechanism that will not timeout if it is signalled often enough
///
internal class TrafficTimeout
{
    private readonly Action onTimeout;
    private object signalLock = new object();
    private IObserver<Unit> signals;

    ///
    /// Initialises a new instance of the <see cref="TrafficTimeout"/> class.
    ///
    /// <param name="timeout">The duration to wait after receiving signals before timing out.</param>
    /// <param name="onTimeout">The <see cref="Action"/> to perform when the the timeout duration expires.</param>
    public TrafficTimeout(TimeSpan timeout, Action onTimeout)
    {
        // Subscribe to a throttled observable to trigger the expirey
        var messageQueue = new BehaviorSubject<Unit>(Unit.Default);
        IDisposable subscription = null;
        subscription = messageQueue.Throttle(timeout).Subscribe(
        p =>
        {
            messageQueue.OnCompleted();
            messageQueue.Dispose();
        });

        this.signals = messageQueue.AsObserver();
        this.onTimeout = onTimeout;
    }

    ///
    /// Signals that traffic has been received.
    ///
    public void Signal()
    {
        lock (this.signalLock)
        {
            this.signals.OnNext(Unit.Default);
        }
    }
}

Body:
Firstly, here's an example of the trouble you can run into:

void Main()
{
    Console.WriteLine(GC.GetTotalMemory(true));
    for (int i = 0; i < 1000; i++)
    {
        DumbSubscription();
        Console.WriteLine(GC.GetTotalMemory(true));
    }
    Console.WriteLine(GC.GetTotalMemory(true));
}

public void DumbSubscription()
{
    Observable.Interval(TimeSpan.FromMilliseconds(50))
        .Subscribe(i => {});
}

You will see your memory usage go up forever. Active Rx subscriptions do not get garbage collected and this observable is infinite. Therefore, if you increase the loop limit, or add a delay, and you'll simply have more wasted memory: Nothing will help you except for disposing of those subscriptions.

However, let's say we change the definition of DumbSubscription to this:

public void DumbSubscription()
{
    Observable.Interval(TimeSpan.FromMilliseconds(50))
        .Take(1)
        .Subscribe(i => {});
}

The .Take(1) addition means that the observable will complete after one interval, so it's no longer infinite. You'll see that your memory usage stabilizes: Subscriptions tend to properly dispose of themselves upon completion or exception.

However, that doesn't change the fact that, like any other IDisposable, it's a best practice to call Dispose (either manually or via using) to make sure resources are properly disposed of. Additionally, if you tweak your observable, you can easily run into the memory leak problem pointed out at the beginning.


问:
SQL query to include time segments with no counts
I am working in SQL Server 2014. I have table that records 'counts' and a timestamp of the count. The counting period is a two hour block that can start at any quarter hour. In the example data below, the count starts at 16:00 and goes through 18:00. The counting block could have started at 01:30 and stopped at 03:30.

```<code>Timestamp   Count
16:00:31    1
16:00:42    1
16:16:04    1
16:16:06    1
16:45:10    1
16:45:31    1
16:45:32    1
17:16:45    1
17:16:52    1
17:16:53    1
17:33:19    1
17:34:01    1
17:45:03    1
17:46:08    1
</code>```

I have a query which sums the counts over 15 minute intervals within the two hour block:

```<code>SELECT
    FORMAT(DATEPART(HOUR, [Timestamp]), '0#') + ':' + FORMAT(DATEPART(MINUTE, [TimeStamp]) / 15 * 15, '0#') AS QtrHrBeg
    , COUNT(*) AS CountTotal
FROM
    [Sandbox].[trippetoe].[SURVEYCOUNTS]
GROUP BY
    DATEPART(HOUR, [TIMESTAMP])
    , (DATEPART(MINUTE, [TIMESTAMP]) / 15 * 15)
</code>```

which results in this:

```<code>QtrHrBeg    Count
16:00   2
16:15   2
16:45   3
17:15   3
17:30   2
17:45   2
</code>```

I'd like to include 15 minute intervals where there are no counts - in this example the quarter hours beginning at 16:30 and 17:00, like below:

```<code>QtrHrBeg    Count
16:00   2
16:15   2
16:30   0
16:45   3
17:00   0
17:15   3
17:30   2
17:45   2
</code>```

How can i do that?

答:
You can use the following

Find the minimum date and the maximum date in the data you are going to work on , then round these two values to the nearest 15

Split the segment into 15 minutes intervals

Left join your data with the result came out and apply group by the StartTime and I used format in order to show the time formatting only

The benefit of this approach is that it works on specific interval and will not take any time interval outside of your data ranges.

```<code>with initial as(
  select dateadd(minute, datediff(minute,0,min([Time])) / 15 * 15, 0) as MinTime,
         dateadd(minute, datediff(minute,0,max([Time])) / 15 * 15, 0) as MaxTime
  from data
 ), times as(
   select StartTime = MinTime,
          EndTime =dateadd(millisecond,-1,dateadd(minute,15,MinTime)),
          MaxTime
   from initial
   union all
   select dateadd(millisecond,1,EndTime),
          dateadd(minute,15,EndTime),
          MaxTime
   from times
   where EndTime<MaxTime
 )

 select format(t.StartTime,'HH:mm') as [Time],isnull(sum(d.[Count]),0) as [Count]
 from times t
 left join data d on d.[Time] between t.StartTime and t.EndTime
 group by t.StartTime
</code>```

Here is the output

```<code>Time    Count
16:00   2
16:15   2
16:30   0
16:45   3
17:00   0
17:15   3
17:30   2
17:45   2
</code>```

Here a working demo

Hope this will help you

EDIT

I changed the usage of second to millisecond based on the comment from @HABO, it will solve the case where there is some times like 16:59:59

Body:
I am working in SQL Server 2014. I have table that records 'counts' and a timestamp of the count. The counting period is a two hour block that can start at any quarter hour. In the example data below, the count starts at 16:00 and goes through 18:00. The counting block could have started at 01:30 and stopped at 03:30.

Timestamp   Count
16:00:31    1
16:00:42    1
16:16:04    1
16:16:06    1
16:45:10    1
16:45:31    1
16:45:32    1
17:16:45    1
17:16:52    1
17:16:53    1
17:33:19    1
17:34:01    1
17:45:03    1
17:46:08    1

I have a query which sums the counts over 15 minute intervals within the two hour block:

SELECT
    FORMAT(DATEPART(HOUR, [Timestamp]), '0#') + ':' + FORMAT(DATEPART(MINUTE, [TimeStamp]) / 15 * 15, '0#') AS QtrHrBeg
    , COUNT(*) AS CountTotal
FROM
    [Sandbox].[trippetoe].[SURVEYCOUNTS]
GROUP BY
    DATEPART(HOUR, [TIMESTAMP])
    , (DATEPART(MINUTE, [TIMESTAMP]) / 15 * 15)

which results in this:

QtrHrBeg    Count
16:00   2
16:15   2
16:45   3
17:15   3
17:30   2
17:45   2

I'd like to include 15 minute intervals where there are no counts - in this example the quarter hours beginning at 16:30 and 17:00, like below:

QtrHrBeg    Count
16:00   2
16:15   2
16:30   0
16:45   3
17:00   0
17:15   3
17:30   2
17:45   2

How can i do that?

Body:
You can use the following

Find the minimum date and the maximum date in the data you are going to work on , then round these two values to the nearest 15

Split the segment into 15 minutes intervals

Left join your data with the result came out and apply group by the StartTime and I used format in order to show the time formatting only

The benefit of this approach is that it works on specific interval and will not take any time interval outside of your data ranges.

with initial as(
  select dateadd(minute, datediff(minute,0,min([Time])) / 15 * 15, 0) as MinTime,
         dateadd(minute, datediff(minute,0,max([Time])) / 15 * 15, 0) as MaxTime
  from data
 ), times as(
   select StartTime = MinTime,
          EndTime =dateadd(millisecond,-1,dateadd(minute,15,MinTime)),
          MaxTime
   from initial
   union all
   select dateadd(millisecond,1,EndTime),
          dateadd(minute,15,EndTime),
          MaxTime
   from times
   where EndTime<MaxTime
 )

 select format(t.StartTime,'HH:mm') as [Time],isnull(sum(d.[Count]),0) as [Count]
 from times t
 left join data d on d.[Time] between t.StartTime and t.EndTime
 group by t.StartTime

Here is the output

Time    Count
16:00   2
16:15   2
16:30   0
16:45   3
17:00   0
17:15   3
17:30   2
17:45   2

Here a working demo

Hope this will help you

EDIT

I changed the usage of second to millisecond based on the comment from @HABO, it will solve the case where there is some times like 16:59:59


问:
How to limit the amount of characters a javafx textfield
I´m using a FXML to set my form, but I need to set the limit of characters in textfields. How can I made this ?</p>

答:
This is a very simple solution that seems to work for me.</p>

```<code>textfield.setOnKeyTyped(event ->{
        int maxCharacters = 5;
        if(tfInput.getText().length() > maxCharacters) event.consume();
    });
</code>```

Body:
This is a very simple solution that seems to work for me.

textfield.setOnKeyTyped(event ->{
        int maxCharacters = 5;
        if(tfInput.getText().length() > maxCharacters) event.consume();
    });


问:
Ifelse in R with multiple categorical conditions
I have a data set, dt.train2 with  1500 different observations and 130 variables. One of them is languages and it can be english, french, arabic...

I want to create a ifelse string that gives attributes 1 for english, 2 for french, 3 for spanish and 0 for anything else. I have no idea how to do it.

```<code>dt.train2[, language_string := ifelse(language == "english",
                                      1,
                                      ifelse(language == "french",
                                             2,
                                             ifelse(language == "spanish",3)]
</code>```

I'm using this to run linear model about sales.

答:
I agree with the comments that if this is for a linear model, it is a bad way to go about it. If you insist on languages as predictors, it is better practice to make a series of dummy variables. In this case, you would add 3 predictors ("english", "french", "arabic") which all take values of 0 or 1.

Either way, here is my dplyr take on the problem, which utilizes a CASE WHEN SQL-style syntax and is easier to read.

```<code>require(tidyverse)
dt.train2 <- dt.train2 %>%
          mutate(language_string = case_when(language == "english" ~ 1,
                                             language == "french" ~ 2,
                                             language == "spanish" ~ 3,
                                             TRUE ~ 0))
</code>```

Body:
I have a data set, dt.train2 with  1500 different observations and 130 variables. One of them is languages and it can be english, french, arabic...

I want to create a ifelse string that gives attributes 1 for english, 2 for french, 3 for spanish and 0 for anything else. I have no idea how to do it.

dt.train2[, language_string := ifelse(language == "english",
                                      1,
                                      ifelse(language == "french",
                                             2,
                                             ifelse(language == "spanish",3)]

I'm using this to run linear model about sales.

Body:
I agree with the comments that if this is for a linear model, it is a bad way to go about it. If you insist on languages as predictors, it is better practice to make a series of dummy variables. In this case, you would add 3 predictors ("english", "french", "arabic") which all take values of 0 or 1.

Either way, here is my dplyr take on the problem, which utilizes a CASE WHEN SQL-style syntax and is easier to read.

require(tidyverse)
dt.train2 <- dt.train2 %>%
          mutate(language_string = case_when(language == "english" ~ 1,
                                             language == "french" ~ 2,
                                             language == "spanish" ~ 3,
                                             TRUE ~ 0))


问:
Breaking change to get filename without extension in Swift2
In Swift1, we can get file short name without extension by following code:

```<code>self.name = pathFilename.lastPathComponent.stringByDeletingPathExtension
</code>```

While I updated to Swift 2, this API is not available anymore. With the warning message, I have to use NSURL. So the new code will be:

```<code>var filename = NSURL(fileURLWithPath: str).lastPathComponent
filename = NSURL(fileURLWithPath: filename!).URLByDeletingPathExtension?.relativePath
</code>```

It is too complex API breaking change. Is there a better way that could make it simpler?

答:
Swift 4

```<code>let url = URL(string: "https://example.com/myFile.html")
if let fileName = url?.deletingPathExtension().lastPathComponent {
    // fileName: myFile
    self.name = fileName
}
</code>```

Body:
In Swift1, we can get file short name without extension by following code:

self.name = pathFilename.lastPathComponent.stringByDeletingPathExtension

While I updated to Swift 2, this API is not available anymore. With the warning message, I have to use NSURL. So the new code will be:

var filename = NSURL(fileURLWithPath: str).lastPathComponent
filename = NSURL(fileURLWithPath: filename!).URLByDeletingPathExtension?.relativePath

It is too complex API breaking change. Is there a better way that could make it simpler?

Body:
Swift 4

let url = URL(string: "https://example.com/myFile.html")
if let fileName = url?.deletingPathExtension().lastPathComponent {
    // fileName: myFile
    self.name = fileName
}


问:
R predict factor variables
I try to do some prediction in R . I loaded & cleaned the data, fit a model and did a prediction which looks pretty good. My problem now is that my prediction gives me a percentage of probability of the occurence of e certain factor instead of the factor itself:

I have a dataset on how well people perform some exercise. This performance is messured in A-D ( which is a factor-variable in my dataset). When I do the prediction I get this output:

but I want to have it like that:

[ B    A    E    A    A    C    D    A    A    A    C ]

How would I do that? This is my code:

```<code>modFitA1 <- rpart(classe ~ ., data=PML_Train_red, method="class")
Predictn<-predict(modFitA1, newdata= PML_Test_red)
Predictn
</code>```

答:
Even though you put method="class" in your model statement,  you need to add type="class" to your predict statement.

```<code>Predictn<-predict(modFitA1, newdata= PML_Test_red, type="class")
</code>```

Title: R predict factor variables

Body:
I try to do some prediction in R . I loaded & cleaned the data, fit a model and did a prediction which looks pretty good. My problem now is that my prediction gives me a percentage of probability of the occurence of e certain factor instead of the factor itself:

I have a dataset on how well people perform some exercise. This performance is messured in A-D ( which is a factor-variable in my dataset). When I do the prediction I get this output:

but I want to have it like that:

[ B    A    E    A    A    C    D    A    A    A    C ]

How would I do that? This is my code:

modFitA1 <- rpart(classe ~ ., data=PML_Train_red, method="class")
Predictn<-predict(modFitA1, newdata= PML_Test_red)
Predictn

Body:
Even though you put method="class" in your model statement,  you need to add type="class" to your predict statement.

Predictn<-predict(modFitA1, newdata= PML_Test_red, type="class")


问:
set scalar fixed length string attribute in hdf5
I need to add a few string scalar attribute to a HDF file, here is my python:

```<code>hdf = h5py.File('data.hdf', 'r+')
hdf['program'].attrs['filename'] = '.\\cover.tif'
hdf['program'].attrs['gis'] = 'cover'
hdf.close()
</code>```

this works in that it indeed added the two attributes, but when I examine them in HDFViewer, they have the type: String, length=variable, I need to have the actual length in the type, for example: String, length=5 for 'cover', how do I do that?

答:
Have to use the attrs.create method as shown below:

```<code>hdf['program'].attrs.create('gis', 'cover', None, dtype='<S5')
</code>```

arguments are:

```<code>name: 'gis'
data: 'cover'
shape: None
dtype (Numpy dtype): '<S5'
</code>```

that last 5 in the dtype argument is the length of the scalar string. This way, the attribute's type will be String, length=5

Body:
I need to add a few string scalar attribute to a HDF file, here is my python:

hdf = h5py.File('data.hdf', 'r+')
hdf['program'].attrs['filename'] = '.\\cover.tif'
hdf['program'].attrs['gis'] = 'cover'
hdf.close()

this works in that it indeed added the two attributes, but when I examine them in HDFViewer, they have the type: String, length=variable, I need to have the actual length in the type, for example: String, length=5 for 'cover', how do I do that?

Body:
Have to use the attrs.create method as shown below:

hdf['program'].attrs.create('gis', 'cover', None, dtype='<S5')

arguments are:

name: 'gis'
data: 'cover'
shape: None
dtype (Numpy dtype): '<S5'

that last 5 in the dtype argument is the length of the scalar string. This way, the attribute's type will be String, length=5


问:
Reading Data from two PHP pages into the third Page
I'm not able to combine the data from two pages. I'm only able to show data from one page. I tried searching for an explanation of my problem on google but I could not find it.
I get an "Undefined index" error as you can see [![in this screenshot][1]][1].
Could not put just code over here because it keeps telling me that I need to use spacing with ctrl + K and im newbie in all this things so please forgive me..

```<code><!DOCTYPE html>
<html>
<head>
<title>TEST</title>
</head>

<body>
 <form action = "page2.php" method = "POST">
                            <select list="Country" placeholder="Country" name="country" required class="form-control" style="max-width:250px; margin-top:50px;" id="Country">
                                <option >Bosnia & Herzegovina</option>
                                <option >Croatia</option>
                                <option >Serbia</option>
                                <option >England</option>
                                <option >Germany</option>
                                <option >Austria</option>
                                <option >Belgium</option>
                                <option >Switzerland</option>
                                <option >Italy</option>
                                <option >Romania</option>
                                <option >France</option>
                                <option >Montenegro</option>
                                <option >Slovenia</option>
                            </select>

            <input type="email" name="email" id="email" placeholder="Your email address" required class="form-control" style="max-width:250px;" />

            <input type="password" name="password" id="creapass" placeholder="Create your password" required  class="form-control" style="max-width:250px;" />

            <input type="password" name="password2" id="password" placeholder="Confirm your password" required  class="form-control" style="max-width:250px;" />

            <a href="page2.php"> <input type="button" value="Next" class="btn btn-primary" style="width:150px;"></a>

            </form>

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

Second Page

```<code><!DOCTYPE html>
<html>
<head>
<title>test2</title>

</head>

<body>
<form action = "finalpage.php" method = "POST">

    <!-- Values from First Step -->

<input type="hidden" name="country" value="<?php $_POST['country'] ?>">

<input type="hidden" name="email" value="<?php $_POST['email'] ?>">

<input type="hidden" name="password" value="<?php $_POST['password'] ?>">
<input type="hidden" name="password" value="<?php $_POST['password2'] ?>">

<!-- End of Values from First Step -->

<?php
echo "Country:" .$_POST["country"]."</br>";
echo "Email:".$_POST["email"]."</br>";
echo "Password:".$_POST["password"]."</br>";
echo "Password2:".$_POST["password2"]."</br>";
?>

                                <input type="text" name="first" class="form-control" placeholder="First name" required style="max-width:250px;" >

                                <input type="text" name="last" class="form-control" placeholder="Last name" required style="max-width:250px;" />

                                <input type="date" name="date" class="dateb" id="dateOfBirth" required  />

                                        <select list="Country" placeholder="Country" name="country2" required class="form-control" style="max-width:250px; " id="Country">
                                            <option >Bosnian</option>
                                            <option >Croat</option>
                                            <option >Serb</option>
                                            <option >English</option>
                                            <option >German</option>
                                            <option >Austrian</option>
                                            <option >Belgian</option>
                                            <option >Swiss</option>
                                            <option >Italian</option>
                                            <option >Romanian</option>
                                            <option >French</option>
                                            <option >Montenegrin</option>
                                            <option >Slovenian</option>
                                        </select>

                                <input type="text" class="form-control" name="street1" placeholder="Street address 1" required style="max-width:250px;" />

                                <input type="text" class="form-control" name="street2" placeholder="Street address 2 (Optional)" style="max-width:250px;" />

                                <input type="text" class="form-control" name="city" placeholder="City" required style="max-width:250px;" />

                                <input type="text" class="form-control" name="region" placeholder="Province/Region" required style="max-width:250px;" />

                                <input type="text" class="form-control" name="postal" placeholder="Postal code" required style="max-width:250px;" />

                                <input type="tel" class="form-control" name="phone" placeholder="Phone number" required style="max-width:250px;" />

                                <input type="checkbox" name="terms" > I have read and agree to the Terms and WBC's User Agreement.

                                <a href="LinkCard.html"><input type="Submit" name="insert" value="Continue" class="btn btn-primary btn-lg"></a>

            </form>

</body>

</html>
</code>```

Final Step.

```<code><html>
<head>
<title>get data from another page</title>
</head>
<body>
<?php
echo "Country:" .$_POST["country"]."</br>";
echo "Email:".$_POST["email"]."</br>";
echo "Password:".$_POST["password"]."</br>";
echo "Password2:".$_POST["password2"]."</br>";

echo "First name:" .$_POST["first"]."</br>";
echo "Last name:".$_POST["last"]."</br>";
echo "Date:".$_POST["date"]."</br>";
echo "Country2:".$_POST["country2"]."</br>";
echo "Street1:" .$_POST["street1"]."</br>";
echo "Street2:".$_POST["street2"]."</br>";
echo "City:".$_POST["city"]."</br>";
echo "Region:".$_POST["region"]."</br>";
echo "Postal code:" .$_POST["postal"]."</br>";
echo "Phone number:".$_POST["phone"]."</br>";
?>
</body>
</html>
</code>```

答:
I am not copying the entire code of yours as it is not required. Below is the logic you have to follow.

In the first step, i.e. your first form (I prefer using PHP format as it allows you to use PHP functions, if required), put your second PHP in the form's action.

```<code><form action = "step_2.php" method = "POST">
</code>```

Now in your step_2.php, you have to add the below in your form.

```<code><!-- Values from First Step -->

<input type="country" name="country" value="<?php echo $_POST['country'] ?>">

<input type="hidden" name="email" value="<?php echo $_POST['email'] ?>">

<input type="hidden" name="password" value="<?php echo $_POST['password'] ?>">

<!-- End of Values from First Step -->
</code>```

Above code will add the values posted from the first step into your second step form. Now you can simply fetch these values in the final step. To do this, add your final step PHP in your Action of this form.

```<code><form action = "final_step.php" method = "POST">
</code>```

In your final_step.php, you can normally get the values by $_POST.

Body:
I'm not able to combine the data from two pages. I'm only able to show data from one page. I tried searching for an explanation of my problem on google but I could not find it.
I get an "Undefined index" error as you can see [![in this screenshot][1]][1].
Could not put just code over here because it keeps telling me that I need to use spacing with ctrl + K and im newbie in all this things so please forgive me..

<!DOCTYPE html>

<title>TEST</title>

 <form action = "page2.php" method = "POST">
                            <select list="Country" placeholder="Country" name="country" required class="form-control" style="max-width:250px; margin-top:50px;" id="Country">
                                <option >Bosnia & Herzegovina</option>
                                <option >Croatia</option>
                                <option >Serbia</option>
                                <option >England</option>
                                <option >Germany</option>
                                <option >Austria</option>
                                <option >Belgium</option>
                                <option >Switzerland</option>
                                <option >Italy</option>
                                <option >Romania</option>
                                <option >France</option>
                                <option >Montenegro</option>
                                <option >Slovenia</option>
                            </select>

            <input type="email" name="email" id="email" placeholder="Your email address" required class="form-control" style="max-width:250px;" />

            <input type="password" name="password" id="creapass" placeholder="Create your password" required  class="form-control" style="max-width:250px;" />

            <input type="password" name="password2" id="password" placeholder="Confirm your password" required  class="form-control" style="max-width:250px;" />

             <input type="button" value="Next" class="btn btn-primary" style="width:150px;">

            </form>

Second Page

<!DOCTYPE html>

<title>test2</title>

<form action = "finalpage.php" method = "POST">

<input type="hidden" name="country" value="<?php $_POST['country'] ?>">

<input type="hidden" name="email" value="<?php $_POST['email'] ?>">

<input type="hidden" name="password" value="<?php $_POST['password'] ?>">
<input type="hidden" name="password" value="<?php $_POST['password2'] ?>">

<?php
echo "Country:" .$_POST["country"]."
";
echo "Email:".$_POST["email"]."
";
echo "Password:".$_POST["password"]."
";
echo "Password2:".$_POST["password2"]."
";
?>

                                <input type="text" name="first" class="form-control" placeholder="First name" required style="max-width:250px;" >

                                <input type="text" name="last" class="form-control" placeholder="Last name" required style="max-width:250px;" />

                                <input type="date" name="date" class="dateb" id="dateOfBirth" required  />

                                        <select list="Country" placeholder="Country" name="country2" required class="form-control" style="max-width:250px; " id="Country">
                                            <option >Bosnian</option>
                                            <option >Croat</option>
                                            <option >Serb</option>
                                            <option >English</option>
                                            <option >German</option>
                                            <option >Austrian</option>
                                            <option >Belgian</option>
                                            <option >Swiss</option>
                                            <option >Italian</option>
                                            <option >Romanian</option>
                                            <option >French</option>
                                            <option >Montenegrin</option>
                                            <option >Slovenian</option>
                                        </select>

                                <input type="text" class="form-control" name="street1" placeholder="Street address 1" required style="max-width:250px;" />

                                <input type="text" class="form-control" name="street2" placeholder="Street address 2 (Optional)" style="max-width:250px;" />

                                <input type="text" class="form-control" name="city" placeholder="City" required style="max-width:250px;" />

                                <input type="text" class="form-control" name="region" placeholder="Province/Region" required style="max-width:250px;" />

                                <input type="text" class="form-control" name="postal" placeholder="Postal code" required style="max-width:250px;" />

                                <input type="tel" class="form-control" name="phone" placeholder="Phone number" required style="max-width:250px;" />

                                <input type="checkbox" name="terms" > I have read and agree to the Terms and WBC's User Agreement.

                                <input type="Submit" name="insert" value="Continue" class="btn btn-primary btn-lg">

            </form>

Final Step.

<title>get data from another page</title>

<?php
echo "Country:" .$_POST["country"]."
";
echo "Email:".$_POST["email"]."
";
echo "Password:".$_POST["password"]."
";
echo "Password2:".$_POST["password2"]."
";

echo "First name:" .$_POST["first"]."
";
echo "Last name:".$_POST["last"]."
";
echo "Date:".$_POST["date"]."
";
echo "Country2:".$_POST["country2"]."
";
echo "Street1:" .$_POST["street1"]."
";
echo "Street2:".$_POST["street2"]."
";
echo "City:".$_POST["city"]."
";
echo "Region:".$_POST["region"]."
";
echo "Postal code:" .$_POST["postal"]."
";
echo "Phone number:".$_POST["phone"]."
";
?>

Body:
I am not copying the entire code of yours as it is not required. Below is the logic you have to follow.

In the first step, i.e. your first form (I prefer using PHP format as it allows you to use PHP functions, if required), put your second PHP in the form's action.

<form action = "step_2.php" method = "POST">

Now in your step_2.php, you have to add the below in your form.

<!-- Values from First Step -->

<input type="country" name="country" value="<?php echo $_POST['country'] ?>">

<input type="hidden" name="email" value="<?php echo $_POST['email'] ?>">

<input type="hidden" name="password" value="<?php echo $_POST['password'] ?>">

<!-- End of Values from First Step -->

Above code will add the values posted from the first step into your second step form. Now you can simply fetch these values in the final step. To do this, add your final step PHP in your Action of this form.

<form action = "final_step.php" method = "POST">

In your final_step.php, you can normally get the values by $_POST.


问:
In javascript, when to use object literal and when to use array?
Here's a sample. My concern is both seem to do the job. which of them to prefer?

```<code>var fooArr = [{ "bar": {"blah": 9 } }];

for(var i in fooArr) {
    var value = fooArr[i].bar.blah;
console.log(value); //checking in firebug console
}

var fooObj = { "bar": {"blah": 9 } };
for(var i in fooObj) {
    var value = fooObj[i].blah;
console.log(value); //checking in firebug console
}
</code>```

Also, the following seems to be not valid, Any way of avoiding array notation.

```<code>var fooObj1 = {
    { "bar": { "blah": 9 } },
    { "bar": { "blah": 4 } },
    { "bar": { "blah":12} }
};
</code>```

So I had to modify the above code to something like below which works. Is it too too bad to be too much sticky with Object literals

```<code>var fooObj1 = {
    1:{ "bar": { "blah": 9 } },
    2:{ "bar": { "blah": 4 } },
    3:{ "bar": { "blah":12} }
};
</code>```

Thanks again and in advance to those who help me with the query.

答:
Use array if you need lists and use objects if you need properties.

In the above case, I would prefer the latter one.

Aside from that, never use for in on an array (it is extremely slow and defeats the purpose) and always use hasOwnProperty when iterating over an object's properties.

Body:
Here's a sample. My concern is both seem to do the job. which of them to prefer?

var fooArr = [{ "bar": {"blah": 9 } }];

for(var i in fooArr) {
    var value = fooArr[i].bar.blah;
console.log(value); //checking in firebug console
}

var fooObj = { "bar": {"blah": 9 } };
for(var i in fooObj) {
    var value = fooObj[i].blah;
console.log(value); //checking in firebug console
}

Also, the following seems to be not valid, Any way of avoiding array notation.

var fooObj1 = {
    { "bar": { "blah": 9 } },
    { "bar": { "blah": 4 } },
    { "bar": { "blah":12} }
};

So I had to modify the above code to something like below which works. Is it too too bad to be too much sticky with Object literals

var fooObj1 = {
    1:{ "bar": { "blah": 9 } },
    2:{ "bar": { "blah": 4 } },
    3:{ "bar": { "blah":12} }
};

Thanks again and in advance to those who help me with the query.


问:
Is it possible to give Highcharts, pie chart, an array of images instead of colors?
I have a pie chart with some colors in it. Though I also want to load image patterns as well.

Here's how I have it:

```<code> plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: false
                },
                showInLegend: true,
                size: 200,
                startAngle: 30,
                colors: [
                    {
                        pattern: '../Images/Food_Bolus_Pattern.gif',
                        width: 10,
                        height: 10
                    },
                    '#9D4EFF',
                    '#004B66',
                    {
                        pattern: '../Images/Quick_Bolus_Pattern.gif',
                        width: 10,
                        height: 10
                    },
                    '#CB9A66'
                ]
            }
        }
</code>```

Here's a fiddle as well! As you can see the images do not render on the pie chart. Is this possible? How can I make this possible? http://jsfiddle.net/2n36syny/

答:
I think I've discovered the issue I'm having. Wergeld's comment has helped alot.

What was needed is a highcharts plugin. View this fiddle to see the pattern pluging loaded up to let images be viewed.

```<code><script src="https://highcharts.github.io/pattern-fill/pattern-fill.js"></script>
</code>```

Body:
I have a pie chart with some colors in it. Though I also want to load image patterns as well.

Here's how I have it:

 plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: false
                },
                showInLegend: true,
                size: 200,
                startAngle: 30,
                colors: [
                    {
                        pattern: '../Images/Food_Bolus_Pattern.gif',
                        width: 10,
                        height: 10
                    },
                    '#9D4EFF',
                    '#004B66',
                    {
                        pattern: '../Images/Quick_Bolus_Pattern.gif',
                        width: 10,
                        height: 10
                    },
                    '#CB9A66'
                ]
            }
        }

Here's a fiddle as well! As you can see the images do not render on the pie chart. Is this possible? How can I make this possible? http://jsfiddle.net/2n36syny/

Body:
I think I've discovered the issue I'm having. Wergeld's comment has helped alot.

What was needed is a highcharts plugin. View this fiddle to see the pattern pluging loaded up to let images be viewed.

<script src="https://highcharts.github.io/pattern-fill/pattern-fill.js"></script>


问:
Angular Modal issue
I am trying to implement a modal from
https://plnkr.co/edit/VSOzZ8AJz61az9TANGsp?p=preview

However, I am trying to put the modal into a component instead of  directive as shown in the plunker above. I rant into one error ($.confirm)

```<code>import { Component, Output, HostListener, EventEmitter, Directive, ElementRef, NgModule,Input } from '@angular/core';

import { Overlay } from 'ngx-modialog';
import { Modal } from 'ngx-modialog/plugins/bootstrap';

@Component({
    selector: 'modal',
    moduleId: module.id,
    templateUrl: 'modal.component.html'

})
export class ModalComponent {
    closeResult: string;

    name: string;
    constructor(public modal: Modal) {
        this.name = 'Angular version'
    }

    @Output('confirm-click') click: any = new EventEmitter();

    @HostListener('click', ['$event']) clicked(e) {
        $.confirm({
            buttons: {
                confirm: () => this.click.emit(),
                cancel: () => { }
            }
        });
    }

}
</code>```

error:  Cannot find name '$'.

************************************UPDATE**************************************

I just ended up using bootstrap Modal , which works and easy to implement
modal.html

```<code><div>

    <span class="fa fa-trash-o"  data-toggle="modal" data-target="#myModal">

    </span>
    <div class="modal fade" id="myModal" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">

                    <button type="button" class="close" data-dismiss="modal">×</button>
                    <h4 class="modal-title">Confirm</h4>
                </div>
                <div class="modal-body">
                    <p>Delete this record?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-dismiss="modal" (click)="onOk()">OK</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

                </div>
            </div>
            <div>

            </div>
        </div>
    </div>
</div>
</code>```

Modal.ts

```<code>     import { Component, Output, HostListener, EventEmitter, Directive, ElementRef, NgModule,Input } from '@angular/core';

import { Overlay } from 'ngx-modialog';
import { Modal } from 'ngx-modialog/plugins/bootstrap';

declare const jQuery: {
    confirm: Function
};

@Component({
    selector: 'modal',
    moduleId: module.id,
    templateUrl: 'modal.component.html'

})
export class ModalComponent {
    @Output() open: EventEmitter<any> = new EventEmitter();

    onOk() {
        console.log("OK");
        this.open.emit('yes');
    }
    onDelete() {

        console.log("Cancel");
    }

}
</code>```

Title: Angular Modal issue

Body:
I am trying to implement a modal from
https://plnkr.co/edit/VSOzZ8AJz61az9TANGsp?p=preview

However, I am trying to put the modal into a component instead of  directive as shown in the plunker above. I rant into one error ($.confirm)

import { Component, Output, HostListener, EventEmitter, Directive, ElementRef, NgModule,Input } from '@angular/core';

import { Overlay } from 'ngx-modialog';
import { Modal } from 'ngx-modialog/plugins/bootstrap';

@Component({
    selector: 'modal',
    moduleId: module.id,
    templateUrl: 'modal.component.html'

})
export class ModalComponent {
    closeResult: string;

    name: string;
    constructor(public modal: Modal) {
        this.name = 'Angular version'
    }

    @Output('confirm-click') click: any = new EventEmitter();

    @HostListener('click', ['$event']) clicked(e) {
        $.confirm({
            buttons: {
                confirm: () => this.click.emit(),
                cancel: () => { }
            }
        });
    }

}

error:  Cannot find name '$'.

************************************UPDATE**************************************

I just ended up using bootstrap Modal , which works and easy to implement
modal.html

                    <button type="button" class="close" data-dismiss="modal">×</button>

Confirm

Delete this record?

                    <button type="button" class="btn btn-primary" data-dismiss="modal" (click)="onOk()">OK</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

Modal.ts

     import { Component, Output, HostListener, EventEmitter, Directive, ElementRef, NgModule,Input } from '@angular/core';

import { Overlay } from 'ngx-modialog';
import { Modal } from 'ngx-modialog/plugins/bootstrap';

declare const jQuery: {
    confirm: Function
};

@Component({
    selector: 'modal',
    moduleId: module.id,
    templateUrl: 'modal.component.html'

})
export class ModalComponent {
    @Output() open: EventEmitter<any> = new EventEmitter();

    onOk() {
        console.log("OK");
        this.open.emit('yes');
    }
    onDelete() {

        console.log("Cancel");
    }

}

Body:
I just ended up using bootstrap Modal , which works and easy to implement
modal.html

<div>

    <span class="fa fa-trash-o"  data-toggle="modal" data-target="#myModal">

    </span>
    <div class="modal fade" id="myModal" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">

                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Confirm</h4>
                </div>
                <div class="modal-body">
                    <p>Delete this record?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-dismiss="modal" (click)="onOk()">OK</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

                </div>
            </div>
            <div>

            </div>
        </div>
    </div>
</div>

Modal.ts

     import { Component, Output, HostListener, EventEmitter, Directive, ElementRef, NgModule,Input } from '@angular/core';

import { Overlay } from 'ngx-modialog';
import { Modal } from 'ngx-modialog/plugins/bootstrap';

declare const jQuery: {
    confirm: Function
};

@Component({
    selector: 'modal',
    moduleId: module.id,
    templateUrl: 'modal.component.html'

})
export class ModalComponent {
    @Output() open: EventEmitter<any> = new EventEmitter();

    onOk() {
        console.log("OK");
        this.open.emit('yes');
    }
    onDelete() {

        console.log("Cancel");
    }

}


问:
Distinguish zero and negative zero
I have run into a situation in my code where a function returns a double, and it is possible for this double to be a zero, a negative zero, or another value entirely. I need to distinguish between zero and negative zero, but the default double comparison does not. Due to the format of doubles, C++ does not allow for comparison of doubles using bitwise operators, so I am unsure how to procede. How can I distinguish between the two?</p>

答:
To test explicitly for a == -0 in C do the following:</p>

```<code>if (*((long *)&a) == 0x8000000000000000) {
    //  a is -0
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Distinguish zero and negative zero

Body:
To test explicitly for a == -0 in C do the following:

if (*((long *)&a) == 0x8000000000000000) {
    //  a is -0
}


问:
Can I prevent the user of my program to resize the console window? (in C)
So I was searching (a lot) and haven't find anything on how to prevent user from resizing my program's console window. I had found information for language C++ and C# but not for C. I already managed to set the size of the console but if the user changes it afterwards it is not good for my program's looking. Is there anything I can do to perfectly resize the console and keep it that way?

答:
Okay so I managed to do the magic with combining codes.
First of all you need a

```<code>#define _WIN32_WINNT 0x0500
</code>```

and after that (the order is important)

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

and after all this you need this code in your main:

```<code>HWND consoleWindow = GetConsoleWindow();
SetWindowLong(consoleWindow, GWL_STYLE, GetWindowLong(consoleWindow, GWL_STYLE) & ~WS_MAXIMIZEBOX & ~WS_SIZEBOX);
</code>```

Body:
Okay so I managed to do the magic with combining codes.
First of all you need a

#define _WIN32_WINNT 0x0500

and after that (the order is important)

#include <windows.h>

and after all this you need this code in your main:

HWND consoleWindow = GetConsoleWindow();
SetWindowLong(consoleWindow, GWL_STYLE, GetWindowLong(consoleWindow, GWL_STYLE) & ~WS_MAXIMIZEBOX & ~WS_SIZEBOX);


问:
Creating an automatic schedule for workers using Python
I'm trying to write a program that takes a list of workers and slots to be filled to come up with a schedule convenient for each worker and filling all the slots. Each worker has a maximum amount of shifts (note that the worker doesn't have to work consecutive shifts), and a list of slots for which they will be available to fill. The program returns False if all slots are not filled, or else it produces a list of workers assigned to the various slots.

A mock example of the data set and expected result:

I tried starting off by creating a class for workers initialized by (name, max_shifts, avail_slots) and then some getter methods.

```<code>Udon = ('Udon', 1, [3,4])
Ramen = ('Ramen', 1, [2])
Soba = ('Soba' , 2, [1,3])

Noodle-workers = [Soba, Ramen, Udon]
Slots = [1, 2, 3, 4]

Schedule(Noodle-workers, Slots)
</code>```

and this is expected to return:

Udon - 4
  Soba - 3
  Ramen - 2
  Soba - 1

They could be all in a list or a dictionary and each line could be a tuple. There is creative leverage on how the result appears. But the function returns False if a slot is not filled

Another data set to test the scalability of the program is as follows:

```<code>Erika  = Worker("Erika",   1, [1, 3, 7, 9])
Ryan   = Worker("Ryan",    1,   [1, 8, 10])
Reece  = Worker("Reece",   1,       [5, 6])
Gordon = Worker("Gordon",  2,    [2, 3, 9])
David  = Worker("David",   2,    [2, 8, 9])
Katie  = Worker("Katie",   1,       [4, 6])
Aashish= Worker("Aashish", 2,      [1, 10])
Grant  = Worker("Grant",   2,      [1, 11])
Raeanne= Worker("Raeanne", 2,  [1, 11, 12])
Erin   = Worker("Erin",    1,          [4])
Alex   = Worker("Alex",    1,          [7])

Workers = [Erika, Ryan, Reece, Gordon, David, Katie, Aashish, Grant,
Raeanne, Erin]
SLOTS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
</code>```

switch Erin (Workers[9]) with Alex in the workers list to get a full Schedule for all slots

My main problem is breaking down the concept to approach the problem. I thought of a tree-like structure to produce all possible combinations of assignments for workers and then eliminating those that don't satisfy the max-shifts. This was also problematic for me in a situation of choosing between two workers eligible for a slot. Furthermore I had the sense that generative recursion would probably solve the problem, but I'm at a loss on how to implement it with the accompanying structures to produce the result.

Anyway I'll really appreciate it if this problem can be solved and also the concept of solving it.

答:
Consider a tree where nodes are the assignment problems themselves (a 'list of workers'/'list of slots' pair) and edges are individual assignments ("put Udon on slot 3").

Here, a worker is not just a named person, it is a person together with the relevant work information: remaining shifts, available slots.

This is how it would start:

A depth-first search is then doable:

```<code>class Worker:

    def __init__(self, name, shifts, slots):
        self.name = name
        self.shifts = shifts
        self.slots = slots

    def copy(self):
        return Worker(self.name, self.shifts, self.slots[:])

    def assign(self, slot):
        assert slot in self.slots
        self.shifts -= 1
        self.slots.remove(slot)

def Schedule(team, slots):
    if slots == []:
        return {}
    for worker in team:
        if worker.shifts > 0:
            for slot in worker.slots:
                if slot in slots:
                    wcp = worker.copy()
                    new_team = [w if w != worker else wcp for w in team]
                    wcp.assign(slot)
                    assignments = Schedule(new_team, [s for s in slots if s != slot])
                    if assignments is not None:
                        assignments[slot] = worker.name
                        return assignments
    return None

Udon = Worker('Udon', 1, [3,4])
Ramen = Worker('Ramen', 1, [2])
Soba = Worker('Soba' , 2, [1,3])

Noodle_workers = [Soba, Ramen, Udon]
Slots = [1, 2, 3, 4]

print(Schedule(Noodle_workers, Slots))
</code>```

Update. A few explanations:

list comprehensions: I use them and (probably) abuse them, they make creating lists so much faster. Notice that the if keyword is in different positions because each line uses a different mechanism:

[w if w != worker else wcp for w in team]: simple list comprehension ([expr(i) for i in ...]) combined with a ternary operator (a if b else c)

[s for s in slots if s != slot]: conditional list comprehension ([expr(i) for i in ... if <condition>].

Expanding: the proposed implementation uses recursion, the depth of which will be equal to the number of slots to be assigned. If that number is high, this could be a problem.

Purpose of new_team: before going into that, I'll start by explaining the tree-model a little more in detail.

The starting problem is defined by giving a pool of workers and a list of slots they need to be assigned to.

Each worker is characterized by its name, the number of shifts he can make, the list of slots he is available for.

When a worker is assigned to a slot, we have to update the number of shifts he still can work, and the list of slots he remains available for. This happens in the assign method:

```<code>self.shifts -= 1
self.slots.remove(slot)
</code>```

We also remove the chosen slot from the list of slots to assign.

This then leads to a new assignment problem: how to assign the remaining workers to the remaining slots? Every choice for the first worker leads to a different new assignment problem. The new assignment problem is a child node of the previous problem in our tree structure.

During the depth-first search, if one search is unsuccessful, we will have to step back up in the tree continue to loop over possible assignments in the parent node.

Now note that a problem consists of a list of Worker objects (or lists in the OP's code) and a list of slots. In python, lists and objects are passed by reference (pointer). If, in a given step of our depth-first search, a Worker object is modified (as it is bound to be once that worker has been assigned), this object stays modified when we climb back up the tree to explore other branches, which would break the code. To avoid that, we create a copy of every worker that is to be assigned:

```<code>                wcp = worker.copy()
</code>```

and pass this copy to the child-nodes after modification. Doing so we guarantee that no data will be corrupted when we come back to that node.

The same problem would arise for the list of slots: if we passed slots to the child nodes, after removing a slot using slots.remove(slot), and if some of the child nodes did the same, the list slots would end up broken, as would the list team if we did the same.

This is solved by passing a new list of workers ans a new list of slots to the child nodes.

Body:
I'm trying to write a program that takes a list of workers and slots to be filled to come up with a schedule convenient for each worker and filling all the slots. Each worker has a maximum amount of shifts (note that the worker doesn't have to work consecutive shifts), and a list of slots for which they will be available to fill. The program returns False if all slots are not filled, or else it produces a list of workers assigned to the various slots.

A mock example of the data set and expected result:

I tried starting off by creating a class for workers initialized by (name, max_shifts, avail_slots) and then some getter methods.

Udon = ('Udon', 1, [3,4])
Ramen = ('Ramen', 1, [2])
Soba = ('Soba' , 2, [1,3])

Noodle-workers = [Soba, Ramen, Udon]
Slots = [1, 2, 3, 4]

Schedule(Noodle-workers, Slots)

and this is expected to return:

Udon - 4
  Soba - 3
  Ramen - 2
  Soba - 1

They could be all in a list or a dictionary and each line could be a tuple. There is creative leverage on how the result appears. But the function returns False if a slot is not filled

Another data set to test the scalability of the program is as follows:

Erika  = Worker("Erika",   1, [1, 3, 7, 9])
Ryan   = Worker("Ryan",    1,   [1, 8, 10])
Reece  = Worker("Reece",   1,       [5, 6])
Gordon = Worker("Gordon",  2,    [2, 3, 9])
David  = Worker("David",   2,    [2, 8, 9])
Katie  = Worker("Katie",   1,       [4, 6])
Aashish= Worker("Aashish", 2,      [1, 10])
Grant  = Worker("Grant",   2,      [1, 11])
Raeanne= Worker("Raeanne", 2,  [1, 11, 12])
Erin   = Worker("Erin",    1,          [4])
Alex   = Worker("Alex",    1,          [7])

Workers = [Erika, Ryan, Reece, Gordon, David, Katie, Aashish, Grant,
Raeanne, Erin]
SLOTS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

switch Erin (Workers[9]) with Alex in the workers list to get a full Schedule for all slots

My main problem is breaking down the concept to approach the problem. I thought of a tree-like structure to produce all possible combinations of assignments for workers and then eliminating those that don't satisfy the max-shifts. This was also problematic for me in a situation of choosing between two workers eligible for a slot. Furthermore I had the sense that generative recursion would probably solve the problem, but I'm at a loss on how to implement it with the accompanying structures to produce the result.

Anyway I'll really appreciate it if this problem can be solved and also the concept of solving it.

Body:
Consider a tree where nodes are the assignment problems themselves (a 'list of workers'/'list of slots' pair) and edges are individual assignments ("put Udon on slot 3").

Here, a worker is not just a named person, it is a person together with the relevant work information: remaining shifts, available slots.

This is how it would start:

A depth-first search is then doable:

class Worker:

    def __init__(self, name, shifts, slots):
        self.name = name
        self.shifts = shifts
        self.slots = slots

    def copy(self):
        return Worker(self.name, self.shifts, self.slots[:])

    def assign(self, slot):
        assert slot in self.slots
        self.shifts -= 1
        self.slots.remove(slot)

def Schedule(team, slots):
    if slots == []:
        return {}
    for worker in team:
        if worker.shifts > 0:
            for slot in worker.slots:
                if slot in slots:
                    wcp = worker.copy()
                    new_team = [w if w != worker else wcp for w in team]
                    wcp.assign(slot)
                    assignments = Schedule(new_team, [s for s in slots if s != slot])
                    if assignments is not None:
                        assignments[slot] = worker.name
                        return assignments
    return None

Udon = Worker('Udon', 1, [3,4])
Ramen = Worker('Ramen', 1, [2])
Soba = Worker('Soba' , 2, [1,3])

Noodle_workers = [Soba, Ramen, Udon]
Slots = [1, 2, 3, 4]

print(Schedule(Noodle_workers, Slots))

Update. A few explanations:

list comprehensions: I use them and (probably) abuse them, they make creating lists so much faster. Notice that the if keyword is in different positions because each line uses a different mechanism:

[w if w != worker else wcp for w in team]: simple list comprehension ([expr(i) for i in ...]) combined with a ternary operator (a if b else c)

[s for s in slots if s != slot]: conditional list comprehension ([expr(i) for i in ... if <condition>].

Expanding: the proposed implementation uses recursion, the depth of which will be equal to the number of slots to be assigned. If that number is high, this could be a problem.

Purpose of new_team: before going into that, I'll start by explaining the tree-model a little more in detail.

The starting problem is defined by giving a pool of workers and a list of slots they need to be assigned to.

Each worker is characterized by its name, the number of shifts he can make, the list of slots he is available for.

When a worker is assigned to a slot, we have to update the number of shifts he still can work, and the list of slots he remains available for. This happens in the assign method:

self.shifts -= 1
self.slots.remove(slot)

We also remove the chosen slot from the list of slots to assign.

This then leads to a new assignment problem: how to assign the remaining workers to the remaining slots? Every choice for the first worker leads to a different new assignment problem. The new assignment problem is a child node of the previous problem in our tree structure.

During the depth-first search, if one search is unsuccessful, we will have to step back up in the tree continue to loop over possible assignments in the parent node.

Now note that a problem consists of a list of Worker objects (or lists in the OP's code) and a list of slots. In python, lists and objects are passed by reference (pointer). If, in a given step of our depth-first search, a Worker object is modified (as it is bound to be once that worker has been assigned), this object stays modified when we climb back up the tree to explore other branches, which would break the code. To avoid that, we create a copy of every worker that is to be assigned:

                wcp = worker.copy()

and pass this copy to the child-nodes after modification. Doing so we guarantee that no data will be corrupted when we come back to that node.

The same problem would arise for the list of slots: if we passed slots to the child nodes, after removing a slot using slots.remove(slot), and if some of the child nodes did the same, the list slots would end up broken, as would the list team if we did the same.

This is solved by passing a new list of workers ans a new list of slots to the child nodes.


Title: What's the function used by ggplot2::scale_size exp?

Body:
I build a ggplot where I pass word sizes say e.g.

textSizes <- c(4.0000000,3.1148256,3.0130814,2.8604651,2.5247093,2.3110465,2.0872093,1.8633721,1.8633721,1.6497093,1.6090116,1.6090116,1.5886628,1.5683140,1.3037791,1.2936047,1.2122093,1.1816860,1.1715116,1.1613372,1.1511628,1.1409884,1.0392442,1.0188953,0.9578488,0.8561047,0.7950581,0.7848837,0.7441860,0.7441860,0.5508721)
textSizes

Assuming p is my plot I use scale_size like this:

p <- p + ggplot2::scale_size(range = c(1.7,15), trans='exp', guide = FALSE)

i.e. I want an exponential re-scaling of the text sizes within the interval 1.7 and 15. To check what ggplot is computing I do:

pg <- ggplot_build(p)
pg

and I see that the resulting sizes that ggplot computes are:

pg[[1]][[1]]$size
 [1] 15.000000 10.041629  9.592390  8.956145  7.698310  6.985947  6.301446  5.670228  5.670228  5.107868  5.004377  5.004377  4.953005
[14]  4.901867  4.253383  4.228834  4.032666  3.959037  3.934464  3.909870  3.885253  3.860608  3.611824  3.561322  3.407508  3.139436
[27]  2.967087  2.937132  2.812636  2.812636  1.700000

However, I can't manually reproduce these values. I tried the following:

interval <- log(c(1.7, 15))
interval
[1] 0.5306283 2.7080502
start <- interval[1]
end <- interval[2]

result <- exp(start+(end-start)*((textSizes-min(textSizes))/(max(textSizes)-min(textSizes))))
result
 [1] 15.000000  8.578360  8.044689  7.305781  5.910347  5.164560  4.483986  3.893096  3.893096  3.401853  3.315564  3.315564  3.273245
[14]  3.231465  2.734465  2.716957  2.580874  2.531618  2.515410  2.499305  2.483303  2.467404  2.313903  2.284368  2.198007  2.061266
[27]  1.983339  1.970641  1.920656  1.920656  1.700000

Basically I do a linear scaling of the textSizes to the interval log(c(1.7, 15)) so that doing exp will give me the desired mapping but my manually computed results don't match ggplot2's.

What is the correct function that ggplot2 is using here?

UPDATE I see that my initial linear mapping doesn't match ggplot2's

log(pg[[1]][[1]]$size)
 [1] 2.7080502 2.3067393 2.2609701 2.1923399 2.0410008 1.9439006 1.8407791 1.7352294 1.7352294 1.6307821 1.6103129 1.6103129 1.5999944
[14] 1.5896162 1.4477146 1.4419264 1.3944278 1.3760009 1.3697746 1.3635042 1.3571881 1.3508248 1.2842130 1.2701318 1.2259813 1.1440433
[27] 1.0875806 1.0774335 1.0341220 1.0341220 0.5306283

whereas my linear mapping gives:

 start+(end-start)*((textSizes-min(textSizes))/(max(textSizes)-min(textSizes)))
 [1] 2.7080502 2.1492428 2.0850121 1.9886659 1.7767045 1.6418200 1.5005124 1.3592047 1.3592047 1.2243202 1.1986279 1.1986279 1.1857818
[14] 1.1729356 1.0059357 0.9995127 0.9481280 0.9288588 0.9224357 0.9160127 0.9095896 0.9031665 0.8389358 0.8260896 0.7875512 0.7233205
[27] 0.6847820 0.6783589 0.6526666 0.6526666 0.5306283

and the difference gives:

log(pg[[1]][[1]]$size) - (start+(end-start)*((textSizes-min(textSizes))/(max(textSizes)-min(textSizes))))
 [1] 0.0000000 0.1574965 0.1759580 0.2036739 0.2642962 0.3020806 0.3402667 0.3760246 0.3760246 0.4064619 0.4116851 0.4116851 0.4142126
[14] 0.4166806 0.4417789 0.4424138 0.4462998 0.4471421 0.4473389 0.4474915 0.4475985 0.4476583 0.4452772 0.4440422 0.4384301 0.4207228
[27] 0.4027986 0.3990746 0.3814553 0.3814553 0.0000000

Body:
OK after debugging ggplot for a while I found the exact transformation:

textSizes <- c(4.0000000,3.1148256,3.0130814,2.8604651,2.5247093,2.3110465,2.0872093,1.8633721,1.8633721,1.6497093,1.6090116,1.6090116,1.5886628,1.5683140,1.3037791,1.2936047,1.2122093,1.1816860,1.1715116,1.1613372,1.1511628,1.1409884,1.0392442,1.0188953,0.9578488,0.8561047,0.7950581,0.7848837,0.7441860,0.7441860,0.5508721)
y <- exp(1)^textSizes
x <- (y-min(y))/(max(y)-min(y))
scales::rescale(x=sqrt(x), to=c(1.7,15), from=c(0, 1))
 [1] 15.000000 10.041629  9.592390  8.956145  7.698310  6.985947  6.301446  5.670228  5.670228  5.107868  5.004377
[12]  5.004377  4.953005  4.901867  4.253383  4.228835  4.032666  3.959037  3.934464  3.909870  3.885253  3.860608
[23]  3.611824  3.561322  3.407508  3.139436  2.967087  2.937132  2.812635  2.812635  1.700000


答:
You use an array when you need to use more than one item. Example:

```<code>var fooArr = [{ bar: { blah: 9 } },{ bar: { blah: 4 } },{ bar: { blah: 12 } }];
for(var i in fooArr) {
  var value = fooArr[i].bar.blah;
  console.log(value); // will log "9", "4" and "12"
}
</code>```

In the second example you only have a single object, so you don't need the the loop at all to access the property:

```<code>var fooObj = { bar: { blah: 9 } };
var value = fooObj.bar.blah;
console.log(value);
</code>```

Title: In javascript, when to use object literal and when to use array?

Body:
You use an array when you need to use more than one item. Example:

var fooArr = [{ bar: { blah: 9 } },{ bar: { blah: 4 } },{ bar: { blah: 12 } }];
for(var i in fooArr) {
  var value = fooArr[i].bar.blah;
  console.log(value); // will log "9", "4" and "12"
}

In the second example you only have a single object, so you don't need the the loop at all to access the property:

var fooObj = { bar: { blah: 9 } };
var value = fooObj.bar.blah;
console.log(value);


问:
VBA-Excel. How can I handle hide/unhide rows based on Private Sub Worksheet_Change(ByVal Target As Range)?
Good morning to all,

I am a newbie in macros & VBA Excel. I wish to handle hide/unhide rows based on Private Sub Worksheet_Change(ByVal Target As Range). I have the following code event

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
ActiveSheet.Unprotect Password:="avalon"
If Target.Column = 2 Then
Application.EnableEvents = False
Cells(Target.Row, 5).Value = Date + Time
Application.EnableEvents = True
End If
ActiveSheet.Protect Password:="avalon"
End Sub
</code>```

The idea is to aggregate this event (hide/unhide rows) when I entry data from 'B4'to 'B21' (Sometimes they will be filled totally and sometimes partially. It does not matter). Maybe, clicking in 'B21'or another event using double click in certain cell to activate unhide rows from 22 to 36 for follow up fill those rows. I hope to be clear, if not let me know to try to clarify my need to discover the proper code based on events.

Thanks in advance. I promise to learn quickly.

答:
It seems that what you are trying to do is to automatically hide or show rows based on the selection.

You can show or hide rows by using the .hidden on a range object (using EntireRow). You just need some way of determining when to hide these rows. By using the selectionChange event, you can show or hide rows based on what rows are currently selected.

The following code, when put on a worksheet object, will help you.

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Select Case Target.Row
    Case 21
        ActiveSheet.Range("B22:B36").EntireRow.Hidden = False
    Case 22 To 36
        ActiveSheet.UsedRange.EntireRow.Hidden = False
    Case Else
        ActiveSheet.Range("B22:B36").EntireRow.Hidden = True
End Select
End Sub
</code>```

You can create more cases and give the row numbers that, when selected, will hide or show other ranges.

I hope I understood your question correctly.

Body:
Good morning to all,

I am a newbie in macros & VBA Excel. I wish to handle hide/unhide rows based on Private Sub Worksheet_Change(ByVal Target As Range). I have the following code event

Private Sub Worksheet_Change(ByVal Target As Range)
ActiveSheet.Unprotect Password:="avalon"
If Target.Column = 2 Then
Application.EnableEvents = False
Cells(Target.Row, 5).Value = Date + Time
Application.EnableEvents = True
End If
ActiveSheet.Protect Password:="avalon"
End Sub

The idea is to aggregate this event (hide/unhide rows) when I entry data from 'B4'to 'B21' (Sometimes they will be filled totally and sometimes partially. It does not matter). Maybe, clicking in 'B21'or another event using double click in certain cell to activate unhide rows from 22 to 36 for follow up fill those rows. I hope to be clear, if not let me know to try to clarify my need to discover the proper code based on events.

Thanks in advance. I promise to learn quickly.

Body:
It seems that what you are trying to do is to automatically hide or show rows based on the selection.

You can show or hide rows by using the .hidden on a range object (using EntireRow). You just need some way of determining when to hide these rows. By using the selectionChange event, you can show or hide rows based on what rows are currently selected.

The following code, when put on a worksheet object, will help you.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Select Case Target.Row
    Case 21
        ActiveSheet.Range("B22:B36").EntireRow.Hidden = False
    Case 22 To 36
        ActiveSheet.UsedRange.EntireRow.Hidden = False
    Case Else
        ActiveSheet.Range("B22:B36").EntireRow.Hidden = True
End Select
End Sub

You can create more cases and give the row numbers that, when selected, will hide or show other ranges.

I hope I understood your question correctly.


问:
JavaScript regular expression check number only
I want a regular expression for the following values:

```<code>1) .1 = False.
2) 0.1 = True.
3) 1.1245 = True.
4) 1.2. = False.
5) 1.24.35 = False.
6) 21.152 = true.
</code>```

This regex should check that the string represents an integer or is composed of only numbers and a single . representing a decimal point.

I am using: /^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/ but it takes "1.2." as true.

答:
You are taking the first digits set as none or more \d*, you should use \d+, then it would work for the cases you want.

Can also look here

Edit: ^[\+\-]?\d+(\.?\d+(?:[Ee][\+\-]?\d+)?)?$

Body:
I want a regular expression for the following values:

1) .1 = False.
2) 0.1 = True.
3) 1.1245 = True.
4) 1.2. = False.
5) 1.24.35 = False.
6) 21.152 = true.

This regex should check that the string represents an integer or is composed of only numbers and a single . representing a decimal point.

I am using: /^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/ but it takes "1.2." as true.


问:
Optimize website to show reader view in Firefox
Firefox 38.0.5 added a "Reader View" to the address bar:

But not all sites get this icon, It only appears when readable content page is detected. So how do I enable this for my site?

I tried media print and an extra stylesheet for print-view, but that has no effect:

```<code><html>
<head>
<style>
  @media print { /* no effect: */
    .no-print { display:none; }
  }
</style>
<!-- no effect either:
<link rel="stylesheet" href="print.css" media="print"><!--  -->
</head><body>
<h1>Some Title</h1>
<img class="no-print" src="http://dummyimage.com/1024x100/000/ffffff&text=This+banner+should+vanish+in+print+view">
<br><br><br>This is the only text
</body></html>
</code>```

What code snippets do I have to add into my website sourcecode so this book icon will become visible to the visitors of my site?

答:
As the code stands in May '20 the trigger function (isProbablyReaderable) scores only p or pre elements and div elements that contain at least one decedent br.

A slight oversimplification of the scoring heuristic is:

For each element in ['p', 'pre', 'div > br']:

If textContent length is > 140 chars, increase score by sqrt(length - 140)

if cumulative score > 20, return true

Body:
Firefox 38.0.5 added a "Reader View" to the address bar:

But not all sites get this icon, It only appears when readable content page is detected. So how do I enable this for my site?

I tried media print and an extra stylesheet for print-view, but that has no effect:

Some Title

This is the only text

What code snippets do I have to add into my website sourcecode so this book icon will become visible to the visitors of my site?


问:
Adding 2 two-digit numbers that results to a 3-digit in assembly
I managed to make the addition of two-digit numbers based on the solutions provided by helpful people from the thread I created last time:

How do I use ADC in assembly?

So now, there seems to be a problem when I add 2 numbers and their result will be a 3-digit number. The jump named IS_3DIGIT handles that possibility, but addition of some numbers like 80 + 80, 99 + 99, 89 + 82 all give wrong results. 56 + 77 works well. So my hypothesis is that adding two numbers higher than 79 will give wrong results. How can I resolve this problem? BTW, additions like 99 + 23 or 89 + 43 give correct results.

```<code>.MODEL SMALL
.STACK 1000
.DATA

MSGA DB 13,10,"Input first number: ","$"
MSGB DB 13,10,"Input second number:","$"
MSGC DB 13,10,"The sum is: ","$"

NUM1 db ?
NUM2 db ?
NUM3 db ?

.CODE

MAIN PROC NEAR

MOV AX, @DATA
MOV DS, AX

; get first number
LEA DX, MSGA
MOV AH, 09h
INT 21h

MOV AH, 01
INT 21H
SUB AL, '0'

MOV BL, AL

MOV AH, 01
INT 21H
SUB AL, '0'

MOV CL, AL

; get second number
LEA DX, MSGB
MOV AH, 09h
INT 21h

MOV AH, 01
INT 21H
SUB AL, '0'

MOV DL, AL

MOV AH, 01
INT 21H
SUB AL, '0'

MOV DH, AL

; add
MOV AL, CL
MOV AH, BL
ADD AL, DH
AAA
ADD AH, DL

MOV NUM1, AL
ADD NUM1, '0'

; if tens digit is less than or equal to 9
CMP AH, 9
JLE NOT_3DIGIT

IS_3DIGIT:
MOV AL, AH   ; move value of ah to al
SUB AH, AH   ; clear ah
ADD AL, 0    ; al + 0 = al (tens digit)
AAA          ; move for addition
ADD AH, 0    ; ah + 0 + 1 = ah + 1 (hundreds digit)
MOV NUM2, AL
MOV NUM3, AH
ADD NUM2, '0'
ADD NUM3, '0'
; output sum
LEA DX, MSGC
MOV AH, 09h
INT 21h
MOV DL, NUM3
MOV AH, 02H
INT 21h
MOV DL, NUM2
MOV AH, 02H
INT 21h
JMP PRINT_LASTDIGIT

NOT_3DIGIT:
MOV NUM2, AH
ADD NUM2, '0'
; output sum
LEA DX, MSGC
MOV AH, 09h
INT 21h
MOV DL, NUM2
MOV AH, 02H
INT 21h

PRINT_LASTDIGIT:
MOV DL, NUM1
MOV AH, 02H
INT 21h

EXIT:
MOV AH, 4Ch
INT 21h

MAIN ENDP
END MAIN
</code>```

答:
I think it can be done in other way round. There is no need to check whether it has become 3 digit or not. </p>

```<code>PRINT MACRO MSG
      LEA DX,MSG
      MOV AH,09H
      INT 21H
ENDM

READ MACRO N,J1,J2
      J1: MOV AH,01H
          INT 21H
      CMP AL,0DH
      JE J2
      SUB AL,30H
      MOV BL,AL
      MOV AX,N
      MOV DX,0AH
      MUL DX
      XOR BH,BH
      ADD AX,BX
      MOV N,AX
      JMP J1
  J2: NOP
ENDM

PRINTMUL MACRO N1,L2,L3
            MOV BX,000AH
            MOV AX,N1
            XOR CX,CX

       L2: XOR DX,DX
           DIV BX
           PUSH DX
           INC CX
           CMP AX,0000H
           JNE L2

       L3: POP DX
           ADD DL,30H
           MOV AH,02H
           INT 21H
           LOOP L3
ENDM

.MODEL SMALL
.STACK 100H
.DATA
    N DW 0
    M DW 0
    MS DB 0DH,0AH,"ENTER 1ST: $"
    MT DB 0DH,0AH,"ENTER 2ND: $"
    ANS DB 0DH,0AH,"ANSWER IS: $"
.CODE
MAIN PROC
    MOV AX,@DATA
    MOV DS,AX

    PRINT MS
    READ N,U1,U2

    PRINT MT
    READ M,G1,G2

    PRINT ANS
    MOV AX,N
    ADD AX,M

    PRINTMUL AX,H1,J5

MAIN ENDP
END MAIN
</code>```

Body:
I managed to make the addition of two-digit numbers based on the solutions provided by helpful people from the thread I created last time:

How do I use ADC in assembly?

So now, there seems to be a problem when I add 2 numbers and their result will be a 3-digit number. The jump named IS_3DIGIT handles that possibility, but addition of some numbers like 80 + 80, 99 + 99, 89 + 82 all give wrong results. 56 + 77 works well. So my hypothesis is that adding two numbers higher than 79 will give wrong results. How can I resolve this problem? BTW, additions like 99 + 23 or 89 + 43 give correct results.

.MODEL SMALL
.STACK 1000
.DATA

MSGA DB 13,10,"Input first number: ","$"
MSGB DB 13,10,"Input second number:","$"
MSGC DB 13,10,"The sum is: ","$"

NUM1 db ?
NUM2 db ?
NUM3 db ?

.CODE

MAIN PROC NEAR

MOV AX, @DATA
MOV DS, AX

; get first number
LEA DX, MSGA
MOV AH, 09h
INT 21h

MOV AH, 01
INT 21H
SUB AL, '0'

MOV BL, AL

MOV AH, 01
INT 21H
SUB AL, '0'

MOV CL, AL

; get second number
LEA DX, MSGB
MOV AH, 09h
INT 21h

MOV AH, 01
INT 21H
SUB AL, '0'

MOV DL, AL

MOV AH, 01
INT 21H
SUB AL, '0'

MOV DH, AL

; add
MOV AL, CL
MOV AH, BL
ADD AL, DH
AAA
ADD AH, DL

MOV NUM1, AL
ADD NUM1, '0'

; if tens digit is less than or equal to 9
CMP AH, 9
JLE NOT_3DIGIT

IS_3DIGIT:
MOV AL, AH   ; move value of ah to al
SUB AH, AH   ; clear ah
ADD AL, 0    ; al + 0 = al (tens digit)
AAA          ; move for addition
ADD AH, 0    ; ah + 0 + 1 = ah + 1 (hundreds digit)
MOV NUM2, AL
MOV NUM3, AH
ADD NUM2, '0'
ADD NUM3, '0'
; output sum
LEA DX, MSGC
MOV AH, 09h
INT 21h
MOV DL, NUM3
MOV AH, 02H
INT 21h
MOV DL, NUM2
MOV AH, 02H
INT 21h
JMP PRINT_LASTDIGIT

NOT_3DIGIT:
MOV NUM2, AH
ADD NUM2, '0'
; output sum
LEA DX, MSGC
MOV AH, 09h
INT 21h
MOV DL, NUM2
MOV AH, 02H
INT 21h

PRINT_LASTDIGIT:
MOV DL, NUM1
MOV AH, 02H
INT 21h

EXIT:
MOV AH, 4Ch
INT 21h

MAIN ENDP
END MAIN

Body:
I think it can be done in other way round. There is no need to check whether it has become 3 digit or not.

PRINT MACRO MSG
      LEA DX,MSG
      MOV AH,09H
      INT 21H
ENDM

READ MACRO N,J1,J2
      J1: MOV AH,01H
          INT 21H
      CMP AL,0DH
      JE J2
      SUB AL,30H
      MOV BL,AL
      MOV AX,N
      MOV DX,0AH
      MUL DX
      XOR BH,BH
      ADD AX,BX
      MOV N,AX
      JMP J1
  J2: NOP
ENDM

PRINTMUL MACRO N1,L2,L3
            MOV BX,000AH
            MOV AX,N1
            XOR CX,CX

       L2: XOR DX,DX
           DIV BX
           PUSH DX
           INC CX
           CMP AX,0000H
           JNE L2

       L3: POP DX
           ADD DL,30H
           MOV AH,02H
           INT 21H
           LOOP L3
ENDM

.MODEL SMALL
.STACK 100H
.DATA
    N DW 0
    M DW 0
    MS DB 0DH,0AH,"ENTER 1ST: $"
    MT DB 0DH,0AH,"ENTER 2ND: $"
    ANS DB 0DH,0AH,"ANSWER IS: $"
.CODE
MAIN PROC
    MOV AX,@DATA
    MOV DS,AX

    PRINT MS
    READ N,U1,U2

    PRINT MT
    READ M,G1,G2

    PRINT ANS
    MOV AX,N
    ADD AX,M

    PRINTMUL AX,H1,J5

MAIN ENDP
END MAIN