问:
How to extract substring as part of dplyr::mutate piping
I have the following data frame:

library(tidyverse)

df <-  structure(list(pfc_chr = c("chr1", "chr1", "chr1", "chr1", "chr1",
"chr1", "chr1", "chr1", "chr1", "chr1"), pfc_chr_st = c(3046442L,
3119671L, 3164756L, 3167322L, 3210838L, 3212196L, 3249068L, 3268246L,
3444892L, 3451544L), peak_name = c("XXX-ad_peak_1", "XXX-ad_peak_2a",
"PMN_peak_2", "Ytb_peak_3", "PMN_peak_3", "XXX-ad_peak_6",
"XXX-ad_peak_8", "PMN_peak_5", "XXX-ad_peak_11", "XXX-ad_peak_12"
)), .Names = c("pfc_chr", "pfc_chr_st", "peak_name"), row.names = c(NA,
-10L), class = c("tbl_df", "tbl", "data.frame"))

df
#> # A tibble: 10 x 3
#>    pfc_chr pfc_chr_st      peak_name
#>      <chr>      <int>          <chr>
#>  1    chr1    3046442  XXX-ad_peak_1
#>  2    chr1    3119671 XXX-ad_peak_2a
#>  3    chr1    3164756     PMN_peak_2
#>  4    chr1    3167322     Ytb_peak_3
#>  5    chr1    3210838     PMN_peak_3
#>  6    chr1    3212196  XXX-ad_peak_6
#>  7    chr1    3249068  XXX-ad_peak_8
#>  8    chr1    3268246     PMN_peak_5
#>  9    chr1    3444892 XXX-ad_peak_11
#> 10    chr1    3451544 XXX-ad_peak_12
```

<p>What I want to do is to extract the substring in <code>peak_name</code> as part of
dplyr pipe. The final desired result is:</p>

<pre class="lang-r prettyprint-override"><code>   pfc_chr pfc_chr_st      peak_name        new_col
1     chr1    3046442  XXX-ad_peak_1         XXX-ad
2     chr1    3119671 XXX-ad_peak_2a         XXX-ad
3     chr1    3164756     PMN_peak_2            PMN
4     chr1    3167322     Ytb_peak_3            Ytb
5     chr1    3210838     PMN_peak_3            PMN
6     chr1    3212196  XXX-ad_peak_6         XXX-ad
7     chr1    3249068  XXX-ad_peak_8         XXX-ad
8     chr1    3268246     PMN_peak_5            PMN
9     chr1    3444892 XXX-ad_peak_11         XXX-ad
10    chr1    3451544 XXX-ad_peak_12         XXX-ad
</code>```

I tried this but fail:

> df %>% mutate(new_col = stringr::str_match(peak_name, "^(.*?)\\_peak\\_*?"))
Error in mutate_impl(.data, dots) :
  Column `new_col` must be length 10 (the number of rows) or one, not 20
```

What's the right way to do it?

答:
select second column.

```<code>df %>% mutate(new_col = stringr::str_match(peak_name, "^(.*?)\\_peak\\_*?")[, 2])
</code>```

output

```<code>    pfc_chr pfc_chr_st      peak_name new_col
1    chr1    3046442  XXX-ad_peak_1  XXX-ad
2    chr1    3119671 XXX-ad_peak_2a  XXX-ad
3    chr1    3164756     PMN_peak_2     PMN
4    chr1    3167322     Ytb_peak_3     Ytb
5    chr1    3210838     PMN_peak_3     PMN
6    chr1    3212196  XXX-ad_peak_6  XXX-ad
7    chr1    3249068  XXX-ad_peak_8  XXX-ad
8    chr1    3268246     PMN_peak_5     PMN
9    chr1    3444892 XXX-ad_peak_11  XXX-ad
10    chr1    3451544 XXX-ad_peak_12  XXX-ad
</code>```

Body:
I have the following data frame:

library(tidyverse)

df <-  structure(list(pfc_chr = c("chr1", "chr1", "chr1", "chr1", "chr1",
"chr1", "chr1", "chr1", "chr1", "chr1"), pfc_chr_st = c(3046442L,
3119671L, 3164756L, 3167322L, 3210838L, 3212196L, 3249068L, 3268246L,
3444892L, 3451544L), peak_name = c("XXX-ad_peak_1", "XXX-ad_peak_2a",
"PMN_peak_2", "Ytb_peak_3", "PMN_peak_3", "XXX-ad_peak_6",
"XXX-ad_peak_8", "PMN_peak_5", "XXX-ad_peak_11", "XXX-ad_peak_12"
)), .Names = c("pfc_chr", "pfc_chr_st", "peak_name"), row.names = c(NA,
-10L), class = c("tbl_df", "tbl", "data.frame"))

df
#> # A tibble: 10 x 3
#>    pfc_chr pfc_chr_st      peak_name
#>      <chr>      <int>          <chr>
#>  1    chr1    3046442  XXX-ad_peak_1
#>  2    chr1    3119671 XXX-ad_peak_2a
#>  3    chr1    3164756     PMN_peak_2
#>  4    chr1    3167322     Ytb_peak_3
#>  5    chr1    3210838     PMN_peak_3
#>  6    chr1    3212196  XXX-ad_peak_6
#>  7    chr1    3249068  XXX-ad_peak_8
#>  8    chr1    3268246     PMN_peak_5
#>  9    chr1    3444892 XXX-ad_peak_11
#> 10    chr1    3451544 XXX-ad_peak_12

What I want to do is to extract the substring in peak_name as part of
dplyr pipe. The final desired result is:

   pfc_chr pfc_chr_st      peak_name        new_col
1     chr1    3046442  XXX-ad_peak_1         XXX-ad
2     chr1    3119671 XXX-ad_peak_2a         XXX-ad
3     chr1    3164756     PMN_peak_2            PMN
4     chr1    3167322     Ytb_peak_3            Ytb
5     chr1    3210838     PMN_peak_3            PMN
6     chr1    3212196  XXX-ad_peak_6         XXX-ad
7     chr1    3249068  XXX-ad_peak_8         XXX-ad
8     chr1    3268246     PMN_peak_5            PMN
9     chr1    3444892 XXX-ad_peak_11         XXX-ad
10    chr1    3451544 XXX-ad_peak_12         XXX-ad

I tried this but fail:

> df %>% mutate(new_col = stringr::str_match(peak_name, "^(.*?)\\_peak\\_*?"))
Error in mutate_impl(.data, dots) :
  Column `new_col` must be length 10 (the number of rows) or one, not 20

What's the right way to do it?

Body:
select second column.

df %>% mutate(new_col = stringr::str_match(peak_name, "^(.*?)\\_peak\\_*?")[, 2])

output

    pfc_chr pfc_chr_st      peak_name new_col
1    chr1    3046442  XXX-ad_peak_1  XXX-ad
2    chr1    3119671 XXX-ad_peak_2a  XXX-ad
3    chr1    3164756     PMN_peak_2     PMN
4    chr1    3167322     Ytb_peak_3     Ytb
5    chr1    3210838     PMN_peak_3     PMN
6    chr1    3212196  XXX-ad_peak_6  XXX-ad
7    chr1    3249068  XXX-ad_peak_8  XXX-ad
8    chr1    3268246     PMN_peak_5     PMN
9    chr1    3444892 XXX-ad_peak_11  XXX-ad
10    chr1    3451544 XXX-ad_peak_12  XXX-ad


来源: stackexchange

问:
How to get the Last working day of the Week for any Given date
I need to calculate Last working day of the Week (Friday) for any date which is given in the excel sheet... Example:: if my date is given as 09-March-2016 the last working day would be 11-March-2016, similarly if my date in Excel cell is 01-March-2016 the Last working day would be 04-March-2016, Can Any one help me with the formula so that I can work further pleaseeeeeeeee... really need your help team :) </p>

答:
A1 Cell = Your date (you need last working day in this week)

B1 Cell = A1+(6-WEEKDAY(A1))   - result (in case that friday is last working date)

NOTICE: B1 must be formated as date!

ContentLicense: CC BY-SA 3.0


问:
Controller not receiving comment.id from Upvote link
I'm trying to use an Upvote function in conjunction with the acts_as_votable gem. The problem that I'm having with it is that when I hover on the Upvote link I can see that the comment.id is not given to the URL preview, and then sure enough when I click Upvote the error message tells me:

```<code>Couldn't find Comment with 'id'=#
<Comment::ActiveRecord_Relation:0x007f813b169658>
</code>```

The comments loop in my views looks like this:

```<code> <div class="box">
 <% @comment.each do |w| %>
    <tr>
      <td><b><%= w.title %></b></td><br>
      <td><%= w.location %></td><br>
      <td><%= w.body %></td><br>
      <%= link_to "upvote", like_comment_path(@comment), method: :put
      %><br>
    </tr>
  <% end %>
 </div>
</code>```

And my CommentsController:

```<code>def upvote
  @comment = Comment.find(params[:id])
  @comment.upvote_by current_user
  redirect_to comments_path
end
</code>```

And my config/routes:

```<code>resources :comments do
  member do
    put "like", to: "comments#upvote"
    put "dislike", to: "comments#downvote"
  end
end
</code>```

This feels like it should be something very simple, but I just can't figure out why the id is not given, so help would be much appreciated :-)

答:
I assume your @comment is a collection on comments. If so then you should rename your @comment variable to @comments and iterate through the @comments collection in your view like this :

```<code><div class="box">
 <% @comments.each do |comment| %>
    <tr>
      <td><b><%= comment.title %></b></td><br>
      <td><%= comment.location %></td><br>
      <td><%= comment.body %></td><br>
      <%= link_to "upvote", like_comment_path(comment), method: :put
      %><br>
    </tr>
  <% end %>
 </div>
</code>```

As you can see you can create a link_to update your comment item like this :
<%= link_to "upvote", like_comment_path(comment), method: :put

Body:
I'm trying to use an Upvote function in conjunction with the acts_as_votable gem. The problem that I'm having with it is that when I hover on the Upvote link I can see that the comment.id is not given to the URL preview, and then sure enough when I click Upvote the error message tells me:

Couldn't find Comment with 'id'=#
<Comment::ActiveRecord_Relation:0x007f813b169658>

The comments loop in my views looks like this:

 <% @comment.each do |w| %>

      <%= w.title %>

      <%= w.location %>

      <%= w.body %>

      <%= link_to "upvote", like_comment_path(@comment), method: :put
      %>

  <% end %>

And my CommentsController:

def upvote
  @comment = Comment.find(params[:id])
  @comment.upvote_by current_user
  redirect_to comments_path
end

And my config/routes:

resources :comments do
  member do
    put "like", to: "comments#upvote"
    put "dislike", to: "comments#downvote"
  end
end

This feels like it should be something very simple, but I just can't figure out why the id is not given, so help would be much appreciated :-)

Body:
I assume your @comment is a collection on comments. If so then you should rename your @comment variable to @comments and iterate through the @comments collection in your view like this :

<div class="box">
 <% @comments.each do |comment| %>
    <tr>
      <td><b><%= comment.title %></b></td><br>
      <td><%= comment.location %></td><br>
      <td><%= comment.body %></td><br>
      <%= link_to "upvote", like_comment_path(comment), method: :put
      %><br>
    </tr>
  <% end %>
 </div>

As you can see you can create a link_to update your comment item like this :
<%= link_to "upvote", like_comment_path(comment), method: :put


问:
Extracting initials from a single string
I am looking to extract initials from a single textbox using Left, mid and other similar functions. The user enters their first, middle initial and last name; assuming spaces and a period after the middle initial. I need to ensure the initials extracted are uppercase, even if the text is entered in lowercase. Any assistance in a code that can accomplish this in VBA for Access would be appreciated. I am able to use the functions individually but am new to coding and am unsure how to string them together correctly.

```<code>Private Sub cmdGreeting_Click()
strOutput = Left(txtInput.Value, 1) & Mid(txtinput.value, 1) & Right(txtinput.value, 1)
lblOutput.Caption = strOutput
End Sub
</code>```

This is as far as I have gotten and I know it's incorrect because I have no idea how to account for the 3 separate names.

答:
This is the code I've been using for a while.  It will include the the initials of double-barreled names as well.

?GetInitials("Darren Bartrup-Cook") will return DBC.

?GetInitials("The quick brown fox jumps over the lazy dog") will return TQBFJOTLD.

```<code>Public Function GetInitials(FullName As String) As String

    Dim RegEx As Object
    Dim Ret As Object
    Dim RetItem As Object

    On Error GoTo ERR_HANDLE

    Set RegEx = CreateObject("VBScript.RegExp")
    With RegEx
        .IgnoreCase = True
        .Global = True
        .Pattern = "(\b[a-zA-Z])[a-zA-Z]* ?"
        Set Ret = .Execute(FullName)
        For Each RetItem In Ret
            GetInitials = GetInitials & UCase(RetItem.Submatches(0))
        Next RetItem
    End With

EXIT_PROC:
        On Error GoTo 0
        Exit Function

ERR_HANDLE:
        'Add your own error handling here.
        'DisplayError Err.Number, Err.Description, "mdl_GetInitials.GetInitials()"
        Resume EXIT_PROC

End Function
</code>```

Body:
I am looking to extract initials from a single textbox using Left, mid and other similar functions. The user enters their first, middle initial and last name; assuming spaces and a period after the middle initial. I need to ensure the initials extracted are uppercase, even if the text is entered in lowercase. Any assistance in a code that can accomplish this in VBA for Access would be appreciated. I am able to use the functions individually but am new to coding and am unsure how to string them together correctly.

Private Sub cmdGreeting_Click()
strOutput = Left(txtInput.Value, 1) & Mid(txtinput.value, 1) & Right(txtinput.value, 1)
lblOutput.Caption = strOutput
End Sub

This is as far as I have gotten and I know it's incorrect because I have no idea how to account for the 3 separate names.

Body:
This is the code I've been using for a while.  It will include the the initials of double-barreled names as well.

?GetInitials("Darren Bartrup-Cook") will return DBC.

?GetInitials("The quick brown fox jumps over the lazy dog") will return TQBFJOTLD.

Public Function GetInitials(FullName As String) As String

    Dim RegEx As Object
    Dim Ret As Object
    Dim RetItem As Object

    On Error GoTo ERR_HANDLE

    Set RegEx = CreateObject("VBScript.RegExp")
    With RegEx
        .IgnoreCase = True
        .Global = True
        .Pattern = "(\b[a-zA-Z])[a-zA-Z]* ?"
        Set Ret = .Execute(FullName)
        For Each RetItem In Ret
            GetInitials = GetInitials & UCase(RetItem.Submatches(0))
        Next RetItem
    End With

EXIT_PROC:
        On Error GoTo 0
        Exit Function

ERR_HANDLE:
        'Add your own error handling here.
        'DisplayError Err.Number, Err.Description, "mdl_GetInitials.GetInitials()"
        Resume EXIT_PROC

End Function


问:
How to clear all the history Webview in WebAppInterface
I try to clear all the history in WebView at WebAppInterface but it is not getting clear.

Code:-

```<code>    wvList = (WebView) view.findViewById(R.id.wv);
    wvList .setHorizontalScrollBarEnabled(false);
    wvList .getSettings().setJavaScriptEnabled(true);
    wvList .getSettings().setDomStorageEnabled(true);
    wvList .addJavascriptInterface(new WebAppInterface(mContext), "Android");
    wvList .setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            view.loadUrl(request.getUrl().toString());
            return false;
        }
    });

public class WebAppInterface {
    Context mContext;

    /**
     * Instantiate the interface and set the context
     */
    WebAppInterface(Context cxt) {
        mContext = cxt;
    }

    /**
     * Show a SnackBar from the web page
     */
    @JavascriptInterface
    public void showMessage(String msg) {
        wvList .post(new Runnable() {
        @Override
        public void run() {
            wvList .clearHistory();// Not working
            wvList .loadURL(url.toString);
        }
    });
    }
}
</code>```

Only in showMessage I want to clear all the history of webview so that in back press it will not go to previous page.

答:
try override this function in WebViewClient</p>

```<code>@Override
public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
    super.doUpdateVisitedHistory(view, url, isReload);
    if (needClearHistory) {
        needClearHistory = false;
        webview.clearHistory();
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I try to clear all the history in WebView at WebAppInterface but it is not getting clear.

Code:-

    wvList = (WebView) view.findViewById(R.id.wv);
    wvList .setHorizontalScrollBarEnabled(false);
    wvList .getSettings().setJavaScriptEnabled(true);
    wvList .getSettings().setDomStorageEnabled(true);
    wvList .addJavascriptInterface(new WebAppInterface(mContext), "Android");
    wvList .setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            view.loadUrl(request.getUrl().toString());
            return false;
        }
    });

public class WebAppInterface {
    Context mContext;

    /**
     * Instantiate the interface and set the context
     */
    WebAppInterface(Context cxt) {
        mContext = cxt;
    }

    /**
     * Show a SnackBar from the web page
     */
    @JavascriptInterface
    public void showMessage(String msg) {
        wvList .post(new Runnable() {
        @Override
        public void run() {
            wvList .clearHistory();// Not working
            wvList .loadURL(url.toString);
        }
    });
    }
}

Only in showMessage I want to clear all the history of webview so that in back press it will not go to previous page.

Body:
try override this function in WebViewClient

@Override
public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
    super.doUpdateVisitedHistory(view, url, isReload);
    if (needClearHistory) {
        needClearHistory = false;
        webview.clearHistory();
    }
}


问:
Selecting meta tags with Selenium
I want to extract data from a meta tag but the tag is as follows

```<code><meta property="og:description" content="blah"/>
</code>```

Since there is no id/class/etc. I can't use

```<code>driver.FindElement(By.[id/class/etc.]);
</code>```

This meta tag has a unique property and content so I am wondering if there is any better way to locate and extract the content than selecting all "meta" tags and iterating through them.

答:
While extracting data from a meta tag, I would suggest to use the attributes as much as possible. In your case :

XPath:

```<code>driver.FindElement(By.XPath("//meta[@property='og:description' and @content='blah']"));
</code>```

CssSelector:

```<code>driver.FindElement(By.CssSelector("meta[property='og:description'][content='blah']"));
</code>```

Title: Selecting meta tags with Selenium

Body:
I want to extract data from a meta tag but the tag is as follows

<meta property="og:description" content="blah"/>

Since there is no id/class/etc. I can't use

driver.FindElement(By.[id/class/etc.]);

This meta tag has a unique property and content so I am wondering if there is any better way to locate and extract the content than selecting all "meta" tags and iterating through them.

Body:
While extracting data from a meta tag, I would suggest to use the attributes as much as possible. In your case :

XPath:

driver.FindElement(By.XPath("//meta[@property='og:description' and @content='blah']"));

CssSelector:

driver.FindElement(By.CssSelector("meta[property='og:description'][content='blah']"));


问:
can't find controls in page, but only when running via selenium-server
I have a set of tests that I've developed using the Selenium IDE in Firefox. Tests run fine and all pass. Now I'm trying to port those over to C# and run the tests for IE using MSTest and selenium-server. Here's the sequence of events:

Run all tests on Firefox via Selenium IDE. All tests pass.

Export tests to MSTest (Nunit export, rename some stuff etc.)

Start selenium-server-1.0.3

Run the tests in VS2008. Selenium setup is: selenium = new DefaultSelenium("localhost", 4444, "*chrome", "http://localhost/theSite/");; note that I can browse to http://localhost/theSite/ just fine.

4a. Confirm test is launching Firefox. Got result:
 17:00:30.290 INFO - Preparing Firefox profile...
 17:00:33.842 INFO - Launching Firefox...

First test ( waitForText "Login" in control "ctl00_TopNavBar_LoginStatus1") fails. Can't find the control.
  if ("Login" == selenium.GetText("id=ctl00_TopNavBar_LoginStatus1")) break;
  or
  if ("Login" == selenium.GetText("ctl00_TopNavBar_LoginStatus1")) break;

All other tests fail as well -- same reason. Each test has a waitForText at the top.

Tried running the test in *chrome, *iexploreproxy and *firefox. All fail for the same reason.

Tried dumping a screenshot using selenium.CaptureEntirePageScreenshot("c:\\temp\\screenshots\\seleniumSite.png", "background=#FFFFFF"); and the screenshot is just a white bar.

So, my question is, how do I go about debugging this and figuring out what the real problem is? Clearly the page will render and the tests will pass. It's just when I try those tests in Selenium-RC that it fails so badly. Does the Selenium IDE have some bugs related to exporting tests to C#? (I have noticed one bug).

答:
Are you executing selenium.Start() and selenium.Open()? Do you see the page opened in the browser?

Full initialization should be something similar to:

```<code>selenium = new DefaultSelenium("localhost", 4444, "*chrome", "http://localhost/");
selenium.Start();
selenium.Open("/theSite/");
</code>```

Important Note! test your IDE tests by starting with an empty page. Also, when using the IDE, if a command only has one parameter put it in the Target field, even if it isn't a control name.

ContentLicense: CC BY-SA 2.5

Body:
Are you executing selenium.Start() and selenium.Open()? Do you see the page opened in the browser?

Full initialization should be something similar to:

selenium = new DefaultSelenium("localhost", 4444, "*chrome", "http://localhost/");
selenium.Start();
selenium.Open("/theSite/");

Important Note! test your IDE tests by starting with an empty page. Also, when using the IDE, if a command only has one parameter put it in the Target field, even if it isn't a control name.


问:
prn parameter in Scapy
Is the parameter prn in the sniff-function ofScapy an abbreviation for anything?

I know it is used to define a callback-function for the sniffed packet, I just can't find the meaning of prn.

I couldn't find an explanation for the abbreviation in the documentation.

答:
That's probably for "print", since the result of the callback (if it is not None) is printed.

The first (historical) use of this callback was to print, for example, a .summary() or a .display() of each sniffed packet (see the tshark() function).

Title: prn parameter in Scapy


问:
Multidimensional array with object and arrays
I have facing issue in accessing the index 1 in a array.
How can i access the index 1?

Tried to access like this.

```<code>$selection = $menu_selection->{1}->vl
</code>```

but i it showing undefined offset error. can anyone help me.

```<code>Array
(
    [1] => stdClass Object
        (
            [vl] => Array
                (
                    [0] => 1
                    [1] => 2
                )

            [op] => Array
                (
                    [0] => O
                    [1] => O
                )

        )

    [189] => Array
        (
            [vl] => Array
                (
                    [0] => 1
                )

        )

)
</code>```

答:
From PHP 7.2 on you can do this (costly way):

```<code>((object) $menu_selection)->{1}->v1;
</code>```

If way of accessing values doesn't matter it should be:

```<code>$menu_selection[1]->v1;
</code>```

Body:
I have facing issue in accessing the index 1 in a array.
How can i access the index 1?

Tried to access like this.

$selection = $menu_selection->{1}->vl

but i it showing undefined offset error. can anyone help me.

Array
(
    [1] => stdClass Object
        (
            [vl] => Array
                (
                    [0] => 1
                    [1] => 2
                )

            [op] => Array
                (
                    [0] => O
                    [1] => O
                )

        )

    [189] => Array
        (
            [vl] => Array
                (
                    [0] => 1
                )

        )

)

Body:
From PHP 7.2 on you can do this (costly way):

((object) $menu_selection)->{1}->v1;

If way of accessing values doesn't matter it should be:

$menu_selection[1]->v1;


问:
Passing arguments to tclsh via bash heredoc
I have following testcase:

```<code>#!/bin/bash
tclsh <<EOF
puts "argv=$argv"
EOF
</code>```

How I can pass arguments to the tclsh? The arguments must be after the file (as per man page of tclsh)

```<code>SYNOPSIS
    tclsh ?-encoding name? ?fileName arg arg ...?
</code>```

Update:

First I will take bash command flags and use them to make arguments for tclsh:

```<code>tclarg1="....."
tclarg2="....."
</code>```

Then I will have string variable with tcl:

```<code>SCRIPT='
    proc test{arg1 arg2} {
        some tcl commands
    }
    test ???? ????
'
</code>```

And lastly I execute that string:

```<code>tclsh <<-HERE
${POPUPSCRIPT}
HERE
</code>```

How I pass "tclarg1" and "tclarg2" to the tcl script?

The string could come from other sources (by sourcing another file) and also bash script can execute that string from multiple locations/functions.

答:
```<code>#!/bin/bash
tclsh <<EOF
puts "argv=$@"
EOF
</code>```

Body:
I have following testcase:

#!/bin/bash
tclsh <<EOF
puts "argv=$argv"
EOF

How I can pass arguments to the tclsh? The arguments must be after the file (as per man page of tclsh)

SYNOPSIS
    tclsh ?-encoding name? ?fileName arg arg ...?

Update:

First I will take bash command flags and use them to make arguments for tclsh:

tclarg1="....."
tclarg2="....."

Then I will have string variable with tcl:

SCRIPT='
    proc test{arg1 arg2} {
        some tcl commands
    }
    test ???? ????
'

And lastly I execute that string:

tclsh <<-HERE
${POPUPSCRIPT}
HERE

How I pass "tclarg1" and "tclarg2" to the tcl script?

The string could come from other sources (by sourcing another file) and also bash script can execute that string from multiple locations/functions.


问:
Excel Macro, Check for headers
I am new to VBA and I would like to check if there's any way of determining whether my excel sheet has headers. The manual way of doing it is via data,

1) Click on Data,
2) Sort
3) Check whether "My Data has headers" checkbox has been checked.

Is there any way to reproduce the steps as shown above via macro?
Thanks!

答:
You can use the sort method which has an option for declaring if there are headers or not in the sheet. If you don't declare it yourself using xlYes or xlNo there is an option to use xlGuess if you want Excel to attempt to determine the header. Example:

```<code>Columns("A:C").Sort key1:=Range("C2"), _
  order1:=xlAscending, header:=xlGuess
</code>```

For further info: https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-sort-method-excel?query=

Title: Excel Macro, Check for headers

Body:
You can use the sort method which has an option for declaring if there are headers or not in the sheet. If you don't declare it yourself using xlYes or xlNo there is an option to use xlGuess if you want Excel to attempt to determine the header. Example:

Columns("A:C").Sort key1:=Range("C2"), _
  order1:=xlAscending, header:=xlGuess

For further info: https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-sort-method-excel?query=


问:
How to create a mini-game?
I'am wondering how to create a mini-game like "diner dash" or like "big fish games". I want my game to be 2D but it looks like 3D. See this image:

(source: topxgames.com)

If you know some good game-engine to create like those games, please let me know.

答:
You can use Java to create 2d or 3d games like  "diner dash" or like "big fish games" .
take a look here http://developers.sun.com/mobility/midp/articles/game/</p>

Title: How to create a mini-game?


问:
JavaScript error handling: can I throw an error inside a ternary operator?
Am I allowed to throw an error inside a ternary operator? Is this valid:

```<code>function foo(params) {

    var msg = (params.msg) ? params.msg : (throw "error");

    // do stuff if everything inside `params` is defined
}
</code>```

What I'm trying to do is make sure all of the parameters needed, which are in a param object, are defined and throw an error if any one is not defined.

If this is just foolish, is there a better approach to doing this?

答:
Came across this while using fetch, here's the solution I offer for that particular case:

```<code>return fetch(url, request)
  .then(response => response.status >= 400 && response.status < 600
    ? response.json().then(error => {throw new Error(error.message)})
    : response);
</code>```

Note the (inline) block around throw which transforms the arrow-function body from a (return) expression to a statement.

Body:
Am I allowed to throw an error inside a ternary operator? Is this valid:

function foo(params) {

    var msg = (params.msg) ? params.msg : (throw "error");

    // do stuff if everything inside `params` is defined
}

What I'm trying to do is make sure all of the parameters needed, which are in a param object, are defined and throw an error if any one is not defined.

If this is just foolish, is there a better approach to doing this?

Body:
Came across this while using fetch, here's the solution I offer for that particular case:

return fetch(url, request)
  .then(response => response.status >= 400 && response.status < 600
    ? response.json().then(error => {throw new Error(error.message)})
    : response);

Note the (inline) block around throw which transforms the arrow-function body from a (return) expression to a statement.


问:
Why does UPDATE statement give divide by zero even if that particular row doesn't exist?
Ok this may be idiot question but I want to know why does the update statement gives divided by 0 operation even thought there is no row in the table. Does it execute the set function first and then try to apply to the where clause.</p>

```<code>  CREATE TABLE #tmp
    (
    Id INT,
    Amount money
    )

    UPDATE t
    SET t.Amount=0/0
    FROM #tmp AS t
    WHERE t.Id=2

    DROP TABLE #tmp
</code>```

答: Because the query will be parsed before SQL Server attempts to execute it. At that point it will throw an error because the command is unexecutable.</p>

Body:
Ok this may be idiot question but I want to know why does the update statement gives divided by 0 operation even thought there is no row in the table. Does it execute the set function first and then try to apply to the where clause.

  CREATE TABLE #tmp
    (
    Id INT,
    Amount money
    )

    UPDATE t
    SET t.Amount=0/0
    FROM #tmp AS t
    WHERE t.Id=2

    DROP TABLE #tmp


答:
You are making a two errors.

$selection = $menu_selection->{1}->vl

The first error is accessing the first array position, you must do something like this $selection = $menu_selection[1].
The second error is using ->, this notation is used to access object properties and to call object functions.

To access index 1, you do something like this:

$selection = $menu_selection[1]

To access vl from array 1 try:

$selection = $menu_selection[1]->vl

As you can see in the var_dump, $menu_selection[1] is an object of type stdClass, that's why you need -> to access the vl property.

Title: Multidimensional array with object and arrays


问:
Can't install sense plugin for Kibana
I am trying to install sense plugin for elasticsearch/kibana.
I have successfully installed Kibana but when following the instruction on https://www.elastic.co/guide/en/sense/current/installing.html
I type :
./kibana plugin --install elastic/sense, on the bin directory inside kibana folder, and I get :

```<code> ERROR  unknown command plugin

  Usage: bin/kibana [command=serve] [options]

  Kibana is an open source (Apache Licensed), browser based analytics and search dashboard for Elasticsearch.

  Commands:
    serve  [options]  Run the kibana server
    help  <command>   Get the help for a specific command

  "serve" Options:

    -h, --help                 output usage information
    -e, --elasticsearch <uri>  Elasticsearch instance
    -c, --config <path>        Path to the config file, can be changed with the CONFIG_PATH environment variable as well. Use mulitple --config args to include multiple config files.
    -p, --port <port>          The port to bind to
    -q, --quiet                Prevent all logging except errors
    -Q, --silent               Prevent all logging
    --verbose                  Turns on verbose logging
    -H, --host <host>          The host to bind to
    -l, --log-file <path>      The file to log to
    --plugin-dir <path>        A path to scan for plugins, this can be specified multiple times to specify multiple directories
    --plugin-path <path>       A path to a plugin which should be included by the server, this can be specified multiple times to specify multiple paths
    --plugins <path>           an alias for --plugin-dir
</code>```

I can't figure out why I get this error, how can I install sense plugin then ?

答:
Sense is now included as Console in Kibana 5.0. You can view the following link:
https://github.com/elastic/sense/blob/master/README.md

There is no need of installing sense seprately, as it is now included as Console.
elasticsearch and kibana should be running then Console can be found on :

http://localhost:5601/app/kibana#/dev_tools/console

Title: Can't install sense plugin for Kibana

Body:
I am trying to install sense plugin for elasticsearch/kibana.
I have successfully installed Kibana but when following the instruction on https://www.elastic.co/guide/en/sense/current/installing.html
I type :
./kibana plugin --install elastic/sense, on the bin directory inside kibana folder, and I get :

 ERROR  unknown command plugin

  Usage: bin/kibana [command=serve] [options]

  Kibana is an open source (Apache Licensed), browser based analytics and search dashboard for Elasticsearch.

  Commands:
    serve  [options]  Run the kibana server
    help  <command>   Get the help for a specific command

  "serve" Options:

    -h, --help                 output usage information
    -e, --elasticsearch <uri>  Elasticsearch instance
    -c, --config <path>        Path to the config file, can be changed with the CONFIG_PATH environment variable as well. Use mulitple --config args to include multiple config files.
    -p, --port <port>          The port to bind to
    -q, --quiet                Prevent all logging except errors
    -Q, --silent               Prevent all logging
    --verbose                  Turns on verbose logging
    -H, --host <host>          The host to bind to
    -l, --log-file <path>      The file to log to
    --plugin-dir <path>        A path to scan for plugins, this can be specified multiple times to specify multiple directories
    --plugin-path <path>       A path to a plugin which should be included by the server, this can be specified multiple times to specify multiple paths
    --plugins <path>           an alias for --plugin-dir

I can't figure out why I get this error, how can I install sense plugin then ?


问:
Change Galaxy S8 Navigation Bar Color Programmatically
Since galaxy s8 home/back/recent buttons are now soft keys, so i need to change the back color of the buttons within my application only.</p>

答:
You problem is solved in Lollipop and above,</p>

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    window.setNavigationBarColor(Color.YOUR_COLOR);
}
</code>```

Body:
You problem is solved in Lollipop and above,

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    window.setNavigationBarColor(Color.YOUR_COLOR);
}


问:
Oracle Create a view replacing ids with names in column (not 1nf)
We have for example this table:

```<code>pl_num camp_type  products
1       T         1,2,3
2       B         1,3,4
</code>```

Yeah, I know it's not in 1NF but we need to work with it
because of application loads data in such way.

And we have table DICT_PRODUCT, for example (in reality, there are more than 500 product):

```<code>id product_name
1   a
2   b
3   c
4   d
</code>```

So, what we need is to create view where product_id was replaced by its name in dictionary

---V_TAB1 ---

```<code>pl_num camp_type  products
1       T         1,b,c
2       B         a,c,d
</code>```

答:
Try this one:</p>

```<code>   select distinct *
    from (
    select t.u_name, u_id, regexp_substr(t.prod,'[^,]+', 1, level) id
    from (select prod,u_id, u_name from  cmdm.t_prod) t
    connect by regexp_substr(prod,'[^,]+',1,level) is not null) ut
    inner join cmdm.t_dct dt
    on ut.id=dt.id
</code>```

Body:
We have for example this table:

pl_num camp_type  products
1       T         1,2,3
2       B         1,3,4

Yeah, I know it's not in 1NF but we need to work with it
because of application loads data in such way.

And we have table DICT_PRODUCT, for example (in reality, there are more than 500 product):

id product_name
1   a
2   b
3   c
4   d

So, what we need is to create view where product_id was replaced by its name in dictionary

---V_TAB1 ---

pl_num camp_type  products
1       T         1,b,c
2       B         a,c,d

Body:
Try this one:

   select distinct *
    from (
    select t.u_name, u_id, regexp_substr(t.prod,'[^,]+', 1, level) id
    from (select prod,u_id, u_name from  cmdm.t_prod) t
    connect by regexp_substr(prod,'[^,]+',1,level) is not null) ut
    inner join cmdm.t_dct dt
    on ut.id=dt.id


答:
Try this. It will work if products column in TAB1 contain numbers and not any other characters.

```<code>WITH prod
     AS (SELECT pl_num, camp_type, TO_NUMBER (TRIM (COLUMN_VALUE)) product
           FROM Tab1 t, XMLTABLE (t.products))
  SELECT prod.pl_num,
         prod.camp_type,
         LISTAGG (d.product_name, ',') WITHIN GROUP (ORDER BY id) products
    FROM prod JOIN dict_product d ON prod.product = d.id
GROUP BY prod.pl_num, prod.camp_type;
</code>```

DEMO

Title: Oracle Create a view replacing ids with names in column (not 1nf)

Body:
Try this. It will work if products column in TAB1 contain numbers and not any other characters.

WITH prod
     AS (SELECT pl_num, camp_type, TO_NUMBER (TRIM (COLUMN_VALUE)) product
           FROM Tab1 t, XMLTABLE (t.products))
  SELECT prod.pl_num,
         prod.camp_type,
         LISTAGG (d.product_name, ',') WITHIN GROUP (ORDER BY id) products
    FROM prod JOIN dict_product d ON prod.product = d.id
GROUP BY prod.pl_num, prod.camp_type;

DEMO


问:
Laravel storage outside on localmachine in folder like as 'C:/uploads'
I want to save file in folder outside Laravel project to folder on local machine for example 'C:/uploads'. When the project installed on local machine is saved in 'C:/uploads' folder but when the project is installed online on server don't save in 'C:/uploads'.

In filesystems.php I put like as:

```<code>'local' => [
     'driver' => 'local',
      //'root' => storage_path('app/public'),
      //'root' => public_path('uploads'),
      'root'=>'C:\uploads',
 ],

'public' => [
    'driver' => 'local',
     'root' => storage_path('app/public'),
     'visibility' => 'public',
],
</code>```

In HomeController.php function:

```<code>$files = Input::file('images');
$file_count = count($files);
$uploadcount = 0;
foreach($files as $file) {
  //$destinationPath = 'uploads';
  $filename = time() .'-'.$file->getClientOriginalName();
  //$file->move($destinationPath, $filename);
  Storage::disk('local')->put($filename, File::get($file));
  $image=new Image();
  $image->sparepart_id = $id;
  $image->Filename=$filename;
  $image->save();
  $uploadcount ++;
</code>```

}

答:
You can use Laravel's environment variables to achieve this.

In your .env file (example 1)

```<code>FILESYSTEM_DRIVER=name_of_your_disk
</code>```

Or define the application environment (example 2)

```<code>APP_ENV=production
</code>```

Then change these values accordingly for your local env and server env and use them in your code to check what env is being used.

In your home controller you can simply use the Storage facade without the disk call to use the default disk defined in ex 1. Or you could check for APP_ENV and save or not save to the desired disk based on that.

```<code>if(env('APP_ENV') !== 'production')
{
    Storage::disk('local')->put($filename, File::get($file))
}
</code>```

Body:
I want to save file in folder outside Laravel project to folder on local machine for example 'C:/uploads'. When the project installed on local machine is saved in 'C:/uploads' folder but when the project is installed online on server don't save in 'C:/uploads'.

In filesystems.php I put like as:

'local' => [
     'driver' => 'local',
      //'root' => storage_path('app/public'),
      //'root' => public_path('uploads'),
      'root'=>'C:\uploads',
 ],

'public' => [
    'driver' => 'local',
     'root' => storage_path('app/public'),
     'visibility' => 'public',
],

In HomeController.php function:

$files = Input::file('images');
$file_count = count($files);
$uploadcount = 0;
foreach($files as $file) {
  //$destinationPath = 'uploads';
  $filename = time() .'-'.$file->getClientOriginalName();
  //$file->move($destinationPath, $filename);
  Storage::disk('local')->put($filename, File::get($file));
  $image=new Image();
  $image->sparepart_id = $id;
  $image->Filename=$filename;
  $image->save();
  $uploadcount ++;

}

Body:
You can use Laravel's environment variables to achieve this.

In your .env file (example 1)

FILESYSTEM_DRIVER=name_of_your_disk

Or define the application environment (example 2)

APP_ENV=production

Then change these values accordingly for your local env and server env and use them in your code to check what env is being used.

In your home controller you can simply use the Storage facade without the disk call to use the default disk defined in ex 1. Or you could check for APP_ENV and save or not save to the desired disk based on that.

if(env('APP_ENV') !== 'production')
{
    Storage::disk('local')->put($filename, File::get($file))
}


问:
Fatal Exception: java.lang.NoClassDefFoundError: android/view/ViewStructure
I am building an community directory application for android OS.
It is working fine Lollipop onward devices.Appplication has been sometime
crashed in  Android OS 4.4 version. Error log mentioned below :</p>

```<code># Platform: android
# Date: 2017-12-04T08:33:00Z
# OS Version: 4.4.2
# Device: Galaxy S5
# RAM Free: 63.1%
# Disk Free: 69.3%

Fatal Exception: java.lang.NoClassDefFoundError: android/view/ViewStructure
Caused by java.lang.ClassNotFoundException: Didn't find class
"android.view.ViewStructure" on path: DexPathList[[zip file
"/data/app/com.blacksmithyouthclub-1.apk", zip file
"/data/data/com.blacksmithyouthclub/code_cache/secondary-
dexes/com.blacksmithyouthclub-1.apk.classes2.zip"],nativeLibraryDirectories=
[/data/app-lib/com.blacksmithyouthclub-1, /vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
at java.lang.Class.getDeclaredMethods(Class.java)
at java.lang.Class.getDeclaredMethods(Class.java:656)
at android.view.ViewDebug.getExportedPropertyMethods(ViewDebug.java:960)
at android.view.ViewDebug.exportMethods(ViewDebug.java:1047)
at android.view.ViewDebug.dumpViewProperties(ViewDebug.java:997)
at android.view.ViewDebug.dumpViewProperties(ViewDebug.java:983)
at android.view.ViewDebug.dumpView(ViewDebug.java:900)
at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:855)
at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
at android.view.ViewDebug.dump(ViewDebug.java:793)
at android.view.ViewDebug.dispatchCommand(ViewDebug.java:416)
at android.view.ViewRootImpl$W.executeCommand(ViewRootImpl.java:6258)
at android.view.IWindow$Stub.onTransact(IWindow.java:65)
at android.os.Binder.execTransact(Binder.java:404)
at dalvik.system.NativeStart.run(NativeStart.java)
</code>```

答:
ViewDebug.getExportedPropertyMethods() should only occur if
  hierarchyviewer / ddm is connected. This is not a user crash.

Check here.

Body:
I am building an community directory application for android OS.
It is working fine Lollipop onward devices.Appplication has been sometime
crashed in  Android OS 4.4 version. Error log mentioned below :

# Platform: android
# Date: 2017-12-04T08:33:00Z
# OS Version: 4.4.2
# Device: Galaxy S5
# RAM Free: 63.1%
# Disk Free: 69.3%

Fatal Exception: java.lang.NoClassDefFoundError: android/view/ViewStructure
Caused by java.lang.ClassNotFoundException: Didn't find class
"android.view.ViewStructure" on path: DexPathList[[zip file
"/data/app/com.blacksmithyouthclub-1.apk", zip file
"/data/data/com.blacksmithyouthclub/code_cache/secondary-
dexes/com.blacksmithyouthclub-1.apk.classes2.zip"],nativeLibraryDirectories=
[/data/app-lib/com.blacksmithyouthclub-1, /vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
at java.lang.Class.getDeclaredMethods(Class.java)
at java.lang.Class.getDeclaredMethods(Class.java:656)
at android.view.ViewDebug.getExportedPropertyMethods(ViewDebug.java:960)
at android.view.ViewDebug.exportMethods(ViewDebug.java:1047)
at android.view.ViewDebug.dumpViewProperties(ViewDebug.java:997)
at android.view.ViewDebug.dumpViewProperties(ViewDebug.java:983)
at android.view.ViewDebug.dumpView(ViewDebug.java:900)
at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:855)
at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
at android.view.ViewDebug.dump(ViewDebug.java:793)
at android.view.ViewDebug.dispatchCommand(ViewDebug.java:416)
at android.view.ViewRootImpl$W.executeCommand(ViewRootImpl.java:6258)
at android.view.IWindow$Stub.onTransact(IWindow.java:65)
at android.os.Binder.execTransact(Binder.java:404)
at dalvik.system.NativeStart.run(NativeStart.java)


答:
If you try it like this you will not get an error :

```<code>CREATE TABLE #tmp
(
Id INT,
Amount money
)

UPDATE t
SET    t.Amount=0/0
FROM   #tmp AS t
WHERE  1 = 0

DROP TABLE #tmp
</code>```

You get the error because your where clause forced a search in your table, and it will peform the set operation also at the same time

Title: Why does UPDATE statement give divide by zero even if that particular row doesn't exist?

Body:
If you try it like this you will not get an error :

CREATE TABLE #tmp
(
Id INT,
Amount money
)

UPDATE t
SET    t.Amount=0/0
FROM   #tmp AS t
WHERE  1 = 0

DROP TABLE #tmp

You get the error because your where clause forced a search in your table, and it will peform the set operation also at the same time


问:
Filesystem.php - failed to open stream
I made multiple web-applications using Laravel so this is not my first production deply. However - I've bumped into a weird issue that I can't seem to find the answer for. As with all applications I've done so far - I copy/pasted all the files to the production server, set up the .env file, edited app.php and database.php in the config folder but i keep getting this error:

```<code>    ErrorException in ClassLoader.php line 412:
     include(/home/xxxxx/public_html/appname/vendor/composer/../laravel/framework/src/Illuminate/Filesystem/Filesystem.php):
    failed to open stream: No such file or directory
    in ClassLoader.php line 412
at HandleExceptions->handleError('2', 'include(/home/xxxxx/public_html/appname/vendor/composer/../laravel/framework/src/Illuminate/Filesystem/Filesystem.php): failed to open stream: No such file or directory', '/home/xxxxx/public_html/appname/vendor/composer/ClassLoader.php', '412', array('file' => '/home/xxxxx/public_html/appname/vendor/composer/../laravel/framework/src/Illuminate/Filesystem/Filesystem.php')) in ClassLoader.php line 412
at Composer\Autoload\includeFile() in ClassLoader.php line 412
at Composer\Autoload\includeFile('/home/xxxxx/public_html/appname/vendor/composer/../laravel/framework/src/Illuminate/Filesystem/Filesystem.php') in ClassLoader.php line 301
at ClassLoader->loadClass('Illuminate\Filesystem\Filesystem')
at spl_autoload_call('Illuminate\Filesystem\Filesystem') in Application.php line 539
at Application->registerConfiguredProviders() in RegisterProviders.php line 17
at RegisterProviders->bootstrap(object(Application)) in Application.php line 203
at Application->bootstrapWith(array('Illuminate\Foundation\Bootstrap\DetectEnvironment', 'Illuminate\Foundation\Bootstrap\LoadConfiguration', 'Illuminate\Foundation\Bootstrap\ConfigureLogging', 'Illuminate\Foundation\Bootstrap\HandleExceptions', 'Illuminate\Foundation\Bootstrap\RegisterFacades', 'Illuminate\Foundation\Bootstrap\RegisterProviders', 'Illuminate\Foundation\Bootstrap\BootProviders')) in Kernel.php line 253
at Kernel->bootstrap() in Kernel.php line 144
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 116
at Kernel->handle(object(Request)) in index.php line 54
</code>```

Now... I've tried everything i found on the web so far. Clearing cache, checking file permissions, running composer dump autoload, reuploading all the files - but nothing seems to help. It's a shared hosting with PHP v5.6 which already has several laravel applications running and they work perfectly. The only difference is that this one is laravel 5.3 and the other are 5.2.

I have no errors on my local dev machine.

Any ideas!?

答:
This might happen due to some security features that are active on the web hosting itself. The mentioned class gets flagged as malware and the AV keeps deleting it upon upload/reupload. Since the whole file/class is missing - the application throws the mentioned error.

If you don't run your own server and can't white-list the file, just contact your hosting provider to do it for you.

Title: Filesystem.php - failed to open stream

Body:
I made multiple web-applications using Laravel so this is not my first production deply. However - I've bumped into a weird issue that I can't seem to find the answer for. As with all applications I've done so far - I copy/pasted all the files to the production server, set up the .env file, edited app.php and database.php in the config folder but i keep getting this error:

    ErrorException in ClassLoader.php line 412:
     include(/home/xxxxx/public_html/appname/vendor/composer/../laravel/framework/src/Illuminate/Filesystem/Filesystem.php):
    failed to open stream: No such file or directory
    in ClassLoader.php line 412
at HandleExceptions->handleError('2', 'include(/home/xxxxx/public_html/appname/vendor/composer/../laravel/framework/src/Illuminate/Filesystem/Filesystem.php): failed to open stream: No such file or directory', '/home/xxxxx/public_html/appname/vendor/composer/ClassLoader.php', '412', array('file' => '/home/xxxxx/public_html/appname/vendor/composer/../laravel/framework/src/Illuminate/Filesystem/Filesystem.php')) in ClassLoader.php line 412
at Composer\Autoload\includeFile() in ClassLoader.php line 412
at Composer\Autoload\includeFile('/home/xxxxx/public_html/appname/vendor/composer/../laravel/framework/src/Illuminate/Filesystem/Filesystem.php') in ClassLoader.php line 301
at ClassLoader->loadClass('Illuminate\Filesystem\Filesystem')
at spl_autoload_call('Illuminate\Filesystem\Filesystem') in Application.php line 539
at Application->registerConfiguredProviders() in RegisterProviders.php line 17
at RegisterProviders->bootstrap(object(Application)) in Application.php line 203
at Application->bootstrapWith(array('Illuminate\Foundation\Bootstrap\DetectEnvironment', 'Illuminate\Foundation\Bootstrap\LoadConfiguration', 'Illuminate\Foundation\Bootstrap\ConfigureLogging', 'Illuminate\Foundation\Bootstrap\HandleExceptions', 'Illuminate\Foundation\Bootstrap\RegisterFacades', 'Illuminate\Foundation\Bootstrap\RegisterProviders', 'Illuminate\Foundation\Bootstrap\BootProviders')) in Kernel.php line 253
at Kernel->bootstrap() in Kernel.php line 144
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 116
at Kernel->handle(object(Request)) in index.php line 54

Now... I've tried everything i found on the web so far. Clearing cache, checking file permissions, running composer dump autoload, reuploading all the files - but nothing seems to help. It's a shared hosting with PHP v5.6 which already has several laravel applications running and they work perfectly. The only difference is that this one is laravel 5.3 and the other are 5.2.

I have no errors on my local dev machine.

Any ideas!?


问:
Prevent changes to columns
Running MS Access 2016. Say I have a table "Models" with the following columns:

Model

Brand

Type

No single field is unique, but together there should only be one combination.
My problem is that when I'm running a query, I can get data from these columns and alter one of the fields to something that is not valid.
I don't want to run validation on the table, as I tihnk there is a more simple solution to this.

For example, if the model is "Macbok Air" and the brand is "Apple", I shouldn't be able to change the brand to anything else in the query with the lookup combo box.

I hope this makes sense, help appriciated.

A quick google search showed this reply:
". If the controlsource of the combo is a field in the forms' Recordsource then selecting a value in that combo will change the value for that field for the current record. If you want to use the selected name tin the combo to filter the form or another form, you need to leave the combo Unbound (blank Controlsource)

You can still reference the value in the combo as long as the form is open."

However, I'm not exactly sure how to do this. And I'm not using forms yet. Can anyone elaborate?

答:
if the model is "Macbok Air" and the brand is "Apple", I shouldn't be
  able to change the brand to anything else

But that is a business rule only humans (you) know of. The database can have no idea, that an "Apple Surface 4" should not be a valid combo.

Your only method would be to maintain a manually validated table with valid combinations, and then let the user select an ID of these combos in one or more levels.

Title: Prevent changes to columns


问:
Setting up precision C++
So, i'm attempting to set the precision for input values in my code. I want the values to be printed with two decimal points afterwards of precision though i'm not exactly sure how.

Here's my code.

```<code>#include <iostream>
#include <iomanip>

float uphill, wellD, waterLvl, buckVol;
float buckAscRate, downHill, volume;
float last;
float timeReq;

int scene = 1;

void timeRequired()
{
    std::setw(2);
    std::setprecision(2);

    std::cout << "Scenario " << scene << ":" << std::endl;
    std::cout << "up hill" << "          " << uphill << " sec" << std::endl;
    std::cout << "well diamter" << "          " << wellD << " in" << std::endl;
    std::cout << "water level" << "          " << waterLvl << " in" << std::endl;
    std::cout << "bucket volume" << "          " << buckVol << " cu ft" << std::endl;
    std::cout << "bucket ascent rate" << "          " << buckAscRate << " in/sec" << std::endl;
    std::cout << "down hill" << "          " << downHill << " sec" << std::endl;
    std::cout << "required volume" << "          " << volume << " cu ft" << std::endl;

    timeReq = (uphill + downHill);

    std::cout << "TIME REQUIRED" << "          " << timeReq << " sec" << std::endl;

    std::cout << " " << std::endl;

}

void scenarioCONT()
{
    do
    {
        std::cin >> wellD;
        std::cin >> waterLvl;
        std::cin >> buckVol;
        std::cin >> buckAscRate;
        std::cin >> downHill;
        std::cin >> volume;
        std::cin >> last;

        if (uphill <= 1) uphill = 2;
        if (wellD <= 0) wellD = 1;
        if (waterLvl <= 0) waterLvl = 1;
        if (buckVol <= 0) buckVol = 1;
        if (buckAscRate <= 0) buckAscRate = 1;
        if (downHill <= 0) buckAscRate = 1;
        if (volume <= 0) volume = 1;

        if (last > 1)
        {
            uphill = last;
            scenarioCONT();

        }

    } while (last != 0);

}
void scenario()
{
    do
    {
        std::cin >> uphill;
        std::cin >> wellD;
        std::cin >> waterLvl;
        std::cin >> buckVol;
        std::cin >> buckAscRate;
        std::cin >> downHill;
        std::cin >> volume;
        std::cin >> last;

        if (uphill <= 1) uphill = 2;
        if (wellD <= 0) wellD = 1;
        if (waterLvl <= 0) waterLvl = 1;
        if (buckVol <= 0) buckVol = 1;
        if (buckAscRate <= 0) buckAscRate = 1;
        if (downHill <= 0) buckAscRate = 1;
        if (volume <= 0) volume = 1;

        if (last > 1)
        {
            timeRequired();
            uphill = last;
            scenarioCONT();

        }
            scene++;
            timeRequired();

    } while (last != 0);

}

int main()
{

    scenario();

    system("pause");
}
</code>```

I've been told to use ionmanip to set the precision, though i'm not 100% on how to do it. Any suggestions?

答:
If you want to output 2 decimal digits, you should use std::fixed, together with std::setprecision().

Take a look here.

For easier understanding, here is an example:
cout << setprecision(2)<< 3.1415; outputs 3.1 (2 digits in total) and

cout << setprecision(2)<<fixed<< 3.1415; outputs 3.14 (2 digits after floating point)

Title: Setting up precision C++

Body:
So, i'm attempting to set the precision for input values in my code. I want the values to be printed with two decimal points afterwards of precision though i'm not exactly sure how.

Here's my code.

#include <iostream>
#include <iomanip>

float uphill, wellD, waterLvl, buckVol;
float buckAscRate, downHill, volume;
float last;
float timeReq;

int scene = 1;

void timeRequired()
{
    std::setw(2);
    std::setprecision(2);

    std::cout << "Scenario " << scene << ":" << std::endl;
    std::cout << "up hill" << "          " << uphill << " sec" << std::endl;
    std::cout << "well diamter" << "          " << wellD << " in" << std::endl;
    std::cout << "water level" << "          " << waterLvl << " in" << std::endl;
    std::cout << "bucket volume" << "          " << buckVol << " cu ft" << std::endl;
    std::cout << "bucket ascent rate" << "          " << buckAscRate << " in/sec" << std::endl;
    std::cout << "down hill" << "          " << downHill << " sec" << std::endl;
    std::cout << "required volume" << "          " << volume << " cu ft" << std::endl;

    timeReq = (uphill + downHill);

    std::cout << "TIME REQUIRED" << "          " << timeReq << " sec" << std::endl;

    std::cout << " " << std::endl;

}

void scenarioCONT()
{
    do
    {
        std::cin >> wellD;
        std::cin >> waterLvl;
        std::cin >> buckVol;
        std::cin >> buckAscRate;
        std::cin >> downHill;
        std::cin >> volume;
        std::cin >> last;

        if (uphill <= 1) uphill = 2;
        if (wellD <= 0) wellD = 1;
        if (waterLvl <= 0) waterLvl = 1;
        if (buckVol <= 0) buckVol = 1;
        if (buckAscRate <= 0) buckAscRate = 1;
        if (downHill <= 0) buckAscRate = 1;
        if (volume <= 0) volume = 1;

        if (last > 1)
        {
            uphill = last;
            scenarioCONT();

        }

    } while (last != 0);

}
void scenario()
{
    do
    {
        std::cin >> uphill;
        std::cin >> wellD;
        std::cin >> waterLvl;
        std::cin >> buckVol;
        std::cin >> buckAscRate;
        std::cin >> downHill;
        std::cin >> volume;
        std::cin >> last;

        if (uphill <= 1) uphill = 2;
        if (wellD <= 0) wellD = 1;
        if (waterLvl <= 0) waterLvl = 1;
        if (buckVol <= 0) buckVol = 1;
        if (buckAscRate <= 0) buckAscRate = 1;
        if (downHill <= 0) buckAscRate = 1;
        if (volume <= 0) volume = 1;

        if (last > 1)
        {
            timeRequired();
            uphill = last;
            scenarioCONT();

        }
            scene++;
            timeRequired();

    } while (last != 0);

}

int main()
{

    scenario();

    system("pause");
}

I've been told to use ionmanip to set the precision, though i'm not 100% on how to do it. Any suggestions?


问:
how to get some text when using svg tags
How can i get some text between svg tags?

I am using this piece of code and i want some text inside the blue area:

```<code><div class="container2">
Here should be some text
<svg viewBox="1 1 500 500" preserveAspectRatio="yMinYMin meet">
<path d="M0,100 C150,200 350,1 500,100 L500,00 L0,1 Z" style="stroke:  none; fill:#05aed9;"></path>
</svg>
</code>```

And here is my fiddle: https://jsfiddle.net/ucLkwh65/1/

答:
If you add a HTML tag within the container then you can set the positioning to absolute and display the text:

```<code><div class="container2">
<h1 class="innertext">
Lorem Ipsum Dolor Sit
</h1>
<svg viewBox="1 1 500 500" preserveAspectRatio="yMinYMin meet">
    <path d="M0,100 C150,200 350,1 500,100 L500,00 L0,1 Z" style="stroke: none; fill:#05aed9;"></path>
  </svg>
</div>
</code>```

Then add the CSS:

```<code>.innertext {
  position: absolute;
  z-index: 1;
  left: 0;
  top: 0;
}
</code>```

This will create the following effect:

svg {
  display: inline-block;
  position: absolute;
  top: 0;
  left: 0;
}
svg.one {
  padding-top: 20px;
}
.container {
  display: inline-block;
  position: relative;
  width: 100%;
  padding-bottom: 100%;
  vertical-align: middle;
  overflow: hidden;
}
.innertext {
  position: absolute;
  z-index: 1;
  left: 0;
  top: 0;
}
body {
   margin: 0;
    padding: 0;
    border: 0;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <svg class="one" viewBox="0 0 500 500" preserveAspectRatio="xMinYMin meet">
    <path d="M0,100 C150,200 350,0 500,100 L500,00 L0,0 Z" style="stroke: none; fill:#1e90ff;"></path>
  </svg>

</div>

<div class="container2">
<h1 class="innertext">
Lorem Ipsum Dolor Sit
</h1>
<svg viewBox="1 1 500 500" preserveAspectRatio="yMinYMin meet">
    <path d="M0,100 C150,200 350,1 500,100 L500,00 L0,1 Z" style="stroke: none; fill:#05aed9;"></path>
  </svg>
</div></code>```

Body:
How can i get some text between svg tags?

I am using this piece of code and i want some text inside the blue area:

Here should be some text
<svg viewBox="1 1 500 500" preserveAspectRatio="yMinYMin meet">
<path d="M0,100 C150,200 350,1 500,100 L500,00 L0,1 Z" style="stroke:  none; fill:#05aed9;"></path>
</svg>

And here is my fiddle: https://jsfiddle.net/ucLkwh65/1/

Body:
If you add a HTML tag within the container then you can set the positioning to absolute and display the text:

<div class="container2">
<h1 class="innertext">
Lorem Ipsum Dolor Sit
</h1>
<svg viewBox="1 1 500 500" preserveAspectRatio="yMinYMin meet">
    <path d="M0,100 C150,200 350,1 500,100 L500,00 L0,1 Z" style="stroke: none; fill:#05aed9;"></path>
  </svg>
</div>

Then add the CSS:

.innertext {
  position: absolute;
  z-index: 1;
  left: 0;
  top: 0;
}

This will create the following effect:

svg {
  display: inline-block;
  position: absolute;
  top: 0;
  left: 0;
}
svg.one {
  padding-top: 20px;
}
.container {
  display: inline-block;
  position: relative;
  width: 100%;
  padding-bottom: 100%;
  vertical-align: middle;
  overflow: hidden;
}
.innertext {
  position: absolute;
  z-index: 1;
  left: 0;
  top: 0;
}
body {
   margin: 0;
    padding: 0;
    border: 0;
  }

<div class="container">
  <svg class="one" viewBox="0 0 500 500" preserveAspectRatio="xMinYMin meet">
    <path d="M0,100 C150,200 350,0 500,100 L500,00 L0,0 Z" style="stroke: none; fill:#1e90ff;"></path>
  </svg>

</div>

<div class="container2">
<h1 class="innertext">
Lorem Ipsum Dolor Sit
</h1>
<svg viewBox="1 1 500 500" preserveAspectRatio="yMinYMin meet">
    <path d="M0,100 C150,200 350,1 500,100 L500,00 L0,1 Z" style="stroke: none; fill:#05aed9;"></path>
  </svg>
</div>


问:
Is it safe to mix readline() and line iterators in python file processing?
Is it safe to read some lines with readline() and also use for line in file, and is it guaranteed to use the same file position?

Usually, I want to disregard the first line (headers), so I do this:

```<code>FI = open("myfile.txt")
FI.readline()             # disregard the first line
for line in FI:
    my_process(line)
FI.close()
</code>```

Is this safe, i.e., is it guaranteed that the same file position variable is used while iterating lines?

答:
It is safe if the mechanisms are under control.

=============================

.

There is no problem to do an iteration after a readline() instruction

But there's one to execute a readline() after an iteration

I created a 'rara.txt' file with this text ( each line have a length of 5 because of the '\r\n' end of line under Windows)

```<code>1AA
2BB
3CC
4DD
5EE
6FF
7GG
8HH
9II
10j
11k
12l
13m
14n
15o
</code>```

And I executed

```<code>FI  = open("rara.txt",'rb')
lineR = FI.readline()
print repr(lineR)+'   len=='+str(len(lineR))+\
      '  FI.tell() after FI.readline() : ',FI.tell(),'\n'

cnt = 0
for line in FI:
    cnt += 1
    print 'cnt=='+str(cnt)+'   '+repr(line)+'   len=='+str(len(line))+\
          "  FI.tell() after 'line in FI' : ",FI.tell()
    if cnt==4:
        break
print "\nFI.tell() after iteration 'for line in FI' : ",FI.tell(),'\n'

lineR = FI.readline()
print repr(lineR)+'   len=='+str(len(lineR))+\
      '  FI.tell() after FI.readline() : ',FI.tell()
lineR = FI.readline()
print repr(lineR)+'   len=='+str(len(lineR))+\
      '  FI.tell() after FI.readline() : ',FI.tell(),'\n'

for line in FI:
    print 'cnt=='+str(cnt)+'   '+repr(line)+'   len=='+str(len(line))+\
          "  FI.tell() after 'line in FI' : ",FI.tell()
print "\nFI.tell() after iteration 'for line in FI' : ",FI.tell(),'\n'
</code>```

The result is

```<code>'1AA\r\n'   len==5  FI.tell() after FI.readline() :  5

cnt==1   '2BB\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==2   '3CC\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==3   '4DD\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==4   '5EE\r\n'   len==5  FI.tell() after 'line in FI' :  75

FI.tell() after iteration 'for line in FI' :  75

Traceback (most recent call last):
  File "E:\Python\NNN codes\esssssai.py", line 16, in <module>
    lineR = FI.readline()
ValueError: Mixing iteration and read methods would lose data
</code>```

.

A strange thing is that if we renew the "cursor" by tell() , method readline() can be active again after an iteration (I don't know what is the behind-the-scene mechanism of "cursor" renewal ):

```<code>FI  = open("rara.txt",'rb')
lineR = FI.readline()
print repr(lineR)+'   len=='+str(len(lineR))+\
      '  FI.tell() after FI.readline() : ',FI.tell(),'\n'

cnt = 0
for line in FI:
    cnt += 1
    print 'cnt=='+str(cnt)+'   '+repr(line)+'   len=='+str(len(line))+\
          "  FI.tell() after 'line in FI' : ",FI.tell()
    if cnt==4:
        pos = FI.tell()
        break
print "\nFI.tell() after iteration 'for line in FI' : ",FI.tell(),'\n'

FI.seek(pos)

lineR = FI.readline()
print repr(lineR)+'   len=='+str(len(lineR))+\
      '  FI.tell() after FI.readline() : ',FI.tell()
lineR = FI.readline()
print repr(lineR)+'   len=='+str(len(lineR))+\
      '  FI.tell() after FI.readline() : ',FI.tell(),'\n'

for line in FI:
    print 'cnt=='+str(cnt)+'   '+repr(line)+'   len=='+str(len(line))+\
          "  FI.tell() after 'line in FI' : ",FI.tell()
print "\nFI.tell() after iteration 'for line in FI' : ",FI.tell(),'\n'
</code>```

result

```<code>'1AA\r\n'   len==5  FI.tell() after FI.readline() :  5

cnt==1   '2BB\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==2   '3CC\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==3   '4DD\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==4   '5EE\r\n'   len==5  FI.tell() after 'line in FI' :  75

FI.tell() after iteration 'for line in FI' :  75

''   len==0  FI.tell() after FI.readline() :  75
''   len==0  FI.tell() after FI.readline() :  75

FI.tell() after iteration 'for line in FI' :  75
</code>```

Anyway, we note that even if the algorithm is to read only 4 lines during iteration (thanks to the count cnt) , the cursor goes already at the end of the file from the very beginning of the iteration: all the file, ahead of the current position when the iteration begins, is once read.

So pos = FI.tell() before the break doesn't give the position after the 4 lines read, but the position of the end of the file.

.

We must do something special if we want to readline() again , after an iteration , from the exact point at which ended the 4 lines reading during an iteration:

```<code>FI  = open("rara.txt",'rb')
lineR = FI.readline()
print repr(lineR)+'   len=='+str(len(lineR))+\
      '  FI.tell() after FI.readline() : ',FI.tell(),'\n'

cnt = 0
pos = FI.tell()
for line in FI:
    cnt += 1
    pos += len(line)
    print 'cnt=='+str(cnt)+'   '+repr(line)+'   len=='+str(len(line))+\
          "  FI.tell() after 'line in FI' : ",FI.tell()
    if cnt==4:
        break
print "\nFI.tell() after iteration 'for line in FI' : ",FI.tell()
print "    pos   after iteration 'for line in FI' : ",pos,'\n'

FI.seek(pos)

lineR = FI.readline()
print repr(lineR)+'   len=='+str(len(lineR))+\
      '  FI.tell() after FI.readline() : ',FI.tell()
lineR = FI.readline()
print repr(lineR)+'   len=='+str(len(lineR))+\
      '  FI.tell() after FI.readline() : ',FI.tell(),'\n'

cnt = 0
for line in FI:
    cnt += 1
    print 'cnt=='+str(cnt)+'   '+repr(line)+'   len=='+str(len(line))+\
          "  FI.tell() after 'line in FI' : ",FI.tell()
print "\nFI.tell() after iteration 'for line in FI' : ",FI.tell(),'\n'
</code>```

result

```<code>'1AA\r\n'   len==5  FI.tell() after FI.readline() :  5

cnt==1   '2BB\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==2   '3CC\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==3   '4DD\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==4   '5EE\r\n'   len==5  FI.tell() after 'line in FI' :  75

FI.tell() after iteration 'for line in FI' :  75
    pos   after iteration 'for line in FI' :  25

'6FF\r\n'   len==5  FI.tell() after FI.readline() :  30
'7GG\r\n'   len==5  FI.tell() after FI.readline() :  35

cnt==1   '8HH\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==2   '9II\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==3   '10j\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==4   '11k\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==5   '12l\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==6   '13m\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==7   '14n\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==8   '15o\r\n'   len==5  FI.tell() after 'line in FI' :  75

FI.tell() after iteration 'for line in FI' :  75
</code>```

.

All these manipulations are possible only because the file was opened in binary mode, because I am on Windows which uses '\r\n' as end of lines to write a file, even if it is ordered to write (in 'w' mode) something like 'abcdef\n',

while on the other hand Python transforms (in mode 'r') all the '\r\n' in '\n'.

That's a mess, and to control all this, files must be opened in 'rb' if we want to do precise manipulations.

.

You know what ? I love these games in the positions of a file

Body:
Is it safe to read some lines with readline() and also use for line in file, and is it guaranteed to use the same file position?

Usually, I want to disregard the first line (headers), so I do this:

FI = open("myfile.txt")
FI.readline()             # disregard the first line
for line in FI:
    my_process(line)
FI.close()

Is this safe, i.e., is it guaranteed that the same file position variable is used while iterating lines?

Body:
It is safe if the mechanisms are under control.

=============================

.

There is no problem to do an iteration after a readline() instruction

But there's one to execute a readline() after an iteration

I created a 'rara.txt' file with this text ( each line have a length of 5 because of the '\r\n' end of line under Windows)

1AA
2BB
3CC
4DD
5EE
6FF
7GG
8HH
9II
10j
11k
12l
13m
14n
15o

And I executed

FI  = open("rara.txt",'rb')
lineR = FI.readline()
print repr(lineR)+'   len=='+str(len(lineR))+\
      '  FI.tell() after FI.readline() : ',FI.tell(),'\n'

cnt = 0
for line in FI:
    cnt += 1
    print 'cnt=='+str(cnt)+'   '+repr(line)+'   len=='+str(len(line))+\
          "  FI.tell() after 'line in FI' : ",FI.tell()
    if cnt==4:
        break
print "\nFI.tell() after iteration 'for line in FI' : ",FI.tell(),'\n'

lineR = FI.readline()
print repr(lineR)+'   len=='+str(len(lineR))+\
      '  FI.tell() after FI.readline() : ',FI.tell()
lineR = FI.readline()
print repr(lineR)+'   len=='+str(len(lineR))+\
      '  FI.tell() after FI.readline() : ',FI.tell(),'\n'

for line in FI:
    print 'cnt=='+str(cnt)+'   '+repr(line)+'   len=='+str(len(line))+\
          "  FI.tell() after 'line in FI' : ",FI.tell()
print "\nFI.tell() after iteration 'for line in FI' : ",FI.tell(),'\n'

The result is

'1AA\r\n'   len==5  FI.tell() after FI.readline() :  5

cnt==1   '2BB\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==2   '3CC\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==3   '4DD\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==4   '5EE\r\n'   len==5  FI.tell() after 'line in FI' :  75

FI.tell() after iteration 'for line in FI' :  75

Traceback (most recent call last):
  File "E:\Python\NNN codes\esssssai.py", line 16, in <module>
    lineR = FI.readline()
ValueError: Mixing iteration and read methods would lose data

.

A strange thing is that if we renew the "cursor" by tell() , method readline() can be active again after an iteration (I don't know what is the behind-the-scene mechanism of "cursor" renewal ):

FI  = open("rara.txt",'rb')
lineR = FI.readline()
print repr(lineR)+'   len=='+str(len(lineR))+\
      '  FI.tell() after FI.readline() : ',FI.tell(),'\n'

cnt = 0
for line in FI:
    cnt += 1
    print 'cnt=='+str(cnt)+'   '+repr(line)+'   len=='+str(len(line))+\
          "  FI.tell() after 'line in FI' : ",FI.tell()
    if cnt==4:
        pos = FI.tell()
        break
print "\nFI.tell() after iteration 'for line in FI' : ",FI.tell(),'\n'

FI.seek(pos)

lineR = FI.readline()
print repr(lineR)+'   len=='+str(len(lineR))+\
      '  FI.tell() after FI.readline() : ',FI.tell()
lineR = FI.readline()
print repr(lineR)+'   len=='+str(len(lineR))+\
      '  FI.tell() after FI.readline() : ',FI.tell(),'\n'

for line in FI:
    print 'cnt=='+str(cnt)+'   '+repr(line)+'   len=='+str(len(line))+\
          "  FI.tell() after 'line in FI' : ",FI.tell()
print "\nFI.tell() after iteration 'for line in FI' : ",FI.tell(),'\n'

result

'1AA\r\n'   len==5  FI.tell() after FI.readline() :  5

cnt==1   '2BB\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==2   '3CC\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==3   '4DD\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==4   '5EE\r\n'   len==5  FI.tell() after 'line in FI' :  75

FI.tell() after iteration 'for line in FI' :  75

''   len==0  FI.tell() after FI.readline() :  75
''   len==0  FI.tell() after FI.readline() :  75

FI.tell() after iteration 'for line in FI' :  75

Anyway, we note that even if the algorithm is to read only 4 lines during iteration (thanks to the count cnt) , the cursor goes already at the end of the file from the very beginning of the iteration: all the file, ahead of the current position when the iteration begins, is once read.

So pos = FI.tell() before the break doesn't give the position after the 4 lines read, but the position of the end of the file.

.

We must do something special if we want to readline() again , after an iteration , from the exact point at which ended the 4 lines reading during an iteration:

FI  = open("rara.txt",'rb')
lineR = FI.readline()
print repr(lineR)+'   len=='+str(len(lineR))+\
      '  FI.tell() after FI.readline() : ',FI.tell(),'\n'

cnt = 0
pos = FI.tell()
for line in FI:
    cnt += 1
    pos += len(line)
    print 'cnt=='+str(cnt)+'   '+repr(line)+'   len=='+str(len(line))+\
          "  FI.tell() after 'line in FI' : ",FI.tell()
    if cnt==4:
        break
print "\nFI.tell() after iteration 'for line in FI' : ",FI.tell()
print "    pos   after iteration 'for line in FI' : ",pos,'\n'

FI.seek(pos)

lineR = FI.readline()
print repr(lineR)+'   len=='+str(len(lineR))+\
      '  FI.tell() after FI.readline() : ',FI.tell()
lineR = FI.readline()
print repr(lineR)+'   len=='+str(len(lineR))+\
      '  FI.tell() after FI.readline() : ',FI.tell(),'\n'

cnt = 0
for line in FI:
    cnt += 1
    print 'cnt=='+str(cnt)+'   '+repr(line)+'   len=='+str(len(line))+\
          "  FI.tell() after 'line in FI' : ",FI.tell()
print "\nFI.tell() after iteration 'for line in FI' : ",FI.tell(),'\n'

result

'1AA\r\n'   len==5  FI.tell() after FI.readline() :  5

cnt==1   '2BB\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==2   '3CC\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==3   '4DD\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==4   '5EE\r\n'   len==5  FI.tell() after 'line in FI' :  75

FI.tell() after iteration 'for line in FI' :  75
    pos   after iteration 'for line in FI' :  25

'6FF\r\n'   len==5  FI.tell() after FI.readline() :  30
'7GG\r\n'   len==5  FI.tell() after FI.readline() :  35

cnt==1   '8HH\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==2   '9II\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==3   '10j\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==4   '11k\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==5   '12l\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==6   '13m\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==7   '14n\r\n'   len==5  FI.tell() after 'line in FI' :  75
cnt==8   '15o\r\n'   len==5  FI.tell() after 'line in FI' :  75

FI.tell() after iteration 'for line in FI' :  75

.

All these manipulations are possible only because the file was opened in binary mode, because I am on Windows which uses '\r\n' as end of lines to write a file, even if it is ordered to write (in 'w' mode) something like 'abcdef\n',

while on the other hand Python transforms (in mode 'r') all the '\r\n' in '\n'.

That's a mess, and to control all this, files must be opened in 'rb' if we want to do precise manipulations.

.

You know what ? I love these games in the positions of a file


问:
Test two different npm package versions at the same time
When I create an npm package, sometimes it would face the need to backward old dependency package version.

If the new version has new api, I may write the code in this pattern:

```<code>import pkg from 'some-pkg';
const isNewVersion = pkg.newVersionApi !== 'undefined';

if (isNewversion) {
  pkg.newVersionApi();
} else {
  pkg.oldVersionApi(); // backward compatible api
}
</code>```

And with this pattern, when I want to write the test, I only can test the installed version code. The other version's code can't be tested.

For real example, in React v15 and v16, React v16 has new API Portal. Before Portal release, v15 has unstable_renderSubtreeIntoContainer api to realize similar feature.

So the code for React would be like:

```<code>import ReactDOM from 'react-dom';
const isV16 = ReactDOM.createPortal !== 'undefined';

if (isV16) {
  ReactDOM.createPortal(...);
} else {
  ReactDOM.unstable_renderSubtreeIntoContainer(...);
}
</code>```

So I want to ask is there any method to test with different dependency version?

Currently, one method I think of is to install the other version again and test it. But it only can do on local. It can't work on ci and it can't count in coverage together.

I think that is not only for react test. It may face on node.js test. Any suggestion can be discussed.

Updated

This question maybe is related to install two versions dependency in npm. But I know currently installing two versions dependency is not workable.

答:
Here is a might be solution, not sure it will work as you expect. But, you will have a direction to move forward.

package.json

```<code>{
  "name": "express-demo",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.3",
    "express": "~4.15.2",
    "jade": "~1.11.0",
    "morgan": "~1.8.1",
    "serve-favicon": "~2.4.2",
    "webpack": "^3.8.1",
    "webpack-dev-middleware": "^1.12.0",
    "webpack-hot-middleware": "^2.20.0"
  },
  "customDependecies": {
    "body-parser": [
      "",
      "1.18.1",
      "1.18.0"
    ]
  }
}
</code>```

Note in above package.json file, I have added a new key customDependecies which I will use for installing multiple dependencies. Here I am using body-parser package for demo. Next you need file, that can read this key and install the deps.

install-deps.js

```<code>const {spawnSync} = require('child_process');
const fs = require('fs');

const customDependencies = require('./package.json').customDependecies;

spawnSync('mkdir', ['./node_modules/.tmp']);

for (var dependency in customDependencies) {
  customDependencies[dependency].forEach((version) => {
    console.log(`Installing ${dependency}@${version}`);
    if (version) {
      spawnSync('npm', ['install', `${dependency}@${version}`]);
      spawnSync('mv', [`./node_modules/${dependency}`, `./node_modules/.tmp/${dependency}@${version}`]);
    } else {
      spawnSync('npm', ['install', `${dependency}`]);
      spawnSync('mv', [`./node_modules/${dependency}`, `./node_modules/.tmp/${dependency}`]);
    }
  });

  customDependencies[dependency].forEach((version) => {
    console.log(`Moving ${dependency}@${version}`);
    if (version) {
      spawnSync('mv', [`./node_modules/.tmp/${dependency}@${version}`, `./node_modules/${dependency}@${version}`]);
    } else {
      spawnSync('mv', [`./node_modules/.tmp/${dependency}`, `./node_modules/${dependency}`]);
    }
  });
}
spawnSync('rm', ['-rf', './node_modules/.tmp']);
console.log(`Installing Deps finished.`);
</code>```

Here, I am installing deps one by one in tmp folder and once installed, I am moving them to ./node_modules folder.

Once, everything is installed, you can check the versions like below

index.js

```<code>var bodyParser = require('body-parser/package.json');
var bodyParser1181 = require('body-parser@1.18.1/package.json');
var bodyParser1182 = require('body-parser@1.18.0/package.json');

console.log(bodyParser.version);
console.log(bodyParser1181.version);
console.log(bodyParser1182.version);
</code>```

Hope, this will serve your purpose.

Body:
When I create an npm package, sometimes it would face the need to backward old dependency package version.

If the new version has new api, I may write the code in this pattern:

import pkg from 'some-pkg';
const isNewVersion = pkg.newVersionApi !== 'undefined';

if (isNewversion) {
  pkg.newVersionApi();
} else {
  pkg.oldVersionApi(); // backward compatible api
}

And with this pattern, when I want to write the test, I only can test the installed version code. The other version's code can't be tested.

For real example, in React v15 and v16, React v16 has new API Portal. Before Portal release, v15 has unstable_renderSubtreeIntoContainer api to realize similar feature.

So the code for React would be like:

import ReactDOM from 'react-dom';
const isV16 = ReactDOM.createPortal !== 'undefined';

if (isV16) {
  ReactDOM.createPortal(...);
} else {
  ReactDOM.unstable_renderSubtreeIntoContainer(...);
}

So I want to ask is there any method to test with different dependency version?

Currently, one method I think of is to install the other version again and test it. But it only can do on local. It can't work on ci and it can't count in coverage together.

I think that is not only for react test. It may face on node.js test. Any suggestion can be discussed.

Updated

This question maybe is related to install two versions dependency in npm. But I know currently installing two versions dependency is not workable.

Body:
Here is a might be solution, not sure it will work as you expect. But, you will have a direction to move forward.

package.json

{
  "name": "express-demo",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.3",
    "express": "~4.15.2",
    "jade": "~1.11.0",
    "morgan": "~1.8.1",
    "serve-favicon": "~2.4.2",
    "webpack": "^3.8.1",
    "webpack-dev-middleware": "^1.12.0",
    "webpack-hot-middleware": "^2.20.0"
  },
  "customDependecies": {
    "body-parser": [
      "",
      "1.18.1",
      "1.18.0"
    ]
  }
}

Note in above package.json file, I have added a new key customDependecies which I will use for installing multiple dependencies. Here I am using body-parser package for demo. Next you need file, that can read this key and install the deps.

install-deps.js

const {spawnSync} = require('child_process');
const fs = require('fs');

const customDependencies = require('./package.json').customDependecies;

spawnSync('mkdir', ['./node_modules/.tmp']);

for (var dependency in customDependencies) {
  customDependencies[dependency].forEach((version) => {
    console.log(`Installing ${dependency}@${version}`);
    if (version) {
      spawnSync('npm', ['install', `${dependency}@${version}`]);
      spawnSync('mv', [`./node_modules/${dependency}`, `./node_modules/.tmp/${dependency}@${version}`]);
    } else {
      spawnSync('npm', ['install', `${dependency}`]);
      spawnSync('mv', [`./node_modules/${dependency}`, `./node_modules/.tmp/${dependency}`]);
    }
  });

  customDependencies[dependency].forEach((version) => {
    console.log(`Moving ${dependency}@${version}`);
    if (version) {
      spawnSync('mv', [`./node_modules/.tmp/${dependency}@${version}`, `./node_modules/${dependency}@${version}`]);
    } else {
      spawnSync('mv', [`./node_modules/.tmp/${dependency}`, `./node_modules/${dependency}`]);
    }
  });
}
spawnSync('rm', ['-rf', './node_modules/.tmp']);
console.log(`Installing Deps finished.`);

Here, I am installing deps one by one in tmp folder and once installed, I am moving them to ./node_modules folder.

Once, everything is installed, you can check the versions like below

index.js

var bodyParser = require('body-parser/package.json');
var bodyParser1181 = require('body-parser@1.18.1/package.json');
var bodyParser1182 = require('body-parser@1.18.0/package.json');

console.log(bodyParser.version);
console.log(bodyParser1181.version);
console.log(bodyParser1182.version);

Hope, this will serve your purpose.


问:
efficiently calculate list of 3d rotation matrices in numpy or scipy
I have a list of N unit-normalized 3D vectors p stored in a numpy ndarray with shape (N, 3). I have another such list, q. I want to calculate an ndarray U of shape (N, 3, 3) storing the rotation matrices that rotate each point in p to the corresponding point q.

The list of rotation matrices U should satisfy:

```<code>np.all(np.einsum('ijk,ik->ij', U, p) ==  q)
</code>```

On a point-by-point basis, the problem reduces to being able to compute a rotation matrix for a rotation of some angle about some axis. Code solving the single-point case appears below:

```<code>def rotation_matrix(angle, direction):
    direction = np.atleast_1d(direction).astype('f4')
    sina = np.sin(angle)
    cosa = np.cos(angle)
    direction = direction/np.sqrt(np.sum(direction*direction))

    R = np.diag([cosa, cosa, cosa])
    R += np.outer(direction, direction) * (1.0 - cosa)
    direction *= sina
    R += np.array(((0.0, -direction[2], direction[1]),
                (direction[2], 0.0, -direction[0]),
                (-direction[1], direction[0],  0.0)))
    return R
</code>```

What I need is a function that behaves exactly as the above function, but instead of accepting a single angle and a single direction, it accepts an angles array of shape (npts, ) and a directions array of shape (npts, 3). The code below is only partially finished - the problem is that neither np.diag nor np.outer accept an axis argument

```<code>def rotation_matrices(angles, directions):
    directions = np.atleast_2d(directions)
    angles = np.atleast_1d(angles)
    npts = directions.shape[0]
    directions = directions/np.sqrt(np.sum(directions*directions, axis=1)).reshape((npts, 1))

    sina = np.sin(angles)
    cosa = np.cos(angles)

    #  Lines below require extension to 2d case - np.diag and np.outer do not support axis arguments
    R = np.diag([cosa, cosa, cosa])
    R += np.outer(directions, directions) * (1.0 - cosa)
    directions *= sina
    R += np.array(((0.0, -directions[2], directions[1]),
                (directions[2], 0.0, -directions[0]),
                (-directions[1], directions[0],  0.0)))
    return R
</code>```

Does either numpy or scipy have a compact vectorized function computing the appropriate rotation matrices in a way that avoids using for loops? The problem is that neither np.diag nor np.outer accept axis as an argument. My application will have N be very large, 1e7 or greater, so a vectorized function that keeps all the relevant axes aligned is necessary for performance reasons.

答:
Dropping this here for now, will explain later.  Using levi-cevita symbols from @jaime's answer here and the matrix form of the Rodrigues formula here and some algebra based on k = (a x b)/sin(theta)

```<code>def rotmatx(p, q):
    eijk = np.zeros((3, 3, 3))
    eijk[0, 1, 2] = eijk[1, 2, 0] = eijk[2, 0, 1] = 1
    eijk[0, 2, 1] = eijk[2, 1, 0] = eijk[1, 0, 2] = -1
    d = (p * q).sum(-1)[:, None, None]
    c = (p.dot(eijk) @ q[..., None]).squeeze()   # cross product (optimized)
    cx = c.dot(eijk)
    return np.eye(3) + cx + cx @ cx / (1 + d)
</code>```

EDIT: dang. question changed.

```<code>def rotation_matrices(angles, directions):
    eijk = np.zeros((3, 3, 3))
    eijk[0, 1, 2] = eijk[1, 2, 0] = eijk[2, 0, 1] = 1
    eijk[0, 2, 1] = eijk[2, 1, 0] = eijk[1, 0, 2] = -1
    theta = angles[:, None, None]
    K = directions.dot(eijk)
    return np.eye(3) + K * np.sin(theta) + K @ K * (1 - np.cos(theta))
</code>```

Body:
I have a list of N unit-normalized 3D vectors p stored in a numpy ndarray with shape (N, 3). I have another such list, q. I want to calculate an ndarray U of shape (N, 3, 3) storing the rotation matrices that rotate each point in p to the corresponding point q.

The list of rotation matrices U should satisfy:

np.all(np.einsum('ijk,ik->ij', U, p) ==  q)

On a point-by-point basis, the problem reduces to being able to compute a rotation matrix for a rotation of some angle about some axis. Code solving the single-point case appears below:

def rotation_matrix(angle, direction):
    direction = np.atleast_1d(direction).astype('f4')
    sina = np.sin(angle)
    cosa = np.cos(angle)
    direction = direction/np.sqrt(np.sum(direction*direction))

    R = np.diag([cosa, cosa, cosa])
    R += np.outer(direction, direction) * (1.0 - cosa)
    direction *= sina
    R += np.array(((0.0, -direction[2], direction[1]),
                (direction[2], 0.0, -direction[0]),
                (-direction[1], direction[0],  0.0)))
    return R

What I need is a function that behaves exactly as the above function, but instead of accepting a single angle and a single direction, it accepts an angles array of shape (npts, ) and a directions array of shape (npts, 3). The code below is only partially finished - the problem is that neither np.diag nor np.outer accept an axis argument

def rotation_matrices(angles, directions):
    directions = np.atleast_2d(directions)
    angles = np.atleast_1d(angles)
    npts = directions.shape[0]
    directions = directions/np.sqrt(np.sum(directions*directions, axis=1)).reshape((npts, 1))

    sina = np.sin(angles)
    cosa = np.cos(angles)

    #  Lines below require extension to 2d case - np.diag and np.outer do not support axis arguments
    R = np.diag([cosa, cosa, cosa])
    R += np.outer(directions, directions) * (1.0 - cosa)
    directions *= sina
    R += np.array(((0.0, -directions[2], directions[1]),
                (directions[2], 0.0, -directions[0]),
                (-directions[1], directions[0],  0.0)))
    return R

Does either numpy or scipy have a compact vectorized function computing the appropriate rotation matrices in a way that avoids using for loops? The problem is that neither np.diag nor np.outer accept axis as an argument. My application will have N be very large, 1e7 or greater, so a vectorized function that keeps all the relevant axes aligned is necessary for performance reasons.

Body:
Dropping this here for now, will explain later.  Using levi-cevita symbols from @jaime's answer here and the matrix form of the Rodrigues formula here and some algebra based on k = (a x b)/sin(theta)

def rotmatx(p, q):
    eijk = np.zeros((3, 3, 3))
    eijk[0, 1, 2] = eijk[1, 2, 0] = eijk[2, 0, 1] = 1
    eijk[0, 2, 1] = eijk[2, 1, 0] = eijk[1, 0, 2] = -1
    d = (p * q).sum(-1)[:, None, None]
    c = (p.dot(eijk) @ q[..., None]).squeeze()   # cross product (optimized)
    cx = c.dot(eijk)
    return np.eye(3) + cx + cx @ cx / (1 + d)

EDIT: dang. question changed.

def rotation_matrices(angles, directions):
    eijk = np.zeros((3, 3, 3))
    eijk[0, 1, 2] = eijk[1, 2, 0] = eijk[2, 0, 1] = 1
    eijk[0, 2, 1] = eijk[2, 1, 0] = eijk[1, 0, 2] = -1
    theta = angles[:, None, None]
    K = directions.dot(eijk)
    return np.eye(3) + K * np.sin(theta) + K @ K * (1 - np.cos(theta))


问:
How to get JSON Data sent through postman tool using post method?
I'm trying to get a JSON data which is sent as JSON data using postman tool and trying to receive it my post() method.

```<code>    var express = require('express');
    var app = express();

    app.post('/myData',function(req,res){
        console.log("--->",req.body);
    });

var server = app.listen(8080,function(){});
</code>```

This is the JSON data sent through postman tool

I'm getting undefined in my console as
"---> undefined"

I'm trying to retrieve the JSON data set in my postman tool to either my console or browser

答:
Corrected. Please try to run this code.</p>

```<code>var express = require('express');
var app = express();

app.post('/myData', function (req, res) {

    req.on('data', function (data) {
        console.log("--->",data.toString());
        res.send("Received");
    });
});

var server = app.listen(8080, function () { });
</code>```

Body:
I'm trying to get a JSON data which is sent as JSON data using postman tool and trying to receive it my post() method.

    var express = require('express');
    var app = express();

    app.post('/myData',function(req,res){
        console.log("--->",req.body);
    });

var server = app.listen(8080,function(){});

This is the JSON data sent through postman tool

I'm getting undefined in my console as
"---> undefined"

I'm trying to retrieve the JSON data set in my postman tool to either my console or browser

Body:
Corrected. Please try to run this code.

var express = require('express');
var app = express();

app.post('/myData', function (req, res) {

    req.on('data', function (data) {
        console.log("--->",data.toString());
        res.send("Received");
    });
});

var server = app.listen(8080, function () { });


问:
Right usage of Qt5 elements regarding memory management
I have the following common scenario:

```<code>class A : public QDialog
{
    Q_OBJECT
public:
    A(QWidget *parent=0);
private:
    QFormLayout *m_formLayout;
    QLinedEdit *m_lineEditTest;
};

A::A(QWidget *parent)
{
    m_formLayout = new QFormLayout(ui.widget_Test);
    m_formLayout->setMargin(0);
    m_formLayout->setSpacing(0);

    m_lineEditTest = new QLineEdit();
    m_formLayout->addWidget(m_lineEditTest);

    ui.widget_Test->setLayout(m_formLayout);
}

A::~A()
{
    delete m_lineEditTest, m_formLayout;
}
</code>```

Is this the correct approach to use class member variables for Qt GUI elements and delete them after the destruction of the QDialog A?

Why I'm asking: I want to avoid raw pointers in my application and replace it with smart pointers, <s>but it's not recommended to use Qt5 with e.g. std::shared_ptr</s>! So should I use https://wiki.qt.io/Smart_Pointers and if yes which one for my scenario? Thx

答:
Here is a summary: (from https://forum.qt.io/topic/65443/raw-pointers-in-qt/5)

```<code>class MyObject : public QObject
{
    Q_OBJECT

public:
    MyObject(QObject *parent = nullptr) {
        obj1 = new QObject(this); // Sets the parent using the 'parent' constructor parameter

        obj2 = new QObject;
        obj2->setParent(this); // Sets the parent using QObject::setParent()

        obj3 = new QObject; // No parent
    }

private:
    QObject *obj1;
    QObject *obj2;
    QObject *obj3;
};
</code>```

When you delete your MyObject, it will automatically delete obj1 and obj2 because of the parent-child relationship. However, obj3 will not get deleted because you did not set it as a child, so the memory for obj3 gets leaked.

There are many ways to handle deletions:

do it manually

use smart pointers

use QObject's parent-child system

So there is no problem to use smart pointers with Qt5 if you don't mix it with parent-child system!

Body:
I have the following common scenario:

class A : public QDialog
{
    Q_OBJECT
public:
    A(QWidget *parent=0);
private:
    QFormLayout *m_formLayout;
    QLinedEdit *m_lineEditTest;
};

A::A(QWidget *parent)
{
    m_formLayout = new QFormLayout(ui.widget_Test);
    m_formLayout->setMargin(0);
    m_formLayout->setSpacing(0);

    m_lineEditTest = new QLineEdit();
    m_formLayout->addWidget(m_lineEditTest);

    ui.widget_Test->setLayout(m_formLayout);
}

A::~A()
{
    delete m_lineEditTest, m_formLayout;
}

Is this the correct approach to use class member variables for Qt GUI elements and delete them after the destruction of the QDialog A?

Why I'm asking: I want to avoid raw pointers in my application and replace it with smart pointers, <s>but it's not recommended to use Qt5 with e.g. std::shared_ptr</s>! So should I use https://wiki.qt.io/Smart_Pointers and if yes which one for my scenario? Thx

Body:
Here is a summary: (from https://forum.qt.io/topic/65443/raw-pointers-in-qt/5)

class MyObject : public QObject
{
    Q_OBJECT

public:
    MyObject(QObject *parent = nullptr) {
        obj1 = new QObject(this); // Sets the parent using the 'parent' constructor parameter

        obj2 = new QObject;
        obj2->setParent(this); // Sets the parent using QObject::setParent()

        obj3 = new QObject; // No parent
    }

private:
    QObject *obj1;
    QObject *obj2;
    QObject *obj3;
};

When you delete your MyObject, it will automatically delete obj1 and obj2 because of the parent-child relationship. However, obj3 will not get deleted because you did not set it as a child, so the memory for obj3 gets leaked.

There are many ways to handle deletions:

do it manually

use smart pointers

use QObject's parent-child system

So there is no problem to use smart pointers with Qt5 if you don't mix it with parent-child system!