问:
How to use multiple columns in Bootsrap not starting From column 1?
I have two buttons in page. According to W3Schools, the page is divided into 12 columns. I want the two buttons to be 4 columns wide but from column 2 to 5 and the second from column 8 to 11. How can I do this? I am using using bootstrap to do this.

Using empty 'p' elements doesn't seem to work as seen below.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

  <input type="button" id="cancel" name="cancel" value="Cancel" onclick="cancel();" class="col-sm-3">

  <input type="button" id="registerX" class="col-sm-3" name="registerX" value="Register" onclick="submitCheck();">

```

I can notice a bigger gap after the second button that the first gap. What can I do?

Edit: To see it open the code in a full page.

答:
Leaving an answer instead of a comment because I don't have enough reputation.
Just wanted to point out OP is using bootstrap 3, not 4, so offset would be written as "col-sm-offset-1", not "offset-sm-1".</p>

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<div class="row container-fluid">
    <div class="col-sm-4 col-sm-offset-1">
        <button type="button" class="btn btn-primary btn-block" id="cancel" name="cancel" value="Cancel" onclick="cancel();">Primary</button>
    </div>
    <div class="col-sm-4 col-sm-offset-2">
        <button type="button" class="btn btn-primary btn-block" id="registerX" name="registerX" value="Register" onclick="submitCheck();">Primary</button>
    </div>
</div>
</code>```

Body:
I have two buttons in page. According to W3Schools, the page is divided into 12 columns. I want the two buttons to be 4 columns wide but from column 2 to 5 and the second from column 8 to 11. How can I do this? I am using using bootstrap to do this.

Using empty 'p' elements doesn't seem to work as seen below.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

  <input type="button" id="cancel" name="cancel" value="Cancel" onclick="cancel();" class="col-sm-3">

  <input type="button" id="registerX" class="col-sm-3" name="registerX" value="Register" onclick="submitCheck();">

I can notice a bigger gap after the second button that the first gap. What can I do?

Edit: To see it open the code in a full page.

Body:
Leaving an answer instead of a comment because I don't have enough reputation.
Just wanted to point out OP is using bootstrap 3, not 4, so offset would be written as "col-sm-offset-1", not "offset-sm-1".

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<div class="row container-fluid">
    <div class="col-sm-4 col-sm-offset-1">
        <button type="button" class="btn btn-primary btn-block" id="cancel" name="cancel" value="Cancel" onclick="cancel();">Primary</button>
    </div>
    <div class="col-sm-4 col-sm-offset-2">
        <button type="button" class="btn btn-primary btn-block" id="registerX" name="registerX" value="Register" onclick="submitCheck();">Primary</button>
    </div>
</div>


来源: stackexchange

问:
Is .indexWhere() async?
As indexWhere() searches through potentially large Lists to find the matching index, is this an async operation?

And if so is there some way to await it? e.g. similar to Future.forEach

答:
Since the method does not return a Future but an int, then the method is synchronous:

https://api.dart.dev/stable/2.7.1/dart-core/List/indexWhere.html

I also want to point out that asynchronous code in Dart are not the same as the code is running in another thread. Since we are talking about finding a index inside a List, then you can be fairly sure that this operation can only be done in a single thread since we need to prevent modifications of the List when we are making the search.

ContentLicense: CC BY-SA 4.0

Title: Is .indexWhere() async?


问:
How to select all active sheets?
Everything is good. The only error I am getting here is the Select. How can I select all active sheets except for specific sheets? I want the Macro to run to all active sheets.

I have the macro code below and please let me know what I can do. I am still an amateur to excel VBA, but I am doing my best to learn more, so I can do more.

Sub Macro1()
'
' Macro1 Macro
'

'
    Columns("A:XFD").Select
    Range("A3").Activate
    Sheets(Array("Sheet1", "1191", "41", "16", "1223")).Select
    Sheets("1191").Activate
    Columns("A:XFD").Select
    Range("A3").Activate
    Range(Selection, Selection.End(xlToRight)).Select
    Range("C15").Select
    Sheets("Sheet1").Select
    ActiveWindow.SelectedSheets.Delete
    Sheets(Array("1191", "41", "16", "1223")).Select
    Sheets("1191").Activate
    ActiveWindow.SmallScroll Down:=-9
    Range("D4").Select
    Sheets(Array("1191", "41", "16", "1223")).Select
    Sheets("1191").Activate
    Range("C4").Select
    Rows("2:2").EntireRow.AutoFit
    Range("D3").Select
    Sheets(Array("41", "16", "1223")).Select
    Sheets("41").Activate
    Rows("4:4").Select
    Range(Selection, Selection.End(xlUp)).Select
    Range(Selection, Selection.End(xlUp)).Select
    Range(Selection, Selection.End(xlUp)).Select
    Range("A4").Select
    ActiveWindow.SmallScroll Down:=-15
    Sheets(Array("41", "16", "1223")).Select
    Sheets("16").Activate
    ActiveWindow.SmallScroll Down:=-15
    Range("D17").Select
    Sheets(Array("41", "16", "1223")).Select
    Sheets("1223").Activate
    ActiveWindow.SmallScroll Down:=-15
    Sheets(Array("1191", "41", "16", "1223")).Select
    Sheets("1191").Activate
    Rows("2:2").Select
    Selection.RowHeight = 34.5
    Range("B3").Select
    Rows("3:3").RowHeight = 60
    Rows("4:4").RowHeight = 106.5
    Rows("4:4").RowHeight = 126
    Rows("5:5").RowHeight = 113.25
    Columns("A:A").Select
    Range(Selection, Selection.End(xlToRight)).Select
    Range(Selection, Selection.End(xlToRight)).Select
    Range(Selection, Selection.End(xlToRight)).Select
    Range(Selection, Selection.End(xlToRight)).Select
    Range(Selection, Selection.End(xlToRight)).Select
    Selection.ColumnWidth = 4.71
    Cells.EntireColumn.AutoFit
    Columns("C:C").Select
    Selection.EntireColumn.Hidden = True
    Columns("G:G").Select
    Selection.EntireColumn.Hidden = True
    Range("D4").Select
    Sheets("1191").Select
    Range("D4").Select
    Cells.Replace What:="Unavailable", Replacement:="", LookAt:=xlWhole, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
    With Application.ReplaceFormat.Interior
        .PatternColorIndex = xlAutomatic
        .Color = 6053069
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
    Cells.Replace What:="", Replacement:="", LookAt:=xlWhole, SearchOrder:= _
        xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=True
    Range("D4").Select
    ActiveWindow.SmallScroll Down:=-24
    Sheets(Array("1191", "41", "16", "1223")).Select
    Sheets("1191").Activate
    Range("B4:F4").Select
    Range(Selection, Selection.End(xlDown)).Select
    Range(Selection, Selection.End(xlDown)).Select
    Range(Selection, Selection.End(xlDown)).Select
    With Selection.Interior
        .Pattern = xlNone
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
    Range("D3").Select
    Sheets("1191").Select
    Range("D4").Select
End Sub
```

答:
Except for the sheet name you want to exclude, put the sheet name in the array, and then select the sheet as the array.</p>

```<code>Sub test()
    Dim Ws As Worksheet
    Dim vR() As Variant
    Dim n As Integer
    For Each Ws In Worksheets
        If Ws.Name <> "Except Sheet Name" Then
            n = n + 1
            ReDim Preserve vR(1 To n)
            vR(n) = Ws.Name
        End If
    Next Ws
    Sheets(vR).Select
End Sub
</code>```

Title: How to select all active sheets?

Body:
Except for the sheet name you want to exclude, put the sheet name in the array, and then select the sheet as the array.

Sub test()
    Dim Ws As Worksheet
    Dim vR() As Variant
    Dim n As Integer
    For Each Ws In Worksheets
        If Ws.Name <> "Except Sheet Name" Then
            n = n + 1
            ReDim Preserve vR(1 To n)
            vR(n) = Ws.Name
        End If
    Next Ws
    Sheets(vR).Select
End Sub


问:
How to start a IIS process with specific username & password
I'm trying to run an application from our internal website. When I use Process.Start("notepad"); I can see that notepad process started in our web server with default identity mentioned in the app pool setting.

But I have to start the process with specific user name & password. So I have tried to run this line of code

```<code>string password = "XXXXX";
System.Security.SecureString securePwd = new System.Security.SecureString();
foreach (char c in password)
{
    // Append the character to the password.
    securePwd.AppendChar(c);
}
Process.Start("notepad", "username", securePwd, "domain");
</code>```

In this case I don't even see any notepad process started in the web server. The lines of code executing because when I pass wrong password I can see my webpage throwing error of "bad username or password".

答:
The code you've written looks fine to me. Perhaps the problem is

I don't even see any notepad process

I would try the following

Capture the ID and write it out to the client e.g.

```<code>Process note = Process.Start("notepad", "username", securePwd, "domain");
Response.Write( note.ID ); //Or whatever mechanism you prefer.
</code>```

Then log on to the server and with PowerShell query the process

e.g.

```<code>PS C:\> get-process notepad  | Select ProcessName, Id
ProcessName                                                                  Id
-----------                                                                  --
notepad                                                                    5512
</code>```

The Id should match what was written to the client

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to run an application from our internal website. When I use Process.Start("notepad"); I can see that notepad process started in our web server with default identity mentioned in the app pool setting.

But I have to start the process with specific user name & password. So I have tried to run this line of code

string password = "XXXXX";
System.Security.SecureString securePwd = new System.Security.SecureString();
foreach (char c in password)
{
    // Append the character to the password.
    securePwd.AppendChar(c);
}
Process.Start("notepad", "username", securePwd, "domain");

In this case I don't even see any notepad process started in the web server. The lines of code executing because when I pass wrong password I can see my webpage throwing error of "bad username or password".

Body:
The code you've written looks fine to me. Perhaps the problem is

I don't even see any notepad process

I would try the following

Capture the ID and write it out to the client e.g.

Process note = Process.Start("notepad", "username", securePwd, "domain");
Response.Write( note.ID ); //Or whatever mechanism you prefer.

Then log on to the server and with PowerShell query the process

e.g.

PS C:\> get-process notepad  | Select ProcessName, Id
ProcessName                                                                  Id
-----------                                                                  --
notepad                                                                    5512

The Id should match what was written to the client


问:
Range-v3 operator overloading to write shorter code
For my matrix class I want to do some sort of operator overloading (probably using expression templates) on range-v3 views for + - / * % .
For example if I want to get a view of the sum of two columns, I want to write

```<code>col_1 + col_2
</code>```

instead of

```<code>rv::zip_with([](auto c1, auto c2) {return c1 + c2;}, col_1, col_2);
</code>```

Probably some ideas from this paper can be used to avoid constructing too many temporaries. Here is the code that I want to write:

```<code>//simple example
//what I want to write
auto rangeview =    col_1 + col_2;
//what I can write
auto rangeview =    rv::zip_with([](auto c1, auto c2) {
                        return c1 + c2;
                    }, col_1, col_2);

//itermediate
//what I want to write
auto rangeview =    col_1 + col_2 + col_3;
//what I can write
auto rangeview =    rv::zip_with([](auto c1, auto c2, auto c3) {
                        return c1 + c2 + c3;
                    }, col_1, col_2, col_3);

//advanced
//what I want to write
auto rangeview =    10*col_1 + 20*col_2 - 30*col_3;
//what I can write
auto rangeview =    rv::zip_with([](auto c1, auto c2, auto c3) {
                        return 10.0*c1 + 20.0*c2 - 30.0*c3;
                    }, col_1, col_2, col_3);

//more advanced with elementwise multiplication
//what I want to write
auto rangeview =    10*col_1 + 20*col_2 - col_2 % col_3;
//what I can write
auto rangeview =    rv::zip_with([](auto c1, auto c2, auto c3) {
                        return 10.0*c1 + 20.0*c2 - c2*c3;
                    }, col_1, col_2, col_3);
</code>```

答:
You main concern seem to be with (possible huge) temporaries that could be created. This can be solved with a concept called expression templates, but there is not really a one size fits all solution here. Best bet is probably switch to a matrix library that supports that. Unless you are developing a  library or want to invest in this you probably want to steer away from writing your own expression templates. An easier method for getting closer, but without a lot of operator overloading/expression templates could be using range based for loop with custom iteration type (not as syntactically sugery as expression templates but much easier to implement):

Pseudocode:

```<code>*resultype* result;//perhaps alloc on this line or make zip handle it..
for (auto z : zip(result, col_1, col_2, col_3)) {
  z[0] = 10.0*z[1] + 20.0*z[2] - 30.0*z[3];
}
</code>```

This is on the idea stage, but will be a bit shorter (and imho a bit more pleasing to read) than the lambda style.
How to implement the zip class I leave out of this answer.

Body:
For my matrix class I want to do some sort of operator overloading (probably using expression templates) on range-v3 views for + - / * % .
For example if I want to get a view of the sum of two columns, I want to write

col_1 + col_2

instead of

rv::zip_with([](auto c1, auto c2) {return c1 + c2;}, col_1, col_2);

Probably some ideas from this paper can be used to avoid constructing too many temporaries. Here is the code that I want to write:

//simple example
//what I want to write
auto rangeview =    col_1 + col_2;
//what I can write
auto rangeview =    rv::zip_with([](auto c1, auto c2) {
                        return c1 + c2;
                    }, col_1, col_2);

//itermediate
//what I want to write
auto rangeview =    col_1 + col_2 + col_3;
//what I can write
auto rangeview =    rv::zip_with([](auto c1, auto c2, auto c3) {
                        return c1 + c2 + c3;
                    }, col_1, col_2, col_3);

//advanced
//what I want to write
auto rangeview =    10*col_1 + 20*col_2 - 30*col_3;
//what I can write
auto rangeview =    rv::zip_with([](auto c1, auto c2, auto c3) {
                        return 10.0*c1 + 20.0*c2 - 30.0*c3;
                    }, col_1, col_2, col_3);

//more advanced with elementwise multiplication
//what I want to write
auto rangeview =    10*col_1 + 20*col_2 - col_2 % col_3;
//what I can write
auto rangeview =    rv::zip_with([](auto c1, auto c2, auto c3) {
                        return 10.0*c1 + 20.0*c2 - c2*c3;
                    }, col_1, col_2, col_3);

Body:
You main concern seem to be with (possible huge) temporaries that could be created. This can be solved with a concept called expression templates, but there is not really a one size fits all solution here. Best bet is probably switch to a matrix library that supports that. Unless you are developing a  library or want to invest in this you probably want to steer away from writing your own expression templates. An easier method for getting closer, but without a lot of operator overloading/expression templates could be using range based for loop with custom iteration type (not as syntactically sugery as expression templates but much easier to implement):

Pseudocode:

*resultype* result;//perhaps alloc on this line or make zip handle it..
for (auto z : zip(result, col_1, col_2, col_3)) {
  z[0] = 10.0*z[1] + 20.0*z[2] - 30.0*z[3];
}

This is on the idea stage, but will be a bit shorter (and imho a bit more pleasing to read) than the lambda style.
How to implement the zip class I leave out of this answer.


问:
Replace() with Split()
I need to enter a "0" in case there's only one digit after the comma, how does replace() work in this situation?

var a = "2x 250,5";

console.log(a.replace(a.split(",")[1], a.split(",")[1] + 0));

//expected result
// 2x 250,50

//Output
//2x 2500,5```

答:
var a = "2x 250,1",
splitvar = ","
a.split(splitvar)[1].length==1 && (a = a.replace(splitvar+a.split(splitvar)[1], ","+a.split(splitvar)[1] + 0))
console.log(a);```

Title: Replace() with Split()


问:
Method to extract exact 95% confidence values from stat_smooth(method = "glm")
I have produced a glm interaction plot using ggplot2. I have attached the code I have used and the plot

 .

I know that the grey shaded areas represent the 95% condfidence interval, but I am wondering if there is a method to get the exact values of the grey shaded areas and therefore 95% confidence interval?

```<code>#bind data togther
</code>```

Modern_EarlyHolocene<-rbind(FladenF30, FladenB30, Early_Holocene)

```<code>#Build modern vs Holocene model
</code>```

Modern_EarlyHolocene<-glm(Max_Height~Age+Time_period, data=Modern_EarlyHolocene,family = gaussian)

```<code>#Produce gg interaction plot
</code>```

Modern_EarlyHolocene_plot<-ggplot(data=Modern_EarlyHolocene) +
  aes(x = Age, y = Max_Height, group = Time_period, color = Time_period,) +>
  geom_point( alpha = .7) +
  stat_smooth(method = "glm", level=0.95) +
  expand_limits(y=c(0,90), x=c(0,250))

#add axis labels

Modern_EarlyHolocene_plot + labs(x = "Age (years)", y = 'Maximum height (mm)') +
  theme(legend.text = element_text(size = 14, colour = "Black"),
        legend.title=element_blank()) +
 theme(axis.text=element_text(size=14),
        axis.title=element_text(size=16,face="bold"))

答:
You are effectively fitting a different regression line for each Time_period, so your glm has to include an interaction term. It should be:

```<code>Modern_EarlyHolocene<-glm(Max_Height~Age*Time_period, data=Modern_EarlyHolocene)
</code>```

I do not have your data, so see below for an example with iris:

```<code>fit = glm(Sepal.Width ~ Sepal.Length * Species,data=iris)
g1 = ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width,color=Species)) +
geom_point( alpha = .7) + stat_smooth(method = "glm", level=0.95)
</code>```

To get the se of the predictions, you do:

```<code>pred = predict(fit,iris,se.fit = TRUE)
df_pred = data.frame(iris,pred=pred$fit,se=pred$se)
</code>```

We can plot this, and the upper and lower bounds of the prediction are 1.96 * the standard error:

```<code>g2 = ggplot(df_pred,aes(x=Sepal.Length,y=Sepal.Width,color=Species)) +
geom_point( alpha = .7) +
geom_ribbon(aes(ymin=pred-1.96*se,ymax=pred+1.96*se,fill=Species),alpha=0.1)
</code>```

Body:
I have produced a glm interaction plot using ggplot2. I have attached the code I have used and the plot

 .

I know that the grey shaded areas represent the 95% condfidence interval, but I am wondering if there is a method to get the exact values of the grey shaded areas and therefore 95% confidence interval?

#bind data togther

Modern_EarlyHolocene<-rbind(FladenF30, FladenB30, Early_Holocene)

#Build modern vs Holocene model

Modern_EarlyHolocene<-glm(Max_Height~Age+Time_period, data=Modern_EarlyHolocene,family = gaussian)

#Produce gg interaction plot

Modern_EarlyHolocene_plot<-ggplot(data=Modern_EarlyHolocene) +
  aes(x = Age, y = Max_Height, group = Time_period, color = Time_period,) +>
  geom_point( alpha = .7) +
  stat_smooth(method = "glm", level=0.95) +
  expand_limits(y=c(0,90), x=c(0,250))

#add axis labels

Modern_EarlyHolocene_plot + labs(x = "Age (years)", y = 'Maximum height (mm)') +
  theme(legend.text = element_text(size = 14, colour = "Black"),
        legend.title=element_blank()) +
 theme(axis.text=element_text(size=14),
        axis.title=element_text(size=16,face="bold"))

Body:
You are effectively fitting a different regression line for each Time_period, so your glm has to include an interaction term. It should be:

Modern_EarlyHolocene<-glm(Max_Height~Age*Time_period, data=Modern_EarlyHolocene)

I do not have your data, so see below for an example with iris:

fit = glm(Sepal.Width ~ Sepal.Length * Species,data=iris)
g1 = ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width,color=Species)) +
geom_point( alpha = .7) + stat_smooth(method = "glm", level=0.95)

To get the se of the predictions, you do:

pred = predict(fit,iris,se.fit = TRUE)
df_pred = data.frame(iris,pred=pred$fit,se=pred$se)

We can plot this, and the upper and lower bounds of the prediction are 1.96 * the standard error:

g2 = ggplot(df_pred,aes(x=Sepal.Length,y=Sepal.Width,color=Species)) +
geom_point( alpha = .7) +
geom_ribbon(aes(ymin=pred-1.96*se,ymax=pred+1.96*se,fill=Species),alpha=0.1)


问:
How to set value to new column in Rails 3?
This is probably in another question, but I cannot find it.

I am a relative noobie to Rails.  I am trying to add a new column to a table that already has data in it.  This column is not going to allow nulls.  What is the easiest way to update all the existing records to have a value in this new column?  I know it is probably in the up block of my migration, but I don't know what the syntax would be.

```<code>def self.up
  change_table :reminders do |t|
    t.boolean :active
  end
  #model name is Reminder - how to update data with a value?
end
</code>```

答:
What you can do is add the column, update all records in the table with the desired value, then change it to not allow nulls. </p>

```<code>def self.up
  add_column :reminders, :active, :boolean, :default => true
  Reminder.update_all( "active = ?", true )
  change_column :reminders, :active, :boolean, :default => true, :null => :false
end
</code>```

Body:
This is probably in another question, but I cannot find it.

I am a relative noobie to Rails.  I am trying to add a new column to a table that already has data in it.  This column is not going to allow nulls.  What is the easiest way to update all the existing records to have a value in this new column?  I know it is probably in the up block of my migration, but I don't know what the syntax would be.

def self.up
  change_table :reminders do |t|
    t.boolean :active
  end
  #model name is Reminder - how to update data with a value?
end

Body:
What you can do is add the column, update all records in the table with the desired value, then change it to not allow nulls.

def self.up
  add_column :reminders, :active, :boolean, :default => true
  Reminder.update_all( "active = ?", true )
  change_column :reminders, :active, :boolean, :default => true, :null => :false
end


问:
How to count overlapping datetime intervals in Pandas?
I have a following DataFrame with two datetime columns:

```<code>    start               end
0   01.01.2018 00:47    01.01.2018 00:54
1   01.01.2018 00:52    01.01.2018 01:03
2   01.01.2018 00:55    01.01.2018 00:59
3   01.01.2018 00:57    01.01.2018 01:16
4   01.01.2018 01:00    01.01.2018 01:12
5   01.01.2018 01:07    01.01.2018 01:24
6   01.01.2018 01:33    01.01.2018 01:38
7   01.01.2018 01:34    01.01.2018 01:47
8   01.01.2018 01:37    01.01.2018 01:41
9   01.01.2018 01:38    01.01.2018 01:41
10  01.01.2018 01:39    01.01.2018 01:55
</code>```

I would like to count how many starts (intervals) are active at the same time before they end at given time (in other words: how many times each row overlaps with the rest of the rows).

E.g. from 00:47 to 00:52 only one is active, from 00:52 to 00:54 two, from 00:54 to 00:55 only one again, and so on.

I tried to stack columns onto each other, sort by date and by iterrating through whole dataframe give each "start" +1 to counter and -1 to each "end". It works but on my original data frame, where I have few millions of rows, iteration takes forever - I need to find a quicker way.

My original basic-and-not-very-good code:

```<code>import pandas as pd
import numpy as np

df = pd.read_csv('something.csv', sep=';')

df = df.stack().to_frame()
df = df.reset_index(level=1)
df.columns = ['status', 'time']
df = df.sort_values('time')
df['counter'] = np.nan
df = df.reset_index().drop('index', axis=1)

print(df.head(10))
</code>```

gives:

```<code>    status  time                counter
0   start   01.01.2018 00:47    NaN
1   start   01.01.2018 00:52    NaN
2   stop    01.01.2018 00:54    NaN
3   start   01.01.2018 00:55    NaN
4   start   01.01.2018 00:57    NaN
5   stop    01.01.2018 00:59    NaN
6   start   01.01.2018 01:00    NaN
7   stop    01.01.2018 01:03    NaN
8   start   01.01.2018 01:07    NaN
9   stop    01.01.2018 01:12    NaN
</code>```

and:

```<code>counter = 0

for index, row in df.iterrows():

    if row['status'] == 'start':
        counter += 1
    else:
        counter -= 1
    df.loc[index, 'counter'] = counter
</code>```

final output:

```<code>        status  time                counter
    0   start   01.01.2018 00:47    1.0
    1   start   01.01.2018 00:52    2.0
    2   stop    01.01.2018 00:54    1.0
    3   start   01.01.2018 00:55    2.0
    4   start   01.01.2018 00:57    3.0
    5   stop    01.01.2018 00:59    2.0
    6   start   01.01.2018 01:00    3.0
    7   stop    01.01.2018 01:03    2.0
    8   start   01.01.2018 01:07    3.0
    9   stop    01.01.2018 01:12    2.0
</code>```

Is there any way i can do this by NOT using iterrows()?

Thanks in advance!

Body:
I have a following DataFrame with two datetime columns:

    start               end
0   01.01.2018 00:47    01.01.2018 00:54
1   01.01.2018 00:52    01.01.2018 01:03
2   01.01.2018 00:55    01.01.2018 00:59
3   01.01.2018 00:57    01.01.2018 01:16
4   01.01.2018 01:00    01.01.2018 01:12
5   01.01.2018 01:07    01.01.2018 01:24
6   01.01.2018 01:33    01.01.2018 01:38
7   01.01.2018 01:34    01.01.2018 01:47
8   01.01.2018 01:37    01.01.2018 01:41
9   01.01.2018 01:38    01.01.2018 01:41
10  01.01.2018 01:39    01.01.2018 01:55

I would like to count how many starts (intervals) are active at the same time before they end at given time (in other words: how many times each row overlaps with the rest of the rows).

E.g. from 00:47 to 00:52 only one is active, from 00:52 to 00:54 two, from 00:54 to 00:55 only one again, and so on.

I tried to stack columns onto each other, sort by date and by iterrating through whole dataframe give each "start" +1 to counter and -1 to each "end". It works but on my original data frame, where I have few millions of rows, iteration takes forever - I need to find a quicker way.

My original basic-and-not-very-good code:

import pandas as pd
import numpy as np

df = pd.read_csv('something.csv', sep=';')

df = df.stack().to_frame()
df = df.reset_index(level=1)
df.columns = ['status', 'time']
df = df.sort_values('time')
df['counter'] = np.nan
df = df.reset_index().drop('index', axis=1)

print(df.head(10))

gives:

    status  time                counter
0   start   01.01.2018 00:47    NaN
1   start   01.01.2018 00:52    NaN
2   stop    01.01.2018 00:54    NaN
3   start   01.01.2018 00:55    NaN
4   start   01.01.2018 00:57    NaN
5   stop    01.01.2018 00:59    NaN
6   start   01.01.2018 01:00    NaN
7   stop    01.01.2018 01:03    NaN
8   start   01.01.2018 01:07    NaN
9   stop    01.01.2018 01:12    NaN

and:

counter = 0

for index, row in df.iterrows():

    if row['status'] == 'start':
        counter += 1
    else:
        counter -= 1
    df.loc[index, 'counter'] = counter

final output:

        status  time                counter
    0   start   01.01.2018 00:47    1.0
    1   start   01.01.2018 00:52    2.0
    2   stop    01.01.2018 00:54    1.0
    3   start   01.01.2018 00:55    2.0
    4   start   01.01.2018 00:57    3.0
    5   stop    01.01.2018 00:59    2.0
    6   start   01.01.2018 01:00    3.0
    7   stop    01.01.2018 01:03    2.0
    8   start   01.01.2018 01:07    3.0
    9   stop    01.01.2018 01:12    2.0

Is there any way i can do this by NOT using iterrows()?

Thanks in advance!

Body:
Use Series.cumsum with Series.map (or Series.replace):

new_df = df.melt(var_name = 'status',value_name = 'time').sort_values('time')
new_df['counter'] = new_df['status'].map({'start':1,'end':-1}).cumsum()
print(new_df)
   status                time  counter
0   start 2018-01-01 00:47:00        1
1   start 2018-01-01 00:52:00        2
11    end 2018-01-01 00:54:00        1
2   start 2018-01-01 00:55:00        2
3   start 2018-01-01 00:57:00        3
13    end 2018-01-01 00:59:00        2
4   start 2018-01-01 01:00:00        3
12    end 2018-01-01 01:03:00        2
5   start 2018-01-01 01:07:00        3
15    end 2018-01-01 01:12:00        2
14    end 2018-01-01 01:16:00        1
16    end 2018-01-01 01:24:00        0
6   start 2018-01-01 01:33:00        1
7   start 2018-01-01 01:34:00        2
8   start 2018-01-01 01:37:00        3
9   start 2018-01-01 01:38:00        4
17    end 2018-01-01 01:38:00        3
10  start 2018-01-01 01:39:00        4
19    end 2018-01-01 01:41:00        3
20    end 2018-01-01 01:41:00        2
18    end 2018-01-01 01:47:00        1
21    end 2018-01-01 01:55:00        0

We could also use numpy.cumsum:

new_df['counter'] = np.where(new_df['status'].eq('start'),1,-1).cumsum()


问:
Named export / unnamed export
I currently follow this tutorial here which uses:

```<code>import { AUTH_TOKEN } from '../constants'
</code>```

While I followed the tutorial step-by-step I have to use

```<code>import AUTH_TOKEN from '../constants'
</code>```

My constants.js looks like this:

```<code>export const AUTH_TOKEN = "auth-token";
</code>```

I struggle to understand why my React.js app behaves the opposite.

答:
Following is called named import and named export

```<code>import { AUTH_TOKEN } from '../constants' // importing in file A
export const AUTH_TOKEN = "tokenValue"    // exporting from file B
</code>```

In above method you use {} and same name for import and export

```<code>import  MY_AUTH_TOKEN  from '../constants' // importing in file A
export default const AUTH_TOKEN = "tokenValue" exporting from file B
</code>```

In above method you do not use {} and name does not matter.

Find the good read for understanding the concept further.

Title: Named export / unnamed export

Body:
I currently follow this tutorial here which uses:

import { AUTH_TOKEN } from '../constants'

While I followed the tutorial step-by-step I have to use

import AUTH_TOKEN from '../constants'

My constants.js looks like this:

export const AUTH_TOKEN = "auth-token";

I struggle to understand why my React.js app behaves the opposite.

Body:
Following is called named import and named export

import { AUTH_TOKEN } from '../constants' // importing in file A
export const AUTH_TOKEN = "tokenValue"    // exporting from file B

In above method you use {} and same name for import and export

import  MY_AUTH_TOKEN  from '../constants' // importing in file A
export default const AUTH_TOKEN = "tokenValue" exporting from file B

In above method you do not use {} and name does not matter.

Find the good read for understanding the concept further.


问:
Kubernetes-dashboard empty : every resources are forbidden
It seems I have a very common problem but I cannot figure it out.

On a new kubernetes cluster (v1.17) I'm trying to install Kubernetes-dashboard.

For this I followed the official steps, starting by installing the dashboard :

```<code>kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0-rc5/aio/deploy/recommended.yaml
</code>```

Then I created the ServiceAccount

```<code>apiVersion: v1
kind: ServiceAccount
metadata:
  name: admin-user
  namespace: kubernetes-dashboard
</code>```

And the ClusterRoleBinding

```<code>apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: admin-user
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
- kind: ServiceAccount
  name: admin-user
  namespace: kubernetes-dashboard
</code>```

Everything is running smoothly and all the objets get created (I can get them and everything looks alright)

After running kubectl proxy the dashboard is accessible at this URL :

```<code>http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/
</code>```

Then I enter the token I got with this command :

```<code>kubectl -n kubernetes-dashboard describe secret $(kubectl -n kubernetes-dashboard get secret | grep admin-user-token | awk '{print $1}')
</code>```

I can login, but the dashboard is empty. The notifications panel is full of

[OBJECT] is forbidden: User "system:serviceaccount:kubernetes-dashboard:admin-user" cannot list resource "[OBJECT]" in API group "extensions" in the namespace "default"

Replace [OBJECT] with every kubernetes object and you have a good overview of my notifications panel ;)

The admin-user has obviously not enough rights to access the objects.

Questions

Did I miss something ?

How can I debug this situation ?

Thank you for your help !

Edit: That was an outage from my cloud provider. I don't know what happened nor how they solved it but they did something and everything is working now.

答: In the end, that was an outage from the cloud provider. I ran into another problem with PVC, they solved it and tadaa the dashboard is working just fine with no modifications.</p>

Body:
It seems I have a very common problem but I cannot figure it out.

On a new kubernetes cluster (v1.17) I'm trying to install Kubernetes-dashboard.

For this I followed the official steps, starting by installing the dashboard :

kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0-rc5/aio/deploy/recommended.yaml

Then I created the ServiceAccount

apiVersion: v1
kind: ServiceAccount
metadata:
  name: admin-user
  namespace: kubernetes-dashboard

And the ClusterRoleBinding

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: admin-user
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
- kind: ServiceAccount
  name: admin-user
  namespace: kubernetes-dashboard

Everything is running smoothly and all the objets get created (I can get them and everything looks alright)

After running kubectl proxy the dashboard is accessible at this URL :

http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/

Then I enter the token I got with this command :

kubectl -n kubernetes-dashboard describe secret $(kubectl -n kubernetes-dashboard get secret | grep admin-user-token | awk '{print $1}')

I can login, but the dashboard is empty. The notifications panel is full of

[OBJECT] is forbidden: User "system:serviceaccount:kubernetes-dashboard:admin-user" cannot list resource "[OBJECT]" in API group "extensions" in the namespace "default"

Replace [OBJECT] with every kubernetes object and you have a good overview of my notifications panel ;)

The admin-user has obviously not enough rights to access the objects.

Questions

Did I miss something ?

How can I debug this situation ?

Thank you for your help !

Edit: That was an outage from my cloud provider. I don't know what happened nor how they solved it but they did something and everything is working now.


问:
"Class 'XMLWriter' not found" Error in php | php55w-xml-5.5.24-1.w6.x86_64.rpm is missing
I am getting this error in PHP in server Fatal Error (E_ERROR): Class 'XMLWriter' not found . we are using Cent OS 6

After exploring some sites, we found that we need to install php55w-xml-5.5.24-1.w6.x86_64.rpm. But the link is not working, I am not able to get this package. we are using PHP 5.5.24. We can not upgrade our PHP because of dependency with other products.Can we resolve this error without upgrading the PHP. Thanks !!!

UPDATE: we are using https://rollbar.com/ for error handing.

答:
Install php7-xmlwriter

yum install php-7xmlwriter


问:
How can I change the choices in a pickerview based on another pickervew?
Picture of current versionI currently have two picker views. Ones a country picker view(US and Canada) and the other is a state picker view. I'd like to have it so when USA is selected it displays US states, and when Canada is selected, Canadian provinces are displayed. Here is a sample of what I have so far. Help would be very much appreciated!

Edit: Still haven't found any working solutions, any help would be appreciated!

```<code>let countries = ["",
"USA",
"Canada",
]
let states = ["Alaska",
"Alabama",
"Arkansas"]
 let provinces = ["Alberta",
"British Columbia",
"Manitoba",
"New Brunswick"]

//Sets picker view
let pickerView = UIPickerView()
//Holds current data in array
var currentArray: [String] = []
//Holds current text field
var activeTextField : UITextField!
var activeField: UITextField?

 fileprivate func delegates() {
  countryTextView.delegate = self
  stateTextView.delegate = self
}

fileprivate func pickerViewDelegates() {
    //Enables pickerview
    pickerView.delegate = self
    pickerView.dataSource = self
}
//Sets pickerview input
fileprivate func pickerViewSet() {
    countryTextView.inputView = pickerView
    stateTextView.inputView = pickerView
}
//Closes keyboard when done button is pressed
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}
//Textfield delegate
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    activeTextField = textField

    switch textField {
    case countryTextView:
        currentArray = countries
    case stateTextView:
        currentArray = states
    default:
        print("Default")
    }
    pickerView.reloadAllComponents()
    return true
}
//Number of rows in picker view
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}
//One element of array per row
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return currentArray.count
}
//Puts the array element of whichever picker view is chosen into picker view
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{
    return currentArray[row]
}
//Selects the array element in the row thats chosen
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    print("Selected item is", currentArray[row])
    activeTextField.text = currentArray[row]
}
</code>```

答:
i do not say my code is "nice". It just works as what you want (as far as i understood you)

if you change from Blubb to USA the second picker will update.

```<code>class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

let countries = ["Blubb",
                 "USA",
                 "Canada",
]
let states = ["Alaska",
              "Alabama",
              "Arkansas"]

let statesCan = ["1", "2"]

//Sets picker view
let pickerView = UIPickerView()
let pickerView2 = UIPickerView()
//Holds current data in array
var currentArray: [String] = []
//Holds current text field
var activeTextField : UITextField!
var activeField: UITextField?

fileprivate func delegates() {
//        countryTextView.delegate = self
//        stateTextView.delegate = self
}

fileprivate func pickerViewDelegates() {
    //Enables pickerview
    pickerView.delegate = self
    pickerView.dataSource = self

    pickerView2.delegate = self
    pickerView2.dataSource = self
}
//Sets pickerview input
fileprivate func pickerViewSet() {
//        countryTextView.inputView = pickerView
 //        stateTextView.inputView = pickerView
}
//Closes keyboard when done button is pressed
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

//Number of rows in picker view
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}
//One element of array per row
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if pickerView == self.pickerView2 {
        return currentArray.count
    } else {
        return countries.count
    }
}
//Puts the array element of whichever picker view is chosen into picker view
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{
    if pickerView == self.pickerView2 {
        return currentArray[row]
    } else {
        return countries[row]
    }
}
//Selects the array element in the row thats chosen
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if pickerView == self.pickerView {
        if row == 0 {
            currentArray = states
        } else {
            currentArray = statesCan
        }
        pickerView2.reloadAllComponents()
    }
//     activeTextField.text = currentArray[row]
}

override func viewDidLoad() {
    super.viewDidLoad()

    currentArray = states

    pickerViewDelegates()
    self.view.addSubview(pickerView)
    self.view.addSubview(pickerView2)

    pickerView2.frame.origin.y = 400

    }

}
</code>```

Body:
Picture of current versionI currently have two picker views. Ones a country picker view(US and Canada) and the other is a state picker view. I'd like to have it so when USA is selected it displays US states, and when Canada is selected, Canadian provinces are displayed. Here is a sample of what I have so far. Help would be very much appreciated!

Edit: Still haven't found any working solutions, any help would be appreciated!

let countries = ["",
"USA",
"Canada",
]
let states = ["Alaska",
"Alabama",
"Arkansas"]
 let provinces = ["Alberta",
"British Columbia",
"Manitoba",
"New Brunswick"]

//Sets picker view
let pickerView = UIPickerView()
//Holds current data in array
var currentArray: [String] = []
//Holds current text field
var activeTextField : UITextField!
var activeField: UITextField?

 fileprivate func delegates() {
  countryTextView.delegate = self
  stateTextView.delegate = self
}

fileprivate func pickerViewDelegates() {
    //Enables pickerview
    pickerView.delegate = self
    pickerView.dataSource = self
}
//Sets pickerview input
fileprivate func pickerViewSet() {
    countryTextView.inputView = pickerView
    stateTextView.inputView = pickerView
}
//Closes keyboard when done button is pressed
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}
//Textfield delegate
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    activeTextField = textField

    switch textField {
    case countryTextView:
        currentArray = countries
    case stateTextView:
        currentArray = states
    default:
        print("Default")
    }
    pickerView.reloadAllComponents()
    return true
}
//Number of rows in picker view
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}
//One element of array per row
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return currentArray.count
}
//Puts the array element of whichever picker view is chosen into picker view
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{
    return currentArray[row]
}
//Selects the array element in the row thats chosen
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    print("Selected item is", currentArray[row])
    activeTextField.text = currentArray[row]
}

Body:
i do not say my code is "nice". It just works as what you want (as far as i understood you)

if you change from Blubb to USA the second picker will update.

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

let countries = ["Blubb",
                 "USA",
                 "Canada",
]
let states = ["Alaska",
              "Alabama",
              "Arkansas"]

let statesCan = ["1", "2"]

//Sets picker view
let pickerView = UIPickerView()
let pickerView2 = UIPickerView()
//Holds current data in array
var currentArray: [String] = []
//Holds current text field
var activeTextField : UITextField!
var activeField: UITextField?

fileprivate func delegates() {
//        countryTextView.delegate = self
//        stateTextView.delegate = self
}

fileprivate func pickerViewDelegates() {
    //Enables pickerview
    pickerView.delegate = self
    pickerView.dataSource = self

    pickerView2.delegate = self
    pickerView2.dataSource = self
}
//Sets pickerview input
fileprivate func pickerViewSet() {
//        countryTextView.inputView = pickerView
 //        stateTextView.inputView = pickerView
}
//Closes keyboard when done button is pressed
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

//Number of rows in picker view
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}
//One element of array per row
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if pickerView == self.pickerView2 {
        return currentArray.count
    } else {
        return countries.count
    }
}
//Puts the array element of whichever picker view is chosen into picker view
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{
    if pickerView == self.pickerView2 {
        return currentArray[row]
    } else {
        return countries[row]
    }
}
//Selects the array element in the row thats chosen
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if pickerView == self.pickerView {
        if row == 0 {
            currentArray = states
        } else {
            currentArray = statesCan
        }
        pickerView2.reloadAllComponents()
    }
//     activeTextField.text = currentArray[row]
}

override func viewDidLoad() {
    super.viewDidLoad()

    currentArray = states

    pickerViewDelegates()
    self.view.addSubview(pickerView)
    self.view.addSubview(pickerView2)

    pickerView2.frame.origin.y = 400

    }

}


问:
Using the value of Javascript variable in django template to render template context
Please do not mark this question as invalid. I didn't find any question in stackoverflow with the problem mentioned below.

I have a django template. I pass the following context to it

```<code>context = {
'1_title': 'Title 1',
'2_title': 'Title 2',
'3_title': 'Title 3',
'4_title': 'Title 4',
}
return render(request, 'index.html', context)
</code>```

I have a HTML file where I have a dropdown. The dropdown have values like 1,2,3,4. I have registered a onClick function to it.

I need to achieve this functionality. I will get the value in onClick function. Then I will concatenate the received value with _title and store to it a javascript variable. Now I need to use that javascript variable to reference django context. I am not able to achieve this. I have googled and did extensive searching in stackoverflow. None seem to answer my question.

The javascript function looks like this:

```<code>function getContextValue(value) {
var key = value + '_title';
return {{ key }}
}
</code>```

If I select 1 in the dropdown, then the above function will have key as 1_title. I need to return the 1_title value from context which is Title 1.

For me it doesn't work and returns 1_title only. I have even tried return {{ 'key' }} . In this it returns key.

Stackoverflow community please be kind. This may be a simple question for you but not for me.

答:
If you wann access the context infos in JS you need to deliver it to JS somehow.

Change your context to something like this for easier access in the template.

```<code>context = {}
context['data_for_select'] = {
'1_title': 'Title 1',
'2_title': 'Title 2',
'3_title': 'Title 3',
'4_title': 'Title 4',
}
return render(request, 'index.html', context)
</code>```

I assume you have something like this in the template:

```<code><select name="dropdown">
  {% for key, title in data_for_select.items %}
    <option value="{{key}}">{{title}}</option>
  {% endfor %}
</select>
</code>```

You can now render the context data somewhere in the DOM for your JS method.
Django provides a handy template filter called json_script https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#json-script

```<code>{{ data_for_select|json_script:"select-data" }}
</code>```

You can use it in JS like:

```<code>var data = JSON.parse(document.getElementById('select-data').textContent);
</code>```

This way you have exposed your template context data to JS.

Body:
Please do not mark this question as invalid. I didn't find any question in stackoverflow with the problem mentioned below.

I have a django template. I pass the following context to it

context = {
'1_title': 'Title 1',
'2_title': 'Title 2',
'3_title': 'Title 3',
'4_title': 'Title 4',
}
return render(request, 'index.html', context)

I have a HTML file where I have a dropdown. The dropdown have values like 1,2,3,4. I have registered a onClick function to it.

I need to achieve this functionality. I will get the value in onClick function. Then I will concatenate the received value with _title and store to it a javascript variable. Now I need to use that javascript variable to reference django context. I am not able to achieve this. I have googled and did extensive searching in stackoverflow. None seem to answer my question.

The javascript function looks like this:

function getContextValue(value) {
var key = value + '_title';
return {{ key }}
}

If I select 1 in the dropdown, then the above function will have key as 1_title. I need to return the 1_title value from context which is Title 1.

For me it doesn't work and returns 1_title only. I have even tried return {{ 'key' }} . In this it returns key.

Stackoverflow community please be kind. This may be a simple question for you but not for me.

Body:
If you wann access the context infos in JS you need to deliver it to JS somehow.

Change your context to something like this for easier access in the template.

context = {}
context['data_for_select'] = {
'1_title': 'Title 1',
'2_title': 'Title 2',
'3_title': 'Title 3',
'4_title': 'Title 4',
}
return render(request, 'index.html', context)

I assume you have something like this in the template:

<select name="dropdown">
  {% for key, title in data_for_select.items %}
    <option value="{{key}}">{{title}}</option>
  {% endfor %}
</select>

You can now render the context data somewhere in the DOM for your JS method.
Django provides a handy template filter called json_script https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#json-script

{{ data_for_select|json_script:"select-data" }}

You can use it in JS like:

var data = JSON.parse(document.getElementById('select-data').textContent);

This way you have exposed your template context data to JS.


问:
Predefined type 'System.ValueTuple`2' is not defined or imported
I have a .NET solution file with about 20 C# projects. All of them are targeting .NET Framework 4.6.2. Within a couple of projects, I can easily write var t = ("hello", "world"); and the compiler is happy. But within some projects of the same solution, the compilation fails with Predefined type System.ValueTuple`2 is not defined or imported for the exact same piece of code.

I've already checked the following things:

There is no mscorlib.dll anywhere in the solution or project directories.

bin and obj have been deleted several times.

Problem can be reproduced on a colleagues computer.

Not a single project is using the NuGet package System.ValueTuple.

I did a text search across all *.csproj files for ValueTuple without any match.

I know that there are dozens of articles related to this error. But most of them are just saying: install the NuGet package or update your .NET Framework version. Unfortunately, none of them seems to cover the problem I'm encountering. Rather than installing or upgrading anything, I'd like to understand the behavior.

答:
I finally found the culprit: there is one project targeting .NET Standard 2.0. Every .NET Framework project referencing the .NET Standard project automatically gets a reference to System.ValueTuple.dll from the GAC (in my case, this is .NET Framework 4.7.2).

Each project without referencing the .NET Standard project does not have the reference. Therefore, the snippet var t = ("hello", "world"); cannot be used.


问:
How do you organize your code for Angular app? (code organisation patterns)
I am struggling with the best pattern for code structure in my Angular app.

I have a project which contains more modules; every module has components tests, etc..

```<code>/app
    /commons
        /components
        /constants
            constant-1.constant.ts
            constant-2.constant.ts
            constant-3.constant.ts
            constant-4.constant.ts
            ...
        /helpers
            helper-1.helper.ts
            helper-2.helper.ts
            ...
    /module-name-1
         /commons
             /helpers
             /constants
         /component-name-1
            /component-name-subcomponent-1
               component-name-subcomponent-1.component.ts
         /component-name-2
            component-name-subcomponent-2.component.ts
         module-name-1.module.ts
         module-name-1-routing.module.ts
</code>```

This is how my code organization looks like. I would like to ask you, how do you struggle with some shared/common parts as constants/functions/helpers... Eg. constants - I tried to keep shared constants in one folder in the module, or if they are shared between modules, in the app path. But sometimes, I use constant just in one component, or 2 of them, and then I have followed by components tree to some far away shared folder where i have defined two lines of code. The same with interfaces - i keep all of them in one folder, but sometimes interface is used just in one component, or sometimes in their childs. How do you organize it? What is the best practice for bigger projects?

I wonder about one commons/ folder in-app route, with the similar structure as rest of app /module/component/ and there keeps interfaces and constants related to the components and keep a common path to them - but when I tried it - it also messed, and there are no helpful tools to manage it.

Any suggestions?

答:
Personally I like a structure like this:</p>

```<code>/app
    /components
        /page-components
            /home
            /contact
        /page-element-components
            /form
               ...
               ...
            /pop-ups
               ...
               ...
            /wizards
               ...
    /Services
        /global-services
            ...
            ...
        /http-services
            ...
            ...
    /Modules
        /app.module.ts
        /lazy-modules
            ...
            ...
        /shared-modules
            ...
            ...
    /Utils
        /helpers
            ...
            ...
        /form-validators
        /pipes
    /Assets
        /global-styling
        /icons
</code>```

Body:
I am struggling with the best pattern for code structure in my Angular app.

I have a project which contains more modules; every module has components tests, etc..

/app
    /commons
        /components
        /constants
            constant-1.constant.ts
            constant-2.constant.ts
            constant-3.constant.ts
            constant-4.constant.ts
            ...
        /helpers
            helper-1.helper.ts
            helper-2.helper.ts
            ...
    /module-name-1
         /commons
             /helpers
             /constants
         /component-name-1
            /component-name-subcomponent-1
               component-name-subcomponent-1.component.ts
         /component-name-2
            component-name-subcomponent-2.component.ts
         module-name-1.module.ts
         module-name-1-routing.module.ts

This is how my code organization looks like. I would like to ask you, how do you struggle with some shared/common parts as constants/functions/helpers... Eg. constants - I tried to keep shared constants in one folder in the module, or if they are shared between modules, in the app path. But sometimes, I use constant just in one component, or 2 of them, and then I have followed by components tree to some far away shared folder where i have defined two lines of code. The same with interfaces - i keep all of them in one folder, but sometimes interface is used just in one component, or sometimes in their childs. How do you organize it? What is the best practice for bigger projects?

I wonder about one commons/ folder in-app route, with the similar structure as rest of app /module/component/ and there keeps interfaces and constants related to the components and keep a common path to them - but when I tried it - it also messed, and there are no helpful tools to manage it.

Any suggestions?

Body:
Personally I like a structure like this:

/app
    /components
        /page-components
            /home
            /contact
        /page-element-components
            /form
               ...
               ...
            /pop-ups
               ...
               ...
            /wizards
               ...
    /Services
        /global-services
            ...
            ...
        /http-services
            ...
            ...
    /Modules
        /app.module.ts
        /lazy-modules
            ...
            ...
        /shared-modules
            ...
            ...
    /Utils
        /helpers
            ...
            ...
        /form-validators
        /pipes
    /Assets
        /global-styling
        /icons


问:
Odd problem I keep having, wondering if its because I use types with same name as namespace?
UPDATE:

I ended up solving this in a way I did not expect - it apparently was not the namespace/typename collision I thought it was (to my surprise when I re-did it and it failed the exact same way).  I think maybe this is minor VS bug - here's what happened:

--> The error path

I added a Winforms project

I added a reference to Lib1

Lib1 appeared as an added reference

(I revise my estimate of exactly when VS gets "confused") The next time I compile, things get broken and it's as if I never added the reference to Lib1.

--> Surprising way I ended up resolving the issue:

I was taking random shots because I was confused and I decided to add the library a (slightly) different way.

Instead of right clicking the References node in the Solution Explorer and choosing Lib1 from the "solutions" tab, I chose it from the "Recent" tab.

When I added it, to my surprise, VS complained that it could not add the library

The reason was my Library was set to .NET 4 and my Winforms app defaulted to Client profile.

--> the issue was resolved when I switched my winforms app to .NET 4

Background/Motivation:

I'm a lone developer - which is why when I have strangnesses like this one, I sometimes spend 20 minutes and if I can't figure it out I completely work around it.  Sometimes these problems recur, and I spend another 20 minutes, and become annoyed with the workaround a second time, which finally makes me really want to figure it out.  This is the case now.

Description of the Problem:

I'm coding along, in this case, I was prototyping an ASP.NET website with VS10.

new project, ASP.NET website: Web1 (creates solution)

add Project, C# library, Lib1 (adds to solution)

Lib1: add Model.cs, View.cs, Presenter.cs, ...etc

Web1: add a DataList to Default.aspx, bind data via Lib1

Test it it works

---> Now I want to see my Lib1 work for a winforms project, basically proving to myself I can write Library code that doesn't care about the UI

add Project, WinformsApp1 (adds to solution)

add a DataGridView to Form1, bind data via Lib1

Then the wierdest thing happend (at least to me): At first, adding a reference to Lib1 and implementing the IView interface on Form1 works fine, but as soon as VS auto populates the stubs for IView, everything goes to a state as if I didn't add the reference to Lib1.  That is, the compiler tells me it doesn't know the definition of IView, and politely reminds me that I might have forgotten to add a reference, but the kicker is that it's talking about the code that it just generated and would not have been able to without that reference.

NOTE: If nobody knows just what this is and I'm wrong that this is a symptom of lone developer syndrome, I'll work up the example again and post the code (I just zapped it).

答: It sounds like you have a method in your interface that has the same name as the namespace, so when you populated the interface the compiler could no longer differentiate between the namespace and the method.</p>


问:
Can Azure Functions be deployed to a Vnet?
Can Azure Functions be deployed inside a VNet?

If I created an App Service environment in a VNet and then picked that App Service Plan when creating the Function, Would that mean that the Azure Function is deployed inside the VNet and have the same restrictions etc. as defined by the VNet?

答:
Yes it can be deployed inside a VNet. I would recommend you to go through the documentation
integrate Functions with an Azure virtual network

An Azure Function can be deployed on an App Service Environment. The App Service Environment is deployed on your own VNET which can have access to on-prem resources via ExpressRoute.


问:
Reverse Bits JavaScript
The problem is standard but the solution in JavaScript takes a lot more effort to code.

I got the solution but my answer is coming half of what is desired.

Problem Description

Reverse the bits of a 32-bit unsigned integer A.

Problem Constraints

0 <= A <= 2^32

Input Format

The first and only argument of input contains an integer A.

Output Format

Return a single unsigned integer denoting minimum xor value.

Example Input

```<code>Input 1:
0
Input 2:
3
</code>```

Example Output

```<code>Output 1:
0
Output 2:
3221225472
</code>```

My solution

```<code>
function modulo(a, b) {
        return a - Math.floor(a/b)*b;
}
function ToUint32(x) {
    return modulo(parseInt(x), Math.pow(2, 32));
}
function revereBits(A){
    A = A.toString(2);
    while (A.length < 31){
        A = "0"+A;
    }
    var reverse = 0;
    var NO_OF_BITS = A.length;
    for(var i = NO_OF_BITS; i >= 1; i--){
        var temp = (parseInt(A, 2) & (1 << i - 1));
        if(temp){
            reverse |= 1 << (NO_OF_BITS - i);

        }
    }
    if( reverse << 1 < 0 ) reverse = ToUint32(reverse << 1);
    return reverse;

}
</code>```

Now, in the line

```<code> if( reverse << 1 < 0 ) reverse = ToUint32(reverse << 1);
</code>```

You see that I  have to double the answer. I cannot, however, get the part of why is this required.

I took the approach from https://www.geeksforgeeks.org/write-an-efficient-c-program-to-reverse-bits-of-a-number/

Had to make few adjustments to it. For example, run the loop from 31 to 1 rather than 0 to 31. The latter gives negative values in first left shift operation for i = 0 itself.

Can someone please help in fixing this solution and point to the problem in this?

UPDATE - Problem is related to Bit manipulation. So guys, please don't answer or comment for anything consisting of in-built string functions of Javascript. Cheers!

答:
Try this:</p>

```<code>function reverseBits(num) {

    let reversed = num.toString(2);
    const padding = "0";
    reversed = padding.repeat(32 - reversed.length) + reversed;
    return parseInt(reversed.split('').reverse().join(''), 2);
}

console.log(reverseBits(0)); // 0
console.log(reverseBits(3)); // 3221225472
</code>```

Title: Reverse Bits JavaScript

Body:
The problem is standard but the solution in JavaScript takes a lot more effort to code.

I got the solution but my answer is coming half of what is desired.

Problem Description

Reverse the bits of a 32-bit unsigned integer A.

Problem Constraints

0 <= A <= 2^32

Input Format

The first and only argument of input contains an integer A.

Output Format

Return a single unsigned integer denoting minimum xor value.

Example Input

Input 1:
0
Input 2:
3

Example Output

Output 1:
0
Output 2:
3221225472

My solution

function modulo(a, b) {
        return a - Math.floor(a/b)*b;
}
function ToUint32(x) {
    return modulo(parseInt(x), Math.pow(2, 32));
}
function revereBits(A){
    A = A.toString(2);
    while (A.length < 31){
        A = "0"+A;
    }
    var reverse = 0;
    var NO_OF_BITS = A.length;
    for(var i = NO_OF_BITS; i >= 1; i--){
        var temp = (parseInt(A, 2) & (1 << i - 1));
        if(temp){
            reverse |= 1 << (NO_OF_BITS - i);

        }
    }
    if( reverse << 1 < 0 ) reverse = ToUint32(reverse << 1);
    return reverse;

}

Now, in the line

 if( reverse << 1 < 0 ) reverse = ToUint32(reverse << 1);

You see that I  have to double the answer. I cannot, however, get the part of why is this required.

I took the approach from https://www.geeksforgeeks.org/write-an-efficient-c-program-to-reverse-bits-of-a-number/

Had to make few adjustments to it. For example, run the loop from 31 to 1 rather than 0 to 31. The latter gives negative values in first left shift operation for i = 0 itself.

Can someone please help in fixing this solution and point to the problem in this?

UPDATE - Problem is related to Bit manipulation. So guys, please don't answer or comment for anything consisting of in-built string functions of Javascript. Cheers!

Body:
Try this:

function reverseBits(num) {

    let reversed = num.toString(2);
    const padding = "0";
    reversed = padding.repeat(32 - reversed.length) + reversed;
    return parseInt(reversed.split('').reverse().join(''), 2);
}

console.log(reverseBits(0)); // 0
console.log(reverseBits(3)); // 3221225472


问:
Cannot perform @Autowired a bean on integration Test for SpringBoot
I have an application on SpringBoot 2.x

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
public class WebSpringBootJarApplication extends SpringBootServletInitializer implements WebApplicationInitializer {

    public static void main(String[] args) {
        SpringApplication.run(WebSpringBootJarApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(WebSpringBootJarApplication.class);
    }
}
```

<p>pom.xml</p>

<pre class="lang-xml prettyprint-override"><code>    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>weblogic.war.spring.boot</groupId>
    <artifactId>weblogic-war-spring-boot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>weblogic-war-spring-boot</name>
    <packaging>war</packaging>
</code>```

This is the class that should be autowired...

@Service
public class CompanyReadServiceImpl implements CompanyReadService {

    private CompanyMapper companyMapper;

    private CompanyReadRepository companyReadRepository;

    @Autowired
    public CompanyReadServiceImpl(CompanyMapper companyMapper,
                                  CompanyReadRepository companyReadRepository) {
        this.companyMapper = companyMapper;
        this.companyReadRepository = companyReadRepository;
    }

    @Transactional
    @Override
    public CompanyDto getById(Long id) {

        Company company = find(id);

        return transform(company);
    }

    @Transactional
    @Override
    public boolean isByName(String name) {
        return this.companyReadRepository.findByName(name).isPresent();
    }

    @Transactional
    @Override
    public CompanyDto getByName(String name) {

        Company company = companyReadRepository.findByName(name).orElse(new Company());

        return transform(company);

    }

    private Company find(Long id){

       return this.companyReadRepository.findById(id).orElseThrow(() -> new RuntimeException("User not found"));
    }

    private CompanyDto transform(Company company){

        return this.companyMapper.companyToCompanyDto(company);
    }
}
```

<p>pom.xml</p>

<pre class="lang-xml prettyprint-override"><code> <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
         </dependency>
</code>```

update

This class is from similar project and It work (but Intellij idea mark the fields as mistakes)

in the src/test/java/weblogic/war/spring/boot/service/read/CompanyReadServiceTest.java

@RunWith(SpringRunner.class)
@SpringBootTest
public class CompanyReadServiceTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(CompanyReadServiceTest.class);

    private static String NAME_METHOD_READ_BY_NAME_BOOLEAN = "isByName";

    @Autowired
    private CompanyReadRepository companyReadRepository;

    @Autowired
    private CompanyReadService companyReadService;

    @Autowired
    private CompanyReadRepositoryTest companyReadRepositoryTest;

    @Autowired
    private CompanyMapper companyMapper;

    @Test
    public void getById() {

        Company lastEntry = getLastEntry();

        Long idExpected = null;
        if(lastEntry != null) idExpected = lastEntry.getId();

        if(idExpected != null){

            CompanyDto companyDto = searchByIdEntry(idExpected);
            Long idActual = companyDto.getId();

            Assert.assertEquals("Lookup of entry - failed!!!", idExpected, idActual );
        }

    }

    @Test
    public void isByName() {

        Company lastEntry = getLastEntry();

        String name = null;
        if(lastEntry != null) name = lastEntry.getName();

        if(name != null){
            boolean entryByName = isEntryByName(name);
            Assert.assertTrue("Lookup of entry - failed", entryByName);
        }
    }

    private CompanyDto searchByIdEntry(Long id){

        return this.companyReadService.getById(id);
    }

    private boolean isEntryByName(String name){

        return getByNameReflection(companyReadService, NAME_METHOD_READ_BY_NAME_BOOLEAN, name);
    }

    private Company getLastEntry() {

        Optional<Company> lastEntry = companyReadRepositoryTest.getLastEntry();

        return lastEntry.orElse(null);
    }

}
```

I make a copy a project.

update_2

I cleared the local Maven storage.
The IDE also (at compile time ) highlights fields that are presumably not automatically connected. but I run a test class and it works ...

Why? (This may have started when I just renamed the package and edited the pom.xml)

Autowiring occur good in working scope  the app. but It doesn't work in testing scope the app.

Who can share ideas on this issue ?

答:
You are trying to load actual application context for Junit purpose.
you can do that using below Where WebSpringBootJarApplication class is the original Spring context</p>

```<code>@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {WebSpringBootJarApplication.class})
public class HelloWorldTest {

@Autowired(required = true)
SomeService service;

@Test
public void helloTest() {
    System.out.println(service);
}
}
</code>```

Body:
I have an application on SpringBoot 2.x

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
public class WebSpringBootJarApplication extends SpringBootServletInitializer implements WebApplicationInitializer {

    public static void main(String[] args) {
        SpringApplication.run(WebSpringBootJarApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(WebSpringBootJarApplication.class);
    }
}

pom.xml

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/>
    </parent>

    <groupId>weblogic.war.spring.boot</groupId>
    <artifactId>weblogic-war-spring-boot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>weblogic-war-spring-boot</name>
    <packaging>war</packaging>

This is the class that should be autowired...

@Service
public class CompanyReadServiceImpl implements CompanyReadService {

    private CompanyMapper companyMapper;

    private CompanyReadRepository companyReadRepository;

    @Autowired
    public CompanyReadServiceImpl(CompanyMapper companyMapper,
                                  CompanyReadRepository companyReadRepository) {
        this.companyMapper = companyMapper;
        this.companyReadRepository = companyReadRepository;
    }

    @Transactional
    @Override
    public CompanyDto getById(Long id) {

        Company company = find(id);

        return transform(company);
    }

    @Transactional
    @Override
    public boolean isByName(String name) {
        return this.companyReadRepository.findByName(name).isPresent();
    }

    @Transactional
    @Override
    public CompanyDto getByName(String name) {

        Company company = companyReadRepository.findByName(name).orElse(new Company());

        return transform(company);

    }

    private Company find(Long id){

       return this.companyReadRepository.findById(id).orElseThrow(() -> new RuntimeException("User not found"));
    }

    private CompanyDto transform(Company company){

        return this.companyMapper.companyToCompanyDto(company);
    }
}

pom.xml

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
         </dependency>

update

This class is from similar project and It work (but Intellij idea mark the fields as mistakes)

in the src/test/java/weblogic/war/spring/boot/service/read/CompanyReadServiceTest.java

@RunWith(SpringRunner.class)
@SpringBootTest
public class CompanyReadServiceTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(CompanyReadServiceTest.class);

    private static String NAME_METHOD_READ_BY_NAME_BOOLEAN = "isByName";

    @Autowired
    private CompanyReadRepository companyReadRepository;

    @Autowired
    private CompanyReadService companyReadService;

    @Autowired
    private CompanyReadRepositoryTest companyReadRepositoryTest;

    @Autowired
    private CompanyMapper companyMapper;

    @Test
    public void getById() {

        Company lastEntry = getLastEntry();

        Long idExpected = null;
        if(lastEntry != null) idExpected = lastEntry.getId();

        if(idExpected != null){

            CompanyDto companyDto = searchByIdEntry(idExpected);
            Long idActual = companyDto.getId();

            Assert.assertEquals("Lookup of entry - failed!!!", idExpected, idActual );
        }

    }

    @Test
    public void isByName() {

        Company lastEntry = getLastEntry();

        String name = null;
        if(lastEntry != null) name = lastEntry.getName();

        if(name != null){
            boolean entryByName = isEntryByName(name);
            Assert.assertTrue("Lookup of entry - failed", entryByName);
        }
    }

    private CompanyDto searchByIdEntry(Long id){

        return this.companyReadService.getById(id);
    }

    private boolean isEntryByName(String name){

        return getByNameReflection(companyReadService, NAME_METHOD_READ_BY_NAME_BOOLEAN, name);
    }

    private Company getLastEntry() {

        Optional<Company> lastEntry = companyReadRepositoryTest.getLastEntry();

        return lastEntry.orElse(null);
    }

}

I make a copy a project.

update_2

I cleared the local Maven storage.
The IDE also (at compile time ) highlights fields that are presumably not automatically connected. but I run a test class and it works ...

Why? (This may have started when I just renamed the package and edited the pom.xml)

Autowiring occur good in working scope  the app. but It doesn't work in testing scope the app.

Who can share ideas on this issue ?

Body:
You are trying to load actual application context for Junit purpose.
you can do that using below Where WebSpringBootJarApplication class is the original Spring context

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {WebSpringBootJarApplication.class})
public class HelloWorldTest {

@Autowired(required = true)
SomeService service;

@Test
public void helloTest() {
    System.out.println(service);
}
}


问:
Gulp Watch is not working in gulp 4.0.2 until run gulp again
In my gulfile.js, I'm using watch to compile scss files to css files. It runs without error and when I run gulp in powershell, it says that it is watching, but whenever I define a style in my scss file, it doesn't affect the css file which is created and I have to stop gulp and run it again. Actually, it's not watching carefully !
Here is my code.
Thanks for any help.

"use strict";

var gulp = require("gulp");
var sass = require("gulp-sass");
var minifyCSS = require("gulp-clean-css");
var uglify = require("gulp-uglify");
var rename = require("gulp-rename");
var changed = require("gulp-changed");
var { task, series } = require("gulp");

var SCSS_SRC = "./src/Assets/scss/**/*.scss";
var SCSS_DEST = "./src/Assets/css";

task("compile_scss", function() {

 gulp
  .src(SCSS_SRC)
  .pipe(sass().on("error", sass.logError))
  .pipe(minifyCSS())
  .pipe(rename({ suffix: ".min" }))
  .pipe(changed(SCSS_DEST))
  .pipe(gulp.dest(SCSS_DEST));
});

task("watch_scss", function() {
 gulp.watch(SCSS_SRC, series(["compile_scss"]));
});

task("default", series("watch_scss"));```

答:
For the problem be solved, as @Gabriel mentioned and according this link, I changed my code to this and the problem solved. But when I ran npm start, the watch stopped working; Therefore, I installed "concurrently" through npm and changed my start in package.json as mentioned here:

npm install concurrently

"start": "concurrently \"react-scripts start \" \"gulp \"",```
</div>
</div>
</p>

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

var gulp = require("gulp");
var sass = require("gulp-sass");
var minifyCSS = require("gulp-clean-css");
var uglify = require("gulp-uglify");
var rename = require("gulp-rename");
var changed = require("gulp-changed");
var { task, series } = require("gulp");

var SCSS_SRC = "./src/Assets/scss/**/*.scss";
var SCSS_DEST = "./src/Assets/css";

function compile_scss() {
 return gulp
  .src(SCSS_SRC)
  .pipe(sass().on("error", sass.logError))
  .pipe(minifyCSS())
  .pipe(rename({ suffix: ".min" }))
  .pipe(changed(SCSS_DEST))
  .pipe(gulp.dest(SCSS_DEST));
}

function watch_scss() {
 gulp.watch(SCSS_SRC, series(compile_scss));
}

exports.default = series(watch_scss);</code>```

Body:
For the problem be solved, as @Gabriel mentioned and according this link, I changed my code to this and the problem solved. But when I ran npm start, the watch stopped working; Therefore, I installed "concurrently" through npm and changed my start in package.json as mentioned here:

npm install concurrently

"start": "concurrently \"react-scripts start \" \"gulp \"",

"use strict";

var gulp = require("gulp");
var sass = require("gulp-sass");
var minifyCSS = require("gulp-clean-css");
var uglify = require("gulp-uglify");
var rename = require("gulp-rename");
var changed = require("gulp-changed");
var { task, series } = require("gulp");

var SCSS_SRC = "./src/Assets/scss/**/*.scss";
var SCSS_DEST = "./src/Assets/css";

function compile_scss() {
 return gulp
  .src(SCSS_SRC)
  .pipe(sass().on("error", sass.logError))
  .pipe(minifyCSS())
  .pipe(rename({ suffix: ".min" }))
  .pipe(changed(SCSS_DEST))
  .pipe(gulp.dest(SCSS_DEST));
}

function watch_scss() {
 gulp.watch(SCSS_SRC, series(compile_scss));
}

exports.default = series(watch_scss);


问:
(Swift) Pass data into another viewController using callBack function
Situation:

I have a tableView with many cells. Every cell has got the same type/class and every cell has got a toggleSwitch.

One of the cells, or more precisely cell in section 2, row 0, when it's switch is toggled, need to update a variable of type bool to true/false(if switch is on => true). That variable is in a second VC.

With the code below, doesn't matter which of the cells is tapped, it prints switch is on/switch is off, but I need that only for a mentioned above cell.

Cell's class:

```<code>@IBOutlet weak var labelCell: UILabel!

@IBOutlet weak var cellSwitch: UISwitch!

@IBAction func toggleSwitch(_ sender: Any) {
    if cellSwitch.isOn == true {
        print("switch is on")
    }
    else {
        print("switch is off")
    }
}
</code>```

In cellForRowAt:

```<code>case (2,0):
        cell.labelCell.text = "Shuffled"
        let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
        let cardVC = (mainStoryboard.instantiateViewController(withIdentifier: "CardViewController") as! CardViewController)
        //place for condition, if switch is on/off, put the true/false to secondVC.shuffle
        cardVC.shuffle = true
</code>```

My question is how my callback function should look like, I have no experience with them. And how to check if this (2,0) cell is tapped?

答:
Declare this callBack function into your tableViewCell file as showing bellow.

```<code>var callback:((Bool) -> Void)?

@IBAction func toggleSwitch(_ sender: Any) {
    if cellSwitch.isOn == true {
        print("switch is on")
        callback?(true)
    }
    else {
        print("switch is off")
        callback?(false)
    }
}

</code>```

you can get row tap using didSelectRowAt method of UITableViewDelegate.

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 2 {
    if indexPath.row == 0 {
        // the tapped detect of (2,0)
    }
}
}
</code>```

And you can get your callBack tap action of UISwitch from cellForRowAt method like show bellow.

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   if indexPath.section == 2 {
      var cell = tableView.dequeueReusableCell(withIdentifier: "yourCell") as! YourCell
      if indexPath.row == 0 {
          //here you can write your callBack closure & your UISwitch's value will retrived here
          cell.callback = { [unowned self] check in
              cardVC.shuffle = check

          }
      }
   }
}
</code>```

Body:
Situation:

I have a tableView with many cells. Every cell has got the same type/class and every cell has got a toggleSwitch.

One of the cells, or more precisely cell in section 2, row 0, when it's switch is toggled, need to update a variable of type bool to true/false(if switch is on => true). That variable is in a second VC.

With the code below, doesn't matter which of the cells is tapped, it prints switch is on/switch is off, but I need that only for a mentioned above cell.

Cell's class:

@IBOutlet weak var labelCell: UILabel!

@IBOutlet weak var cellSwitch: UISwitch!

@IBAction func toggleSwitch(_ sender: Any) {
    if cellSwitch.isOn == true {
        print("switch is on")
    }
    else {
        print("switch is off")
    }
}

In cellForRowAt:

case (2,0):
        cell.labelCell.text = "Shuffled"
        let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
        let cardVC = (mainStoryboard.instantiateViewController(withIdentifier: "CardViewController") as! CardViewController)
        //place for condition, if switch is on/off, put the true/false to secondVC.shuffle
        cardVC.shuffle = true

My question is how my callback function should look like, I have no experience with them. And how to check if this (2,0) cell is tapped?

Body:
Declare this callBack function into your tableViewCell file as showing bellow.

var callback:((Bool) -> Void)?

@IBAction func toggleSwitch(_ sender: Any) {
    if cellSwitch.isOn == true {
        print("switch is on")
        callback?(true)
    }
    else {
        print("switch is off")
        callback?(false)
    }
}

you can get row tap using didSelectRowAt method of UITableViewDelegate.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 2 {
    if indexPath.row == 0 {
        // the tapped detect of (2,0)
    }
}
}

And you can get your callBack tap action of UISwitch from cellForRowAt method like show bellow.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   if indexPath.section == 2 {
      var cell = tableView.dequeueReusableCell(withIdentifier: "yourCell") as! YourCell
      if indexPath.row == 0 {
          //here you can write your callBack closure & your UISwitch's value will retrived here
          cell.callback = { [unowned self] check in
              cardVC.shuffle = check

          }
      }
   }
}


问:
How to dump llvm module to .ll file
I see from this question there is a way to dump a module to bitcode (.bc), but I would like to dump the IR to a .ll file so that I can view the IR.

I know llvm-dis can convert .bc to .ll but in my case it does not work.
I have written some passes that transform the module in a way that llvm-dis fails to convert the bitcode to IR.

Is there an API similar to LLVMWriteBitcodeToFile that lets me dump a module to IR directly?

答:
You can use opt to do that.
e.g.,

opt -S test.bc -o test.ll

Title: How to dump llvm module to .ll file


问:
How to show a progress bar while Firebase data loads
How to show a progress bar while data from Javascript loads to the website.

```<code>  paperRef.once('value').then(function(snapshot) {
      numberOfPapers = snapshot.numChildren();
  });
</code>```

How to show a progress bar till numberOfPapers gets counted ?

答:
The once() method is asynchronous and returns a promise.

As explained in the MDN documentation:

A Promise is in one of these states:

pending: initial state, neither fulfilled nor rejected.

fulfilled: meaning that the operation completed successfully.

rejected: meaning that the operation failed.

You need to show a progress bar just before you call the once() method and hide it either if the promise is fulfilled or rejected. For that you will use the then() and catch() methods, as follows:

```<code>  showProgressBar();
  paperRef.once('value').then(function(snapshot) {
      //Promise is fulfilled
      hideProgressBar();
      numberOfPapers = snapshot.numChildren();
  })
  .catch(error => {
      //Promise is rejected
      hideProgressBar();
      //Show an error message
  });
</code>```

Since you didn't give any detail on which kind of progress bar you plan to use, it's up to you to implement the showProgressBar() and hideProgressBar() methods (showing/hiding a div, a spinner image, etc...)

Body:
How to show a progress bar while data from Javascript loads to the website.

  paperRef.once('value').then(function(snapshot) {
      numberOfPapers = snapshot.numChildren();
  });

How to show a progress bar till numberOfPapers gets counted ?

Body:
The once() method is asynchronous and returns a promise.

As explained in the MDN documentation:

A Promise is in one of these states:

pending: initial state, neither fulfilled nor rejected.

fulfilled: meaning that the operation completed successfully.

rejected: meaning that the operation failed.

You need to show a progress bar just before you call the once() method and hide it either if the promise is fulfilled or rejected. For that you will use the then() and catch() methods, as follows:

  showProgressBar();
  paperRef.once('value').then(function(snapshot) {
      //Promise is fulfilled
      hideProgressBar();
      numberOfPapers = snapshot.numChildren();
  })
  .catch(error => {
      //Promise is rejected
      hideProgressBar();
      //Show an error message
  });

Since you didn't give any detail on which kind of progress bar you plan to use, it's up to you to implement the showProgressBar() and hideProgressBar() methods (showing/hiding a div, a spinner image, etc...)


问:
Firefox CSS spacing issues cross-os
I'm having an issue with Firefox. It displays differently in Windows than on OSX. It looks to be a font spacing issue, or font size, but I can't figure it out. Both use the exact same properties.

Top Window: Mac OSX, Bottom: WinXP

Here's the basic HTML/Computed Style:

Any ideas from anyone?

答:
font kerning differences between the OS's looks like.
It's VERY hackish, but if you can't use a font that's more consistent between versions, you can always hack the kerning... http://www.w3schools.com/css/pr_text_letter-spacing.asp</p>

Title: Firefox CSS spacing issues cross-os