问:
No matching overload function found Error
I am trying to return a vector with template T with data from a file to be searched through in another function.

The program I am working on is a program that stores the name, date of birth, and address that was inputted to the program. I have tried to store the returned vector in another vector with the template type but it keeps on showing:

Error   C2672    'getDataToVector': no matching overloaded function found

Error   C2783    'std::vector> getDataToVector(std::ifstream)': could not deduce template argument for 'T'

template <class T>
void searchData(vector<string>& name, vector<int>& birthdate, vector<string>& address) {
    bool found = false;
    string entry;
    string line;
    int i = 0;

    cout << "Please enter the name you want to search: " << endl;
    getline(cin, entry);

    std::ifstream in;
    in.open("test_file.txt");
    vector<T> file_data = getDataToVector(in);

    while (!found) {
        if (std::find(file_data.begin(), file_data.end(), entry) != file_data.end()) {
            cout << "The name is found" << endl;
            cout << file_data[i] << endl;
            found = true;
        }
        i++;
    }

}

template <class T>
vector<T> getDataToVector(std::ifstream infile) {
    vector<T> data;
    string line;

    while (getline(infile, line)) {
        data.push_back(line);
    }
    return data;
}
```

I am a beginner in c++ programming and am very appreciative for any help anyone can give me.

答:
The error says it cannot deduce what T in getDataToVector should be. It can either be deduced from arguments ( not applicable in your case) or you can set it explicitly: getDataToVector<std::string>(in); means T==std::string. In your case you want to pass on the T from searchData - > getDataToVector<T>(in);

But looking at your code there's no need for templates at all, line is always std::string so data.push_back(line); means that only std::vector<std::string> makes sense. Same for searchData as the T is reduntand and is not even part of the function signature.

Body:
I am trying to return a vector with template T with data from a file to be searched through in another function.

The program I am working on is a program that stores the name, date of birth, and address that was inputted to the program. I have tried to store the returned vector in another vector with the template type but it keeps on showing:

Error   C2672    'getDataToVector': no matching overloaded function found

Error   C2783    'std::vector> getDataToVector(std::ifstream)': could not deduce template argument for 'T'

template <class T>
void searchData(vector<string>& name, vector<int>& birthdate, vector<string>& address) {
    bool found = false;
    string entry;
    string line;
    int i = 0;

    cout << "Please enter the name you want to search: " << endl;
    getline(cin, entry);

    std::ifstream in;
    in.open("test_file.txt");
    vector<T> file_data = getDataToVector(in);

    while (!found) {
        if (std::find(file_data.begin(), file_data.end(), entry) != file_data.end()) {
            cout << "The name is found" << endl;
            cout << file_data[i] << endl;
            found = true;
        }
        i++;
    }

}

template <class T>
vector<T> getDataToVector(std::ifstream infile) {
    vector<T> data;
    string line;

    while (getline(infile, line)) {
        data.push_back(line);
    }
    return data;
}

I am a beginner in c++ programming and am very appreciative for any help anyone can give me.


来源: stackexchange

问:
Moving left brace in C code to the next line?
I have several C source files that need to have one particular formatting feature changed.  In some parts of the file,

```<code>if (x == NULL) {
    ...
}
</code>```

needs to be changed to

```<code>if (x == NULL)
{
    ...
}
</code>```

I was hoping to use the "indent" command, but it's far too aggressive.  It wants to change the entire file with all options.

I suppose I can do this in Perl or maybe even Sed, but I don't know either well enough to figure that out.

答:
Looks like today is my lucky day, as it appears I figured it out:

```<code>sed 's/^\([ ]*\)\(if (.* == NULL)\) {$/\1\2\n\1{/g' <filename>
</code>```

Can someone confirm that this is correct?

ContentLicense: CC BY-SA 4.0

Body:
I have several C source files that need to have one particular formatting feature changed.  In some parts of the file,

if (x == NULL) {
    ...
}

needs to be changed to

if (x == NULL)
{
    ...
}

I was hoping to use the "indent" command, but it's far too aggressive.  It wants to change the entire file with all options.

I suppose I can do this in Perl or maybe even Sed, but I don't know either well enough to figure that out.

Body:
Looks like today is my lucky day, as it appears I figured it out:

sed 's/^\([ ]*\)\(if (.* == NULL)\) {$/\1\2\n\1{/g' <filename>

Can someone confirm that this is correct?


问:
404 error when query string contains com1 for WebApi hosted on IIS 10
I have a simple WebApi solution hosted on IIS10.

I have a ProductController class that inherits ApiController. This class has a method GetProduct

```<code> [HttpGet]
    [Route("api/product/{productName}")]
    public object GetProduct(string productName)
    {
        return "abc";
    }
</code>```

When I try to hit the following api through postman

http://localhost:10000/api/product/com1?query=test

I get a 404 error, Tried to create a folder by the same name (com1) but got an error as well. Then found out that I cannot have the following values in my api
CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9.

I tried adding the following entries in IIS
under Request Filtering

Am I missing out on anything?

答: Your route name does not match the parameter name. Make both of them "productNamed" or "productName".</p>

Body:
I have a simple WebApi solution hosted on IIS10.

I have a ProductController class that inherits ApiController. This class has a method GetProduct

 [HttpGet]
    [Route("api/product/{productName}")]
    public object GetProduct(string productName)
    {
        return "abc";
    }

When I try to hit the following api through postman

http://localhost:10000/api/product/com1?query=test

I get a 404 error, Tried to create a folder by the same name (com1) but got an error as well. Then found out that I cannot have the following values in my api
CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9.

I tried adding the following entries in IIS
under Request Filtering

Am I missing out on anything?


问:
Inserting empty values as string to sql table
I have a project which has a Class which has some members as string which equal "". My teacher had shown examples with Class members declared as String = "NULL". I try to insert to SQL and I get this message:

Error insertion... Error converting data type varchar to numeric.

I know many will suggest to use parameterized values for inserting but I like to finish the way I started this.

I have tried to cast query string Object values with CDec, CInt, Cbit and still no clue how to do it right because I got Exceptions for trying to cast an "".

Also, I have changed to default values of members like this;

Dim NumberOfPackage As String = ""
```

<p>instead of;</p>

<pre class="lang-vb prettyprint-override"><code>Dim NumberOfPackage As String = "NULL"
</code>```

Some Columns in SQL table had ALLOW NULL checkBox set to NOT allowed, I changed the design of the Table to make it easier for insertion.

答:
I think I understand what is happening. Your variable NumberOfPackage contains numbers but since you want to insert NULL sometime, you made it a string.

NumberOfPackage = "23"
NumberOfPackage = "NULL"

"INSERT INTO table (column) VALUES (" & NumberOfPackage & ");"
```

<p>But since you use a string, you might be trying to do</p>

<pre class="lang-vb prettyprint-override"><code>"INSERT INTO table (column) VALUES ('" & NumberOfPackage & "');"
</code>```

Which would cause the error on NULL since your column is a number and it is trying to do

"INSERT INTO table (column) VALUES ('NULL');"
```

Stick with my first example (without the ') if you really want to concatenate strings but everything would be much easier if you used parameters. By using parameters, it would be easier to keep NumberOfPackage as a decimal or a decimal? and do proper math with it.

Body:
I have a project which has a Class which has some members as string which equal "". My teacher had shown examples with Class members declared as String = "NULL". I try to insert to SQL and I get this message:

Error insertion... Error converting data type varchar to numeric.

I know many will suggest to use parameterized values for inserting but I like to finish the way I started this.

I have tried to cast query string Object values with CDec, CInt, Cbit and still no clue how to do it right because I got Exceptions for trying to cast an "".

Also, I have changed to default values of members like this;

Dim NumberOfPackage As String = ""

instead of;

Dim NumberOfPackage As String = "NULL"

Some Columns in SQL table had ALLOW NULL checkBox set to NOT allowed, I changed the design of the Table to make it easier for insertion.

Body:
I think I understand what is happening. Your variable NumberOfPackage contains numbers but since you want to insert NULL sometime, you made it a string.

NumberOfPackage = "23"
NumberOfPackage = "NULL"

"INSERT INTO table (column) VALUES (" & NumberOfPackage & ");"

But since you use a string, you might be trying to do

"INSERT INTO table (column) VALUES ('" & NumberOfPackage & "');"

Which would cause the error on NULL since your column is a number and it is trying to do

"INSERT INTO table (column) VALUES ('NULL');"

Stick with my first example (without the ') if you really want to concatenate strings but everything would be much easier if you used parameters. By using parameters, it would be easier to keep NumberOfPackage as a decimal or a decimal? and do proper math with it.


问:
How can I compile a Rust program with a custom llc?
I have a custom LLVM backend and would like to cross compile Rust for that custom (nostd) target. I'd like to compile Rust programs in two steps:

Using rustc to generate LLVM IR.

Use my own opt and llc to transform LLVM IR into machine code.

I tried using cargo rustc -- --emit=llvm-ir. I get .ll files, and then use llc to get .o files.
Then I cross compile libcore in the same way. When I try to link all the objects together, it tells me about an undefined reference. I was using the same commit of libcore and rustc. This seems a problem with LLVM versions but I'm not sure.

答:
There's a couple things you should be aware of. Most importantly, the version of LLVM that rustc uses by default if you get it from rustup or a distro package manager is /not/ an actual release of LLVM, and may not actually be bitcode-compatible with a particular llvm release. We solved this issue in my project by building rust from source with the --llvm-root flag to configure. You can then use rustup toolchain link to link your built rustc into a custom rustup toolchain.

Second, you can make rustc emit .rlib files that contain llvm bitcode instead of machine code if you use at least rustc 1.34 and pass the -C linker-plugin-lto flag to rustc. I also wrote the following script that can unpack an rlib file containing object code and pack it back up as an rlib file containing llvm bitcode, if the above approach does not work for you.

```<code>#!/bin/bash
dir="$(mktemp -d)"
trap "rm -rf $dir" INT TERM EXIT
archive=$(realpath -m $1)
cd "$dir"
ar x "$archive"
rm ./*.rcgu.o
for file in *.bc.z; do
len=`od -An -t u4 -j 15 -N4 $file`
blen=`od -An -t u8 -j $((len+19)) -N8 $file`
tail -c+$((len+28)) $file | head -c $blen > $file.bc.gz
printf "\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x00" |cat - $file.bc.gz |gzip -dc > ${file%.bc.z}.o
done
rm *.bc.z
rm *.gz
rm "$archive"
llvm-ar rs "${archive}" ./*
</code>```

Once you have the rlib files, you can use any llvm toolchain tool on them the same way you could with a .a file containing llvm bitcode.

In terms of performing the final link, there are a few things to bear in mind. First, rustc automatically generates the symbols __rust_alloc, __rust_alloc_zeroed, __rust_dealloc, and __rust_realloc and points them to either __rg_alloc (and similar __rg_ symbols respectively), which is the GlobalAlloc implementation that uses jemalloc by default, or __rdl_alloc (and similar __rdl_ symbols respectively), which is the system allocator powered by libc malloc. You will have to implement these symbols yourself if you are not using rustc to do the final link.

Second, libstd and libcore depend on some other libraries that you will also probably have to link against. Depending on what segment of the standard library you are using, you may find that different sets of libraries are required, so I can't help you without a specific error message there, but I can tell you that the list of libraries that my application ended up requiring was, in order: std, core, alloc, unwind, compiler_builtins, panic_abort, backtrace_sys, rustc_demangle. If you are using panic=unwind, you will obviously have to use that instead. If you find you still have missing symbols, I would suggest using nm to look for the library containing the missing symbol and figure out where it belongs in the linker order with trial and error.

Hope this helps, as I've spent a fair amount of effort engineering a solution to this exact problem (although not for the purposes of cross compilation).

Body:
There's a couple things you should be aware of. Most importantly, the version of LLVM that rustc uses by default if you get it from rustup or a distro package manager is /not/ an actual release of LLVM, and may not actually be bitcode-compatible with a particular llvm release. We solved this issue in my project by building rust from source with the --llvm-root flag to configure. You can then use rustup toolchain link to link your built rustc into a custom rustup toolchain.

Second, you can make rustc emit .rlib files that contain llvm bitcode instead of machine code if you use at least rustc 1.34 and pass the -C linker-plugin-lto flag to rustc. I also wrote the following script that can unpack an rlib file containing object code and pack it back up as an rlib file containing llvm bitcode, if the above approach does not work for you.

#!/bin/bash
dir="$(mktemp -d)"
trap "rm -rf $dir" INT TERM EXIT
archive=$(realpath -m $1)
cd "$dir"
ar x "$archive"
rm ./*.rcgu.o
for file in *.bc.z; do
len=`od -An -t u4 -j 15 -N4 $file`
blen=`od -An -t u8 -j $((len+19)) -N8 $file`
tail -c+$((len+28)) $file | head -c $blen > $file.bc.gz
printf "\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x00" |cat - $file.bc.gz |gzip -dc > ${file%.bc.z}.o
done
rm *.bc.z
rm *.gz
rm "$archive"
llvm-ar rs "${archive}" ./*

Once you have the rlib files, you can use any llvm toolchain tool on them the same way you could with a .a file containing llvm bitcode.

In terms of performing the final link, there are a few things to bear in mind. First, rustc automatically generates the symbols __rust_alloc, __rust_alloc_zeroed, __rust_dealloc, and __rust_realloc and points them to either __rg_alloc (and similar __rg_ symbols respectively), which is the GlobalAlloc implementation that uses jemalloc by default, or __rdl_alloc (and similar __rdl_ symbols respectively), which is the system allocator powered by libc malloc. You will have to implement these symbols yourself if you are not using rustc to do the final link.

Second, libstd and libcore depend on some other libraries that you will also probably have to link against. Depending on what segment of the standard library you are using, you may find that different sets of libraries are required, so I can't help you without a specific error message there, but I can tell you that the list of libraries that my application ended up requiring was, in order: std, core, alloc, unwind, compiler_builtins, panic_abort, backtrace_sys, rustc_demangle. If you are using panic=unwind, you will obviously have to use that instead. If you find you still have missing symbols, I would suggest using nm to look for the library containing the missing symbol and figure out where it belongs in the linker order with trial and error.

Hope this helps, as I've spent a fair amount of effort engineering a solution to this exact problem (although not for the purposes of cross compilation).


问:
Tomcat with https a non-root user - Bind exception 443
I want to run tomcat on port 443 with non-root user (https://machinIP). I'm getting below error:

```<code>Error initializing endpoint java.net.BindException: Permission denied:443
</code>```

I don't have port 443 in use for sure. I read somewhere that we cannot use port 443 a non-root user & alternative is to use iptables but I'm not aware on exactly how to use iptables..

I'll appreciate if someone can give me the exact command of iptables & whether I need to make any changes in server.xml a well? Current server.xml uses port 8080 for http & port 8443 for https.

Thanks!

答:
Its works for me :-)

```<code> wget http://download.si-linux.co.jp/debian-mirror/squeeze_20120726/pool/main/a/authbind/authbind_1.2.0.tar.gz
</code>```

unzip > CD  >  Make > make install

```<code>    sudo touch /etc/authbind/byport/443
    sudo chmod 500 /etc/authbind/byport/443
    sudo chown <non_root_user> /etc/authbind/byport/443

    vim tomcat/bin/startup.sh
    exec authbind --deep "$PRGDIR"/"$EXECUTABLE" start "$@"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to run tomcat on port 443 with non-root user (https://machinIP). I'm getting below error:

Error initializing endpoint java.net.BindException: Permission denied:443

I don't have port 443 in use for sure. I read somewhere that we cannot use port 443 a non-root user & alternative is to use iptables but I'm not aware on exactly how to use iptables..

I'll appreciate if someone can give me the exact command of iptables & whether I need to make any changes in server.xml a well? Current server.xml uses port 8080 for http & port 8443 for https.

Thanks!

Body:
Its works for me :-)

 wget http://download.si-linux.co.jp/debian-mirror/squeeze_20120726/pool/main/a/authbind/authbind_1.2.0.tar.gz

unzip > CD  >  Make > make install

    sudo touch /etc/authbind/byport/443
    sudo chmod 500 /etc/authbind/byport/443
    sudo chown <non_root_user> /etc/authbind/byport/443

    vim tomcat/bin/startup.sh
    exec authbind --deep "$PRGDIR"/"$EXECUTABLE" start "$@"


问:
Access pass-through query with parameters not updating with prompted parameters
An Access pass-through query works when using the default parameters.  When used in an Access report, the prompts that are used returns records based on the default parameters in the ptq and not the answered prompts.  Default data is being returned.

I have a SQL Server based stored procedure that works, uspWorkCentreReport, that uses @TheDate DATE, @WC VARCHAR(15), @Shift INT for parameters and returns, through a SELECT statement, these columns:

```<code>[JOB NUMBER], [REL #], [JOB NAME], QTY.
</code>```

Here's the ALTER line of the stored procedure code:

```<code>ALTER PROCEDURE [dbo].[uspWorkCentreReport]
     @TheDate DATE,
     @WC VARCHAR(15),
     @Shift INT
</code>```

The Access pass-through query, ptq_uspWorkCentreReport, passes these default parameters '2019-05-30','PCOT',1 and uses a DSN-less ODBC connection that works to return default data.  I forgot to try but I think it will return correct data with whatever default parameters I use to replace '2019-05-30','PCOT',1.  EDIT - I tried it this morning and indeed any appropriate replacement parameters return the appropriate associated records.  Here's the ptq's one line:

```<code>exec uspWorkCentreReport '2019-05-30','PCOT',1
</code>```

I provide the ptq with default parameters based on Albert D. Kallal's SO reply.

I use an Access select query, qry_ptq_uspWorkCentreReport, to receive [JOB NUMBER],[REL #],[JOB NAME],QTY and pass the parameters TheDate, set to Date With Time, WC, set to Short Text, and Shift, set to Integer.

qry_ptq_uspWorkCentreReport uses the pass-through query.  The parameters are set using Access' Parameters applet and not within the query fields.  Running this select query prompts for the 3 parameters but only returns data based on the default parameters set in the ptq's one line.  I did not think to look at the Access SQL statement but will do so when I get to work tomorrow morning.  EDIT - Here's the SQL statement for qry_ptq_uspWorkCentreReport:

```<code>PARAMETERS TheDate DateTime, WC Text ( 255 ), Shift Short;
SELECT ptq_uspWorkCentreReport.[JOB NUMBER], ptq_uspWorkCentreReport.[REL #], ptq_uspWorkCentreReport.[JOB NAME], ptq_uspWorkCentreReport.QTY
FROM ptq_uspWorkCentreReport;
</code>```

Of course the above three functions culminate in an Access report, rpt_qry_ptq_WorkCentreReport to make the records human readable.

I have used the same scenario for another report the takes From and To dates as parameters.  When that report runs, the prompts take the dates and return records based on those dates and not the dates in the ptq.  Here's that ptq:

```<code>exec uspMergeAandPJobs '2018-01-01','2019-01-01'
</code>```

Indeed, I tried using

```<code>exec uspMergeAandPJobs '',''
</code>```

And the report returns 0 records!

Not sure what I am missing and would appreciate any feedback.  TIA.

I tried the following with the help of a tutor:

```<code>Sub Report_Load()

    Dim strFromDate     As String
    Dim strToDate       As String
    Dim strWC           As String
    Dim intShift        As Integer
    Dim strSQL          As String

    strFromDate = InputBox("From Date and Time: ")
    strToDate = InputBox("Enter To Date and Time: ")
    strWC = InputBox("Enter Work Center: ")
    intShift = InputBox("Enter Shift: ")

    Dim qdf As DAO.QueryDef, rst As DAO.Recordset
    Set qdf = CurrentDb.CreateQueryDef("")
    qdf.SQL = "exec dbo.uspWorkCentreReport " & "'" & strFromDate & "', " & "'" & strToDate & "', " & "'" & strWC & "', " & intShift & ";"

    qdf.Connect = "ODBC;DRIVER=ODBC Driver 13 for SQL Server;SERVER=OURS\NTSQL;Trusted_Connection=Yes;DATABASE=TablesCoE;ApplicationIntent=READONLY;"

    qdf.ReturnsRecords = True
    Set rst = qdf.OpenRecordset

    rst.Close
    Set rst = Nothing
    Set qdf = Nothing

End Sub
</code>```

After the prompts VBA spits up a Run-Time error 3129 - Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.  Neither of us were able to determine what was causing the error.  In VBA the "qdf.SQL..." line is highlighted in yellow.

EDIT - Adding stored proc's SQL code:

```<code>ALTER PROCEDURE [dbo].[uspWorkCentreReport_TEST] @FromDate DATETIME,@ToDate DATETIME,@WC VARCHAR(15),@Shift INT

AS

BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

--  Build table variable SumTable structure
DECLARE @SumTable TABLE(matl_nbr VARCHAR(60),QTY DECIMAL(4,0),matl_dsc VARCHAR(50))

--  P jobs and their summed WorkCentre traversals using crosstab - each traversal is added up
INSERT INTO @SumTable(matl_nbr,matl_dsc,QTY)
SELECT     SRC1.matl_nbr,SRC1.matl_dsc,
    SUM(CASE WHEN SRC1.locn_to = @WC THEN 1 ELSE 0 END) AS QTY
FROM
(
SELECT matl_nbr,matl_dsc,locn_to
FROM mtrk_CompanyE.dbo.trxn_hstd th
WHERE (last_upd >= @FromDate AND last_upd <= @ToDate) AND
    locn_to = @WC
)SRC1
GROUP BY matl_nbr,matl_dsc

--  These updates take all the summed WorkCentre (locn_to) columns and turn each into "1" for later summing
UPDATE @SumTable
SET QTY = 1
WHERE QTY >1

--  Shortening the material number from 123456_00_00_R1_00 to 1234560
UPDATE @SumTable
SET matl_nbr = LEFT(matl_nbr,6) + right(LEFT(matl_nbr,9),1)

SELECT LEFT(A.matl_nbr,6)[JOB NUMBER],SUBSTRING(A.matl_nbr,7,1)[REL #],matl_dsc AS [JOB NAME],QTY
FROM (SELECT matl_nbr,matl_dsc,
        SUM(CASE WHEN QTY = 1 THEN 1 ELSE NULL END) AS QTY
FROM @SumTable
GROUP BY matl_nbr,matl_dsc)A
ORDER BY QTY DESC;

END
</code>```

EDIT - Finished sub:

```<code>Private Sub Report_Open(Cancel As Integer)

    Dim strFromDate     As String
    Dim strToDate       As String
    Dim strWC           As String
    Dim intShift        As Integer
    Dim strSQL          As String

    strFromDate = InputBox("Enter From Date and Time: ")
    strToDate = InputBox("Enter To Date and Time: ")
    strWC = InputBox("Enter Work Center: ")
    intShift = InputBox("Enter Shift: ")

    strSQL = "exec dbo.uspWorkCentreReport_TEST " & "'" & strFromDate & "', " & "'" & strToDate & "', " & "'" & strWC & "', " & intShift & ";"

    CurrentDb.QueryDefs("ptq_uspWorkCentreReport").SQL = strSQL

    DoCmd.OpenReport "rpt_qry_ptq_uspWorkCentreReport", acViewReport

    Me.lblFromDate.Caption = strFromDate
    Me.lblToDate.Caption = strToDate
    Me.lblWC.Caption = strWC
    Me.lblShift.Caption = intShift

End Sub
</code>```

答:
Your Access query has parameters:

```<code>PARAMETERS TheDate DateTime, WC Text ( 255 ), Shift Short;
</code>```

and since they are defined in the query definition, Access asks for them when opening/running the query.

But these parameters are never used!

There is no way for Access to pass these parameters into the pass-through query that is the basis of the Access query. Again, a PT query is nothing more than a Connect string and a constant SQL string.

So when you run the Access query, it will always run the saved contents of the PT query, i.e.

exec uspWorkCentreReport '2019-05-30','PCOT',1

The parameters you entered are ignored.

What you need to do (as outlined in the answer you refer to):

create a form to collect the parameter values

dynamically create the SQL string for the PT query with VBA

assign that SQL to the PT query:

CurrentDb.QueryDefs("ptq_uspWorkCentreReport").SQL = strSql

(it is automatically saved)

and then you can run the report based on the Access query - or better: directly use the PT query as record source for the report.

Remove the parameters from the Access query, they are of no use for your situation. Or remove the query entirely, unless you need it to join the PT query with something else.

Edit for above edit:

If you get a runtime error, there is probably a syntax error in your .Sql. Build the SQL string in a variable, do Debug.Print strSql, and run that string in SSMS. You may need to change date formatting (depending on your locale settings).

Also: See my 3rd bullet. Defining a temporary querydef and opening a recordset doesn't work for a report. You must assign the .Sql of the existing query that is the record source of the report.

Addendum: if you need to create a new query, first set .Connect, and then .Sql, so Access knows it's a Pass-Through query.

Access SQL doesn't know exec.

Edit 2

You have an existing, working PT query ptq_uspWorkCentreReport, which returns records for one set of parameters, e.g.

```<code>exec uspWorkCentreReport '2019-05-30','PCOT',1
</code>```

Use this query as record source for your report.

To run the report with different parameters, you must modify the query's SQL. You can do this manually in query design view, or with VBA.

I think Report_Load() is too late for modifying its record source (the PT query). Run the following sub, then open the Report.

Sub SetUspParameters()

    Dim strFromDate     As String
    Dim strToDate       As String
    Dim strWC           As String
    Dim intShift        As Integer
    Dim strSQL          As String

    strFromDate = InputBox("From Date and Time: ")
    strToDate = InputBox("Enter To Date and Time: ")
    strWC = InputBox("Enter Work Center: ")
    intShift = InputBox("Enter Shift: ")

    strSQL = "exec dbo.uspWorkCentreReport " & "'" & strFromDate & "', " & "'" & strToDate & "', " & "'" & strWC & "', " & intShift & ";"

    Debug.Print strSQL

    ' This line is all that's needed to modify the PT query
    CurrentDb.QueryDefs("ptq_uspWorkCentreReport").SQL = strSQL

End Sub
```

In practice, you don't want to use 4 x InputBox, but a form.

Body:
An Access pass-through query works when using the default parameters.  When used in an Access report, the prompts that are used returns records based on the default parameters in the ptq and not the answered prompts.  Default data is being returned.

I have a SQL Server based stored procedure that works, uspWorkCentreReport, that uses @TheDate DATE, @WC VARCHAR(15), @Shift INT for parameters and returns, through a SELECT statement, these columns:

[JOB NUMBER], [REL #], [JOB NAME], QTY.

Here's the ALTER line of the stored procedure code:

ALTER PROCEDURE [dbo].[uspWorkCentreReport]
     @TheDate DATE,
     @WC VARCHAR(15),
     @Shift INT

The Access pass-through query, ptq_uspWorkCentreReport, passes these default parameters '2019-05-30','PCOT',1 and uses a DSN-less ODBC connection that works to return default data.  I forgot to try but I think it will return correct data with whatever default parameters I use to replace '2019-05-30','PCOT',1.  EDIT - I tried it this morning and indeed any appropriate replacement parameters return the appropriate associated records.  Here's the ptq's one line:

exec uspWorkCentreReport '2019-05-30','PCOT',1

I provide the ptq with default parameters based on Albert D. Kallal's SO reply.

I use an Access select query, qry_ptq_uspWorkCentreReport, to receive [JOB NUMBER],[REL #],[JOB NAME],QTY and pass the parameters TheDate, set to Date With Time, WC, set to Short Text, and Shift, set to Integer.

qry_ptq_uspWorkCentreReport uses the pass-through query.  The parameters are set using Access' Parameters applet and not within the query fields.  Running this select query prompts for the 3 parameters but only returns data based on the default parameters set in the ptq's one line.  I did not think to look at the Access SQL statement but will do so when I get to work tomorrow morning.  EDIT - Here's the SQL statement for qry_ptq_uspWorkCentreReport:

PARAMETERS TheDate DateTime, WC Text ( 255 ), Shift Short;
SELECT ptq_uspWorkCentreReport.[JOB NUMBER], ptq_uspWorkCentreReport.[REL #], ptq_uspWorkCentreReport.[JOB NAME], ptq_uspWorkCentreReport.QTY
FROM ptq_uspWorkCentreReport;

Of course the above three functions culminate in an Access report, rpt_qry_ptq_WorkCentreReport to make the records human readable.

I have used the same scenario for another report the takes From and To dates as parameters.  When that report runs, the prompts take the dates and return records based on those dates and not the dates in the ptq.  Here's that ptq:

exec uspMergeAandPJobs '2018-01-01','2019-01-01'

Indeed, I tried using

exec uspMergeAandPJobs '',''

And the report returns 0 records!

Not sure what I am missing and would appreciate any feedback.  TIA.

I tried the following with the help of a tutor:

Sub Report_Load()

    Dim strFromDate     As String
    Dim strToDate       As String
    Dim strWC           As String
    Dim intShift        As Integer
    Dim strSQL          As String

    strFromDate = InputBox("From Date and Time: ")
    strToDate = InputBox("Enter To Date and Time: ")
    strWC = InputBox("Enter Work Center: ")
    intShift = InputBox("Enter Shift: ")

    Dim qdf As DAO.QueryDef, rst As DAO.Recordset
    Set qdf = CurrentDb.CreateQueryDef("")
    qdf.SQL = "exec dbo.uspWorkCentreReport " & "'" & strFromDate & "', " & "'" & strToDate & "', " & "'" & strWC & "', " & intShift & ";"

    qdf.Connect = "ODBC;DRIVER=ODBC Driver 13 for SQL Server;SERVER=OURS\NTSQL;Trusted_Connection=Yes;DATABASE=TablesCoE;ApplicationIntent=READONLY;"

    qdf.ReturnsRecords = True
    Set rst = qdf.OpenRecordset

    rst.Close
    Set rst = Nothing
    Set qdf = Nothing

End Sub

After the prompts VBA spits up a Run-Time error 3129 - Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.  Neither of us were able to determine what was causing the error.  In VBA the "qdf.SQL..." line is highlighted in yellow.

EDIT - Adding stored proc's SQL code:

ALTER PROCEDURE [dbo].[uspWorkCentreReport_TEST] @FromDate DATETIME,@ToDate DATETIME,@WC VARCHAR(15),@Shift INT

AS

BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

--  Build table variable SumTable structure
DECLARE @SumTable TABLE(matl_nbr VARCHAR(60),QTY DECIMAL(4,0),matl_dsc VARCHAR(50))

--  P jobs and their summed WorkCentre traversals using crosstab - each traversal is added up
INSERT INTO @SumTable(matl_nbr,matl_dsc,QTY)
SELECT     SRC1.matl_nbr,SRC1.matl_dsc,
    SUM(CASE WHEN SRC1.locn_to = @WC THEN 1 ELSE 0 END) AS QTY
FROM
(
SELECT matl_nbr,matl_dsc,locn_to
FROM mtrk_CompanyE.dbo.trxn_hstd th
WHERE (last_upd >= @FromDate AND last_upd <= @ToDate) AND
    locn_to = @WC
)SRC1
GROUP BY matl_nbr,matl_dsc

--  These updates take all the summed WorkCentre (locn_to) columns and turn each into "1" for later summing
UPDATE @SumTable
SET QTY = 1
WHERE QTY >1

--  Shortening the material number from 123456_00_00_R1_00 to 1234560
UPDATE @SumTable
SET matl_nbr = LEFT(matl_nbr,6) + right(LEFT(matl_nbr,9),1)

SELECT LEFT(A.matl_nbr,6)[JOB NUMBER],SUBSTRING(A.matl_nbr,7,1)[REL #],matl_dsc AS [JOB NAME],QTY
FROM (SELECT matl_nbr,matl_dsc,
        SUM(CASE WHEN QTY = 1 THEN 1 ELSE NULL END) AS QTY
FROM @SumTable
GROUP BY matl_nbr,matl_dsc)A
ORDER BY QTY DESC;

END

EDIT - Finished sub:

Private Sub Report_Open(Cancel As Integer)

    Dim strFromDate     As String
    Dim strToDate       As String
    Dim strWC           As String
    Dim intShift        As Integer
    Dim strSQL          As String

    strFromDate = InputBox("Enter From Date and Time: ")
    strToDate = InputBox("Enter To Date and Time: ")
    strWC = InputBox("Enter Work Center: ")
    intShift = InputBox("Enter Shift: ")

    strSQL = "exec dbo.uspWorkCentreReport_TEST " & "'" & strFromDate & "', " & "'" & strToDate & "', " & "'" & strWC & "', " & intShift & ";"

    CurrentDb.QueryDefs("ptq_uspWorkCentreReport").SQL = strSQL

    DoCmd.OpenReport "rpt_qry_ptq_uspWorkCentreReport", acViewReport

    Me.lblFromDate.Caption = strFromDate
    Me.lblToDate.Caption = strToDate
    Me.lblWC.Caption = strWC
    Me.lblShift.Caption = intShift

End Sub

Body:
Your Access query has parameters:

PARAMETERS TheDate DateTime, WC Text ( 255 ), Shift Short;

and since they are defined in the query definition, Access asks for them when opening/running the query.

But these parameters are never used!

There is no way for Access to pass these parameters into the pass-through query that is the basis of the Access query. Again, a PT query is nothing more than a Connect string and a constant SQL string.

So when you run the Access query, it will always run the saved contents of the PT query, i.e.

exec uspWorkCentreReport '2019-05-30','PCOT',1

The parameters you entered are ignored.

What you need to do (as outlined in the answer you refer to):

create a form to collect the parameter values

dynamically create the SQL string for the PT query with VBA

assign that SQL to the PT query:

CurrentDb.QueryDefs("ptq_uspWorkCentreReport").SQL = strSql

(it is automatically saved)

and then you can run the report based on the Access query - or better: directly use the PT query as record source for the report.

Remove the parameters from the Access query, they are of no use for your situation. Or remove the query entirely, unless you need it to join the PT query with something else.

Edit for above edit:

If you get a runtime error, there is probably a syntax error in your .Sql. Build the SQL string in a variable, do Debug.Print strSql, and run that string in SSMS. You may need to change date formatting (depending on your locale settings).

Also: See my 3rd bullet. Defining a temporary querydef and opening a recordset doesn't work for a report. You must assign the .Sql of the existing query that is the record source of the report.

Addendum: if you need to create a new query, first set .Connect, and then .Sql, so Access knows it's a Pass-Through query.

Access SQL doesn't know exec.

Edit 2

You have an existing, working PT query ptq_uspWorkCentreReport, which returns records for one set of parameters, e.g.

exec uspWorkCentreReport '2019-05-30','PCOT',1

Use this query as record source for your report.

To run the report with different parameters, you must modify the query's SQL. You can do this manually in query design view, or with VBA.

I think Report_Load() is too late for modifying its record source (the PT query). Run the following sub, then open the Report.

Sub SetUspParameters()

    Dim strFromDate     As String
    Dim strToDate       As String
    Dim strWC           As String
    Dim intShift        As Integer
    Dim strSQL          As String

    strFromDate = InputBox("From Date and Time: ")
    strToDate = InputBox("Enter To Date and Time: ")
    strWC = InputBox("Enter Work Center: ")
    intShift = InputBox("Enter Shift: ")

    strSQL = "exec dbo.uspWorkCentreReport " & "'" & strFromDate & "', " & "'" & strToDate & "', " & "'" & strWC & "', " & intShift & ";"

    Debug.Print strSQL

    ' This line is all that's needed to modify the PT query
    CurrentDb.QueryDefs("ptq_uspWorkCentreReport").SQL = strSQL

End Sub

In practice, you don't want to use 4 x InputBox, but a form.


问:
C pointer problem!
Why does the following C code does not ouput 10

```<code>#include<stdio.h>
#include<stdlib.h>
void get_length(char s[]);
int main( )
{
char buff[128];
printf("\nEnter buffer data: ");
scanf("%s",buff);
get_length(buff);
}

void get_length(char *s){
    int count;
for(count = 0 ; *s != '\0' ; s++)
    count++;
printf("count = %d\n",count);
}
</code>```

The input is I am Rohit

The output is

count = 432

Can anyone please explain that.

答: The scanf call is failing because you have used an invalid format. If you want a string of length 5, then the format should be "%5s" instead of "5s", or just "%s" if the five is a complete typo. So, the character buffer is uninitialized and you are getting the number of bytes before the first random '\n' character is encountered on the stack. Also, scanf ignores newline characters. So, your get_length function will never work as expected.

Title: C pointer problem!

Body:
Why does the following C code does not ouput 10

#include<stdio.h>
#include<stdlib.h>
void get_length(char s[]);
int main( )
{
char buff[128];
printf("\nEnter buffer data: ");
scanf("%s",buff);
get_length(buff);
}

void get_length(char *s){
    int count;
for(count = 0 ; *s != '\0' ; s++)
    count++;
printf("count = %d\n",count);
}

The input is I am Rohit

The output is

count = 432

Can anyone please explain that.


问:
Why does Python add newline characters to some list elements?
I'm reading files from a text file called WeaponShack.list

These are the contents of 'weapon shack.list':

```<code>Grenade
Ak-47
Shotgun
Makarov
Minigun
Bat
Katana
Chainsaw
Flamethrower
</code>```

There are no whitespaces. These items are copy-pasted as is.

I try to strip down some newline characters but the "\n" character just keeps showing up at some elements when I print the list. I don't understand why.

I tried using .strip('\n') but the "\n" characters still pop up at the end of
some elements.

```<code>print("Taking weapons from Weapon shack")
weapons = []
with open("WeaponShack.list",'r') as ws:
    weapons = ws.readlines()
    for weapon in weapons:
        weapons.remove(weapon)
        weapon = weapon.strip('\n')
        weapons.append(weapon)
ws.close()
print(weapons)
</code>```

The expected output is:

Taking weapons from Weapon shack
  ['Ak-47', 'Makarov', 'Bat', 'Chainsaw', 'Grenade', 'Minigun', 'Flamethrower', 'Katana', 'Shotgun']

But the actual output is:

Taking weapons from Weapon shack
  ['Ak-47\n', 'Makarov\n', 'Bat\n', 'Chainsaw\n', 'Grenade', 'Minigun', 'Flamethrower', 'Katana', 'Shotgun']

Does anyone know why this is happening?

EDIT
My focus is why the "\n" character appears. Not how to traverse lists.
Also trying the suggestion: adding a new list:

```<code>print("Taking weapons from Weapon shack")
weapons = []
newWeaponList = []
with open("WeaponShack.list",'r') as ws:
    weapons = ws.readlines()
    for weapon in weapons:
        weapons.remove(weapon)
        weapon = weapon.strip('\n')
        newWeaponList.append(weapon)
ws.close()
print(newWeaponList)
</code>```

produces this output:

Taking weapons from Weapon shack
  ['Grenade', 'Shotgun', 'Minigun', 'Katana', 'Flamethrower']

Weird because it doesn't show all the elements.

答:
It is because you are both reading and modifying the list preventing traversal of each element. The weapons with '\n' at the end are never reached by weapon.strip('\n')

To make it cleaner remove the traversal problem and get rid of the new spaces, try something like this answer:

print("Taking weapons from Weapon shack")
with open("weapons.list") as ws:
    readWeapons = ws.readlines()
    for weapon in readWeapons:
        weapon = weapon.rstrip('\n')
        weapons.append(weapon)
print(weapons)
```

<p>Edit:</p>

<p>To answer your clarification, it's because of how the for loop in python works. I am not privy to the exact details, but it appears that the for loop actually accesses the array in real time rather than read the entire array at once. Check out this reading from test.list which contains four lines corresponding to A-D:</p>

<pre class="lang-py prettyprint-override"><code>print("Taking item from test\n")
with open("test.list",'r') as ws:
    elements = ws.readlines()
    print(elements)
    print()
    for element in elements:
        print('Current element: ' + element)
        elements.remove(element)
        print('Element pre-strip: ' + str(elements))
        element = element.strip('\n')
        print('Stripped element: ' + element)
        elements.append(element)
        print('Element list post-strip: ' + str(elements))
</code>```

Output:

```<code>Taking item from test

['A\n', 'B\n', 'C\n', 'D\n']

Current element: A

Element pre-strip: ['B\n', 'C\n', 'D\n']
Stripped element: A
Element list post-strip: ['B\n', 'C\n', 'D\n', 'A']
Current element: C

Element pre-strip: ['B\n', 'D\n', 'A']
Stripped element: C
Element list post-strip: ['B\n', 'D\n', 'A', 'C']
Current element: A
Element pre-strip: ['B\n', 'D\n', 'C']
Stripped element: A
Element list post-strip: ['B\n', 'D\n', 'C', 'A']
Current element: A
Element pre-strip: ['B\n', 'D\n', 'C']
Stripped element: A
Element list post-strip: ['B\n', 'D\n', 'C', 'A']
</code>```

Because of of the appending rather than prepending, every other element is being skipped as the for loop moves from index a of the array to index a + 1 of the array. This causes, B and D (indices 1 and 3) to be skipped and A to be read 3 times.

Body:
I'm reading files from a text file called WeaponShack.list

These are the contents of 'weapon shack.list':

Grenade
Ak-47
Shotgun
Makarov
Minigun
Bat
Katana
Chainsaw
Flamethrower

There are no whitespaces. These items are copy-pasted as is.

I try to strip down some newline characters but the "\n" character just keeps showing up at some elements when I print the list. I don't understand why.

I tried using .strip('\n') but the "\n" characters still pop up at the end of
some elements.

print("Taking weapons from Weapon shack")
weapons = []
with open("WeaponShack.list",'r') as ws:
    weapons = ws.readlines()
    for weapon in weapons:
        weapons.remove(weapon)
        weapon = weapon.strip('\n')
        weapons.append(weapon)
ws.close()
print(weapons)

The expected output is:

Taking weapons from Weapon shack
  ['Ak-47', 'Makarov', 'Bat', 'Chainsaw', 'Grenade', 'Minigun', 'Flamethrower', 'Katana', 'Shotgun']

But the actual output is:

Taking weapons from Weapon shack
  ['Ak-47\n', 'Makarov\n', 'Bat\n', 'Chainsaw\n', 'Grenade', 'Minigun', 'Flamethrower', 'Katana', 'Shotgun']

Does anyone know why this is happening?

EDIT
My focus is why the "\n" character appears. Not how to traverse lists.
Also trying the suggestion: adding a new list:

print("Taking weapons from Weapon shack")
weapons = []
newWeaponList = []
with open("WeaponShack.list",'r') as ws:
    weapons = ws.readlines()
    for weapon in weapons:
        weapons.remove(weapon)
        weapon = weapon.strip('\n')
        newWeaponList.append(weapon)
ws.close()
print(newWeaponList)

produces this output:

Taking weapons from Weapon shack
  ['Grenade', 'Shotgun', 'Minigun', 'Katana', 'Flamethrower']

Weird because it doesn't show all the elements.

Body:
It is because you are both reading and modifying the list preventing traversal of each element. The weapons with '\n' at the end are never reached by weapon.strip('\n')

To make it cleaner remove the traversal problem and get rid of the new spaces, try something like this answer:

print("Taking weapons from Weapon shack")
with open("weapons.list") as ws:
    readWeapons = ws.readlines()
    for weapon in readWeapons:
        weapon = weapon.rstrip('\n')
        weapons.append(weapon)
print(weapons)

Edit:

To answer your clarification, it's because of how the for loop in python works. I am not privy to the exact details, but it appears that the for loop actually accesses the array in real time rather than read the entire array at once. Check out this reading from test.list which contains four lines corresponding to A-D:

print("Taking item from test\n")
with open("test.list",'r') as ws:
    elements = ws.readlines()
    print(elements)
    print()
    for element in elements:
        print('Current element: ' + element)
        elements.remove(element)
        print('Element pre-strip: ' + str(elements))
        element = element.strip('\n')
        print('Stripped element: ' + element)
        elements.append(element)
        print('Element list post-strip: ' + str(elements))

Output:

Taking item from test

['A\n', 'B\n', 'C\n', 'D\n']

Current element: A

Element pre-strip: ['B\n', 'C\n', 'D\n']
Stripped element: A
Element list post-strip: ['B\n', 'C\n', 'D\n', 'A']
Current element: C

Element pre-strip: ['B\n', 'D\n', 'A']
Stripped element: C
Element list post-strip: ['B\n', 'D\n', 'A', 'C']
Current element: A
Element pre-strip: ['B\n', 'D\n', 'C']
Stripped element: A
Element list post-strip: ['B\n', 'D\n', 'C', 'A']
Current element: A
Element pre-strip: ['B\n', 'D\n', 'C']
Stripped element: A
Element list post-strip: ['B\n', 'D\n', 'C', 'A']

Because of of the appending rather than prepending, every other element is being skipped as the for loop moves from index a of the array to index a + 1 of the array. This causes, B and D (indices 1 and 3) to be skipped and A to be read 3 times.


问:
Sails.js find doesn't work with or and select together
I've made a simple code that was supposed to find several users that worked:

```<code>  Users.find({
      where: {country: req.param('country'), join: true},
      select: ['uid']

    })
</code>```

when I changed the where to or as in the example below I started getting an error.

```<code>  Users.find({
      or: [{country: req.param('country'), join: true},{isAdmin: true}],
      select: ['uid']

    }).then()...
</code>```

Using select works with where but not with or. I get this error:

```<code>Unhandled rejection TypeError: Cannot read property 'req' of undefined
</code>```

答:
As Michael said I chained the where so now it works:

```<code>Users.find({
      select: ['uid','username','fbProfile','profilePic','phone']
    }).where({
      or: [{country: req.param('country'), join: true},{isAdmin: true}]
    })
</code>```

Body:
I've made a simple code that was supposed to find several users that worked:

  Users.find({
      where: {country: req.param('country'), join: true},
      select: ['uid']

    })

when I changed the where to or as in the example below I started getting an error.

  Users.find({
      or: [{country: req.param('country'), join: true},{isAdmin: true}],
      select: ['uid']

    }).then()...

Using select works with where but not with or. I get this error:

Unhandled rejection TypeError: Cannot read property 'req' of undefined

Body:
As Michael said I chained the where so now it works:

Users.find({
      select: ['uid','username','fbProfile','profilePic','phone']
    }).where({
      or: [{country: req.param('country'), join: true},{isAdmin: true}]
    })


问:
How to correctly configure git submodule
I am trying to add a repository as a submodule in another git module.
After adding the submodule I tried to clone the parent project:

```<code>git clone https://...
cd <parent_path>/<submodule_path>
git submodule init
git submodule update
</code>```

Now if I git status in the submodule the HEAD is detached:

```<code>cd <submodule_path>
git status
HEAD detached at a4709b3
nothing to commit, working tree clean
</code>```

After reading this answer I tried to checkout to submodule's master:

```<code>git checkout master
git status

On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean
</code>```

But now, if I git status on parent directory it shows that there are new commits in the submodule (which is definitely not the case)

```<code>cd <parent_dir_path>
git status

On branch test_submodule
Your branch is up to date with 'origin/test_submodule'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   submodule_name (new commits)

no changes added to commit (use "git add" and/or "git commit -a")
</code>```

Can someone shed some light on this?

EDIT:
Here's the output of cd <submodule_path> && git show master:

```<code>commit 42309e0e2f48aba11902633173053e2423d4ba62 (HEAD -> master, origin/master, origin/HEAD)
Merge: a4709b3 1c1ae85
Author: Abc
Date:   Fri May 31 16:27:52 2019 +0100

    Merge pull request #6 in test/testing_submodule from test_integration_with_repos to master

    * commit '1c1ae8515716d9c2d5135e86dc9c024c81e4320b':
      test
</code>```

答:
Your superproject remembers that the submodule must be at the commit a4709b3. But the submodule was updated and now its master points to 42309e0. What you should do now depends on what code (what commit) you want to use with the superproject. The simplest solution is to check out the stored commit:

```<code>cd <submodule_path>
git checkout a4709b3
</code>```

The submodule will be in detached HEAD state. Nothing to worry about.

The other possibility is to update the submodule:

```<code>cd <submodule_path>
git checkout master # reconcile detached HEAD
git pull origin master
</code>```

and then update the superproject:

```<code>cd <parent_dir_path>
git add <submodule_path>
git commit -m "Update submodule"
</code>```

Body:
I am trying to add a repository as a submodule in another git module.
After adding the submodule I tried to clone the parent project:

git clone https://...
cd <parent_path>/<submodule_path>
git submodule init
git submodule update

Now if I git status in the submodule the HEAD is detached:

cd <submodule_path>
git status
HEAD detached at a4709b3
nothing to commit, working tree clean

After reading this answer I tried to checkout to submodule's master:

git checkout master
git status

On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean

But now, if I git status on parent directory it shows that there are new commits in the submodule (which is definitely not the case)

cd <parent_dir_path>
git status

On branch test_submodule
Your branch is up to date with 'origin/test_submodule'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   submodule_name (new commits)

no changes added to commit (use "git add" and/or "git commit -a")

Can someone shed some light on this?

EDIT:
Here's the output of cd <submodule_path> && git show master:

commit 42309e0e2f48aba11902633173053e2423d4ba62 (HEAD -> master, origin/master, origin/HEAD)
Merge: a4709b3 1c1ae85
Author: Abc
Date:   Fri May 31 16:27:52 2019 +0100

    Merge pull request #6 in test/testing_submodule from test_integration_with_repos to master

    * commit '1c1ae8515716d9c2d5135e86dc9c024c81e4320b':
      test

Body:
Your superproject remembers that the submodule must be at the commit a4709b3. But the submodule was updated and now its master points to 42309e0. What you should do now depends on what code (what commit) you want to use with the superproject. The simplest solution is to check out the stored commit:

cd <submodule_path>
git checkout a4709b3

The submodule will be in detached HEAD state. Nothing to worry about.

The other possibility is to update the submodule:

cd <submodule_path>
git checkout master # reconcile detached HEAD
git pull origin master

and then update the superproject:

cd <parent_dir_path>
git add <submodule_path>
git commit -m "Update submodule"


问:
Dropdown list elements contains substring/pattern : Disable element
I got a dropdown list and options, as described below.

If I try to click/select on "POICaption-XX423366 [DONOT ALLOW SELECT FOR THIS]" I am able to restrict this value for selection.

```<code>    <select multiple="multiple" size=20 id="caption_collection">

    <optgroup label="MAKE A CHOICE">
    <option>SHOW ALL ENABLED CAPTIONS</option>
    <option>SHOW ALL DISABLED CAPTIONS</option>
    <option>SHOW ALL LISTED CAPTIONS</option>
    </optgroup>
    <optgroup label="ELSE SELECT ONE OR MULTIPLE">
             <option>ALWCaption-A100104  [ALLOW SELECT HERE]</option>
           <option>ZSDCaption-Z100104  [ALLOW SELECT HERE]</option>
           <option>XCDCaption-S100104  [ALLOW SELECT HERE]</option>
           <option>DCVCaption-Q100104  [ALLOW SELECT HERE]</option>
           <option>ERTCaption-D100104  [ALLOW SELECT HERE]</option>
           <option>BNMCaption-XX223366 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>XWECaption-XX243356 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>QWECaption-XX323356 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>DFGCaption-XX228866 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>TYUCaption-XX220066 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>POICaption-XX423366 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>GHJCaption-D100104  [ALLOW SELECT HERE]</option>
           <option>LKICaption-D100104  [ALLOW SELECT HERE]</option>
           <option>UYTCaption-XX423366 [DO NOT ALLOW SELECT FOR THIS]</option>
           </optgroup>

    </select>
    <br><br>
    <div>
      <textarea id="selected" rows="4" cols="56" readonly></textarea>
    </div>
</code>```

```<code>const needle = '[DO NOT ALLOW SELECT FOR THIS]';
// using jQuery:
$('select option').prop('disabled', function() {
return this.text.includes(needle);
});

$("#caption_collection").change(function() {
$('#selected').html(' ');
$("#caption_collection option:selected").each(function() {
var $this = $(this);
if ($this.length) {
  var selText = $this.text();
   console.log(selText);
  $('#selected').append(selText + ', ');
  //$('#selected').text('Only Captions allowed are:').append(selText + ', ');
}
});

});
</code>```

UPDATE:
Updated with working code, but need more guidance.

PROBLEM:
Got 3 options under optgroup ""MAKE A CHOICE" as below

```<code>SHOW ALL ENABLED CAPTIONS
SHOW ALL DISABLED CAPTIONS
SHOW ALL LISTED CAPTIONS
</code>```

What i want is clicking on each get me the value as shown below

```<code>SHOW ALL ENABLED CAPTIONS
     A100104  ,Z100104  ,S100104  ,Q100104  ,D100104  ,D100104  ,D100104

SHOW ALL DISABLED CAPTIONS
     XX223366  ,XX243356  ,XX323356  ,XX228866  ,XX220066  ,XX423366  ,XX423366

SHOW ALL LISTED CAPTIONS
    XX223366  ,XX243356  ,XX323356  ,XX228866  ,XX220066  ,XX423366  ,XX423366, A100104  ,Z100104  ,S100104  ,Q100104  ,D100104  ,D100104  ,D100104
</code>```

AND under optgroup label="ELSE SELECT ONE OR MULTIPLE"
need to display one or more value as :

```<code>A100104  ,Z100104  ,S100104
A100104
</code>```

Though I can extract

```<code>var stre = "LKICaption-A100104 [LKI   hfjdlfdlfjl]"
var str2 = stre.split('-');
var strval = str2[str2.length - 1];
alert(strval) // A100104 [LKI   hfjdlfdlfjl] but I need only A100104

alert(strval.split(' ')[0]) // Worked this way o/p is A100104
</code>```

答:
With jQuery, one option is as follows:

```<code>// caching the value to use to identify <options> to disable:
const needle = '[DO NOT ALLOW SELECT FOR THIS]';

// here we retrieve all the (relevant) <option> elements, and
// use the prop() method to update the 'disabled' property for
// each <option>:
$('#jQuery option').prop('disabled', function() {
  // here we use this.text to retrieve the text of the
  // current <option> (the 'this'), and use the
  // String.prototype.includes() method to find out if
  // the String includes the string we're searching for.
  // we return true (if it does) or false (if it does not),
  // this sets the 'disabled' property to the result of
  // the evaluation:
  return this.text.includes(needle);
});
</code>```

This is also possible using the plain DOM API:

```<code>// caching the value to use to identify <options> to disable:
const needle = '[DO NOT ALLOW SELECT FOR THIS]';

// here we retrieve all the relevant <option> elements,
// and pass that NodeList to NodeList.prototype.forEach():
document.querySelectorAll('#JavaScript option').forEach(

  // using an Arrow function to perform an action on
  // each of the <option> elements (here 'el' is the
  // current node of the NodeList); updating the
  // el.disabled property of each <option> based on
  // whether the el.text property includes the 'needle':
  (el) => el.disabled = el.text.includes(needle)
);
</code>```

const needle = '[DO NOT ALLOW SELECT FOR THIS]';
// using jQuery:
$('#jQuery option').prop('disabled', function() {
  return this.text.includes(needle);
});

// using plain JavaScript/DOM API:
document.querySelectorAll('#JavaScript option').forEach(
  (el) => el.disabled = el.text.includes(needle)
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  border: 2px solid #000;
  margin: 1em auto;
  padding: 0.5em;
  border-radius: 1em;
}

div::before {
  content: 'Using ' attr(id) ': ';
  display: block;
}</code>```

  <select>
    <option>ALWCaption-A100104 [ALLOW SELECT HERE]</option>
    <option>ZSDCaption-Z100104 [ALLOW SELECT HERE]</option>
    <option>XCDCaption-S100104 [ALLOW SELECT HERE]</option>
    <option>DCVCaption-Q100104 [ALLOW SELECT HERE]</option>
    <option>ERTCaption-D100104 [ALLOW SELECT HERE]</option>
    <option>BNMCaption-XX223366 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>XWECaption-XX243356 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>QWECaption-XX323356 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>DFGCaption-XX228866 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>TYUCaption-XX220066 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>POICaption-XX423366 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>GHJCaption-D100104 [ALLOW SELECT HERE]</option>
    <option>LKICaption-D100104 [ALLOW SELECT HERE]</option>
    <option>UYTCaption-XX423366 [DO NOT ALLOW SELECT FOR THIS]</option>
  </select>

  <select>
    <option>ALWCaption-A100104 [ALLOW SELECT HERE]</option>
    <option>ZSDCaption-Z100104 [ALLOW SELECT HERE]</option>
    <option>XCDCaption-S100104 [ALLOW SELECT HERE]</option>
    <option>DCVCaption-Q100104 [ALLOW SELECT HERE]</option>
    <option>ERTCaption-D100104 [ALLOW SELECT HERE]</option>
    <option>BNMCaption-XX223366 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>XWECaption-XX243356 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>QWECaption-XX323356 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>DFGCaption-XX228866 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>TYUCaption-XX220066 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>POICaption-XX423366 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>GHJCaption-D100104 [ALLOW SELECT HERE]</option>
    <option>LKICaption-D100104 [ALLOW SELECT HERE]</option>
    <option>UYTCaption-XX423366 [DO NOT ALLOW SELECT FOR THIS]</option>
  </select>

```

References:

jQuery:

prop().

JavaScript:

Arrow function syntax.

document.querySelectorAll().

HTMLOptionElement.

String.prototype.includes().

Body:
I got a dropdown list and options, as described below.

If I try to click/select on "POICaption-XX423366 [DONOT ALLOW SELECT FOR THIS]" I am able to restrict this value for selection.

    <select multiple="multiple" size=20 id="caption_collection">

    <optgroup label="MAKE A CHOICE">
    <option>SHOW ALL ENABLED CAPTIONS</option>
    <option>SHOW ALL DISABLED CAPTIONS</option>
    <option>SHOW ALL LISTED CAPTIONS</option>
    </optgroup>
    <optgroup label="ELSE SELECT ONE OR MULTIPLE">
             <option>ALWCaption-A100104  [ALLOW SELECT HERE]</option>
           <option>ZSDCaption-Z100104  [ALLOW SELECT HERE]</option>
           <option>XCDCaption-S100104  [ALLOW SELECT HERE]</option>
           <option>DCVCaption-Q100104  [ALLOW SELECT HERE]</option>
           <option>ERTCaption-D100104  [ALLOW SELECT HERE]</option>
           <option>BNMCaption-XX223366 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>XWECaption-XX243356 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>QWECaption-XX323356 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>DFGCaption-XX228866 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>TYUCaption-XX220066 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>POICaption-XX423366 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>GHJCaption-D100104  [ALLOW SELECT HERE]</option>
           <option>LKICaption-D100104  [ALLOW SELECT HERE]</option>
           <option>UYTCaption-XX423366 [DO NOT ALLOW SELECT FOR THIS]</option>
           </optgroup>

    </select>

      <textarea id="selected" rows="4" cols="56" readonly></textarea>

const needle = '[DO NOT ALLOW SELECT FOR THIS]';
// using jQuery:
$('select option').prop('disabled', function() {
return this.text.includes(needle);
});

$("#caption_collection").change(function() {
$('#selected').html(' ');
$("#caption_collection option:selected").each(function() {
var $this = $(this);
if ($this.length) {
  var selText = $this.text();
   console.log(selText);
  $('#selected').append(selText + ', ');
  //$('#selected').text('Only Captions allowed are:').append(selText + ', ');
}
});

});

UPDATE:
Updated with working code, but need more guidance.

PROBLEM:
Got 3 options under optgroup ""MAKE A CHOICE" as below

SHOW ALL ENABLED CAPTIONS
SHOW ALL DISABLED CAPTIONS
SHOW ALL LISTED CAPTIONS

What i want is clicking on each get me the value as shown below

SHOW ALL ENABLED CAPTIONS
     A100104  ,Z100104  ,S100104  ,Q100104  ,D100104  ,D100104  ,D100104

SHOW ALL DISABLED CAPTIONS
     XX223366  ,XX243356  ,XX323356  ,XX228866  ,XX220066  ,XX423366  ,XX423366

SHOW ALL LISTED CAPTIONS
    XX223366  ,XX243356  ,XX323356  ,XX228866  ,XX220066  ,XX423366  ,XX423366, A100104  ,Z100104  ,S100104  ,Q100104  ,D100104  ,D100104  ,D100104

AND under optgroup label="ELSE SELECT ONE OR MULTIPLE"
need to display one or more value as :

A100104  ,Z100104  ,S100104
A100104

Though I can extract

var stre = "LKICaption-A100104 [LKI   hfjdlfdlfjl]"
var str2 = stre.split('-');
var strval = str2[str2.length - 1];
alert(strval) // A100104 [LKI   hfjdlfdlfjl] but I need only A100104

alert(strval.split(' ')[0]) // Worked this way o/p is A100104

Body:
With jQuery, one option is as follows:

// caching the value to use to identify <options> to disable:
const needle = '[DO NOT ALLOW SELECT FOR THIS]';

// here we retrieve all the (relevant) <option> elements, and
// use the prop() method to update the 'disabled' property for
// each <option>:
$('#jQuery option').prop('disabled', function() {
  // here we use this.text to retrieve the text of the
  // current <option> (the 'this'), and use the
  // String.prototype.includes() method to find out if
  // the String includes the string we're searching for.
  // we return true (if it does) or false (if it does not),
  // this sets the 'disabled' property to the result of
  // the evaluation:
  return this.text.includes(needle);
});

This is also possible using the plain DOM API:

// caching the value to use to identify <options> to disable:
const needle = '[DO NOT ALLOW SELECT FOR THIS]';

// here we retrieve all the relevant <option> elements,
// and pass that NodeList to NodeList.prototype.forEach():
document.querySelectorAll('#JavaScript option').forEach(

  // using an Arrow function to perform an action on
  // each of the <option> elements (here 'el' is the
  // current node of the NodeList); updating the
  // el.disabled property of each <option> based on
  // whether the el.text property includes the 'needle':
  (el) => el.disabled = el.text.includes(needle)
);

const needle = '[DO NOT ALLOW SELECT FOR THIS]';
// using jQuery:
$('#jQuery option').prop('disabled', function() {
  return this.text.includes(needle);
});

// using plain JavaScript/DOM API:
document.querySelectorAll('#JavaScript option').forEach(
  (el) => el.disabled = el.text.includes(needle)
);

div {
  border: 2px solid #000;
  margin: 1em auto;
  padding: 0.5em;
  border-radius: 1em;
}

div::before {
  content: 'Using ' attr(id) ': ';
  display: block;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="jQuery">
  <select>
    <option>ALWCaption-A100104 [ALLOW SELECT HERE]</option>
    <option>ZSDCaption-Z100104 [ALLOW SELECT HERE]</option>
    <option>XCDCaption-S100104 [ALLOW SELECT HERE]</option>
    <option>DCVCaption-Q100104 [ALLOW SELECT HERE]</option>
    <option>ERTCaption-D100104 [ALLOW SELECT HERE]</option>
    <option>BNMCaption-XX223366 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>XWECaption-XX243356 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>QWECaption-XX323356 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>DFGCaption-XX228866 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>TYUCaption-XX220066 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>POICaption-XX423366 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>GHJCaption-D100104 [ALLOW SELECT HERE]</option>
    <option>LKICaption-D100104 [ALLOW SELECT HERE]</option>
    <option>UYTCaption-XX423366 [DO NOT ALLOW SELECT FOR THIS]</option>
  </select>
</div>
<div id="JavaScript">
  <select>
    <option>ALWCaption-A100104 [ALLOW SELECT HERE]</option>
    <option>ZSDCaption-Z100104 [ALLOW SELECT HERE]</option>
    <option>XCDCaption-S100104 [ALLOW SELECT HERE]</option>
    <option>DCVCaption-Q100104 [ALLOW SELECT HERE]</option>
    <option>ERTCaption-D100104 [ALLOW SELECT HERE]</option>
    <option>BNMCaption-XX223366 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>XWECaption-XX243356 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>QWECaption-XX323356 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>DFGCaption-XX228866 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>TYUCaption-XX220066 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>POICaption-XX423366 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>GHJCaption-D100104 [ALLOW SELECT HERE]</option>
    <option>LKICaption-D100104 [ALLOW SELECT HERE]</option>
    <option>UYTCaption-XX423366 [DO NOT ALLOW SELECT FOR THIS]</option>
  </select>
</div>

References:

jQuery:

prop().

JavaScript:

Arrow function syntax.

document.querySelectorAll().

HTMLOptionElement.

String.prototype.includes().


问:
How do I reverse UISlider's min-max values?
Is there a good way to reverse UISlider values? The default is min on the left and max on the right. I'd like it to work the opposite way.

Rotating it 180 degrees seems a bit silly. Any ideas?

Thanks!

答:
The accepted answer is incorrect because it assumes that the slider's Min value is 0.

In my case, my Min is 1.1 and Max is 8.0

You need to subtract the slider's value from Min+Max value to inverse the value.


问:
How to output a pattern without including the beginning of the pattern?
I am trying to extract two characters from CLOB in Orcale. For example, the CLOB column looks like this:

"rateArea":"KCMO","state":"MO","addressComponent":null,"msag":null

I wrote:

```<code> SELECT
 REGEXP_SUBSTR( ORD_DETAILS,  'state":"+\w\w' ) state
 from order_log
</code>```

This gives me the output - state":"MO

I just want MO as my output.

Can you please suggest the regex code for the desired output?

答:
Use a capture group. REGEXP_SUBSTR() takes an optional parameter to specify which group to extract instead ot the whole match.

```<code>SELECT REGEXP_SUBSTR( ORD_DETAILS,  'state":"+(\w\w)', 1, 1, NULL, 1) state
FROM order_log
</code>```

Body:
I am trying to extract two characters from CLOB in Orcale. For example, the CLOB column looks like this:

"rateArea":"KCMO","state":"MO","addressComponent":null,"msag":null

I wrote:

 SELECT
 REGEXP_SUBSTR( ORD_DETAILS,  'state":"+\w\w' ) state
 from order_log

This gives me the output - state":"MO

I just want MO as my output.

Can you please suggest the regex code for the desired output?

Body:
Use a capture group. REGEXP_SUBSTR() takes an optional parameter to specify which group to extract instead ot the whole match.

SELECT REGEXP_SUBSTR( ORD_DETAILS,  'state":"+(\w\w)', 1, 1, NULL, 1) state
FROM order_log


问:
state_enabled="false" doesn't work, but the anothers work
Hello I have the following code:

```<code><selector
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_enabled="false"
        android:color="#FF0000"
        android:drawable="@drawable/white_button_disable"/>

    <item android:state_pressed="true"
        android:drawable="@drawable/white_button"/>

    <item
        android:drawable="@drawable/white_button_shadow"
        android:bottom="4px" />

</selector>
</code>```

white_button_disable

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="@color/red"/>
    <corners android:radius="28dp"/>
    <stroke
        android:width="1px"
        android:color="@color/red" />
</shape>
</code>```

If the button is clicked it shows the white_button, if the buttons don't press it shows white_buttons_shadow.

But if the button is disabled (enabled = "false") it doesn't work, and shows white_button_shadow

Any idea?

答:
Just tested it

```<code> <item android:state_enabled="false"
     android:drawable="@drawable/white_button_disable"/>
</code>```

Your android:color="#FF0000" is breaking the selector.

Remove it and you should be fine.

Body:
Hello I have the following code:

<selector
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_enabled="false"
        android:color="#FF0000"
        android:drawable="@drawable/white_button_disable"/>

    <item android:state_pressed="true"
        android:drawable="@drawable/white_button"/>

    <item
        android:drawable="@drawable/white_button_shadow"
        android:bottom="4px" />

</selector>

white_button_disable

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="@color/red"/>
    <corners android:radius="28dp"/>
    <stroke
        android:width="1px"
        android:color="@color/red" />
</shape>

If the button is clicked it shows the white_button, if the buttons don't press it shows white_buttons_shadow.

But if the button is disabled (enabled = "false") it doesn't work, and shows white_button_shadow

Any idea?

Body:
Just tested it

 <item android:state_enabled="false"
     android:drawable="@drawable/white_button_disable"/>

Your android:color="#FF0000" is breaking the selector.

Remove it and you should be fine.


问:
Using a HAVING clause in an UPDATE statement
This query

```<code>SELECT
FirstName, LastName, NCAAStats.AccountId, College_Translator.school_name, StatTypeId, COUNT(*) AS 'Count'
FROM NCAAstats
INNER JOIN College_Translator
ON College_Translator.AccountID = NCAAstats.AccountId
GROUP BY FirstName, LastName, NCAAStats.AccountId, College_Translator.school_name, CalendarYear, StatTypeId
HAVING COUNT(*) >1
ORDER BY 'Count' DESC
</code>```

Selects records that I would like to set an ISValid bit to 0.

These records are records that appear twice in my database due to an input error.

I'm looking for something like:

```<code>UPDATE NCAAstats
SET IsValid = 0
WHERE (my select statement)
</code>```

This is on MS SQL SERVER 2008

Thanks!

答:
For SQL Server 17</p>

```<code>UPDATE table SET col = val
(SELECT cols FROM table .. )
</code>```

Body:
This query

SELECT
FirstName, LastName, NCAAStats.AccountId, College_Translator.school_name, StatTypeId, COUNT(*) AS 'Count'
FROM NCAAstats
INNER JOIN College_Translator
ON College_Translator.AccountID = NCAAstats.AccountId
GROUP BY FirstName, LastName, NCAAStats.AccountId, College_Translator.school_name, CalendarYear, StatTypeId
HAVING COUNT(*) >1
ORDER BY 'Count' DESC

Selects records that I would like to set an ISValid bit to 0.

These records are records that appear twice in my database due to an input error.

I'm looking for something like:

UPDATE NCAAstats
SET IsValid = 0
WHERE (my select statement)

This is on MS SQL SERVER 2008

Thanks!

Body:
For SQL Server 17

UPDATE table SET col = val
(SELECT cols FROM table .. )


问:
How to get status code response from a Github repo using Octokit?
I'm currently trying to retrieve the status code returned by a Github repo. I have tried to use the #response_status doc, but the documentation isn't very clear on how to create an instance of Octokit:: Error class. And, I can't seem to invoke the method to retrieve the status code.

      #create an instance of the class
      @git_client_error = Octokit::Error.new
      ....
      # sample usage
      @git_client_error.response_status

```

Any examples of implementation using the response_status in ruby would be much appreciated.

答:
If we assume you followed the instructions in the github repo readme, you should have a client object. From there, you make requests on the client. To check the status code you can check responses.  Each client request makes an http request.</p>

```<code>client = Octokit::Client.new(:login => 'somebody', :password => 'something!')
# now make any request
user = client.user
# client.user should return a user object instance of Sawyer::Resource class
response = client.last_response
response.status
=> 200
</code>```

Body:
I'm currently trying to retrieve the status code returned by a Github repo. I have tried to use the #response_status doc, but the documentation isn't very clear on how to create an instance of Octokit:: Error class. And, I can't seem to invoke the method to retrieve the status code.

      #create an instance of the class
      @git_client_error = Octokit::Error.new
      ....
      # sample usage
      @git_client_error.response_status

Any examples of implementation using the response_status in ruby would be much appreciated.

Body:
If we assume you followed the instructions in the github repo readme, you should have a client object. From there, you make requests on the client. To check the status code you can check responses.  Each client request makes an http request.

client = Octokit::Client.new(:login => 'somebody', :password => 'something!')
# now make any request
user = client.user
# client.user should return a user object instance of Sawyer::Resource class
response = client.last_response
response.status
=> 200


问:
Read a large file, line by line, while also writing to a different large file, in Python
I am trying to read a large file line by line while also writing to a large file and I want to know the "best" way of doing so.

I found this Stack Overflow post for reading a large file line by line and want to know the proper way to also incorporate writing to a file. Is there anything better than nesting a 2nd with open

What I currently have:

```<code> #args is parsed from the command line
 #file is an exogenous variable
 with open(args.inPath + file, "r") as fpIn:
   with open(args.outPath + file, "w") as fpOut:
     for line in fpIn:
       if re.match(some match): canWrite = True
       if re.match(some match 2): break
       if canWrite: fpOut.write(line)
</code>```

答:
yield is your best friend: via Lazy Method for Reading Big File in Python?

```<code>def read_in_chunks(file_object, chunk_size=1024):
  """Lazy function (generator) to read a file piece by piece.
  Default chunk size: 1k."""
  while True:
    data = file_object.read(chunk_size)
    if not data:
      break
    yield data

f = open(args.inPath + file, "r")

with open(args.outPath + file, "a") as fpOut:
  for chunk in read_in_chunks(f):
    if re.match(some match): canWrite = True
    if re.match(some match 2): break
    if canWrite: fpOut.write(chunk)
</code>```

See also: https://www.pythoncentral.io/python-generators-and-yield-keyword/ , https://www.geeksforgeeks.org/use-yield-keyword-instead-return-keyword-python/

This will be much lighter on your memory footprint as well.

Body:
I am trying to read a large file line by line while also writing to a large file and I want to know the "best" way of doing so.

I found this Stack Overflow post for reading a large file line by line and want to know the proper way to also incorporate writing to a file. Is there anything better than nesting a 2nd with open

What I currently have:

 #args is parsed from the command line
 #file is an exogenous variable
 with open(args.inPath + file, "r") as fpIn:
   with open(args.outPath + file, "w") as fpOut:
     for line in fpIn:
       if re.match(some match): canWrite = True
       if re.match(some match 2): break
       if canWrite: fpOut.write(line)

Body:
yield is your best friend: via Lazy Method for Reading Big File in Python?

def read_in_chunks(file_object, chunk_size=1024):
  """Lazy function (generator) to read a file piece by piece.
  Default chunk size: 1k."""
  while True:
    data = file_object.read(chunk_size)
    if not data:
      break
    yield data

f = open(args.inPath + file, "r")

with open(args.outPath + file, "a") as fpOut:
  for chunk in read_in_chunks(f):
    if re.match(some match): canWrite = True
    if re.match(some match 2): break
    if canWrite: fpOut.write(chunk)

See also: https://www.pythoncentral.io/python-generators-and-yield-keyword/ , https://www.geeksforgeeks.org/use-yield-keyword-instead-return-keyword-python/

This will be much lighter on your memory footprint as well.


问:
RegEx for matching digits not followed by specific pattern
I am trying to build a regex to match the following style of lines:

```<code>123 warehouse
124 token warehouse.
153token token abc123; etc. - warehouse
223abdc token abc green warehouse
</code>```

But not these lines:

```<code>53red warehouse.
323 green token token etc warehouse.
</code>```

The regex I build uses negative lookahead, but testing it on https://regex101.com/ matches all lines:

```<code>\d+(?!( ?red| ?green)).*(\bwarehouse\b)
</code>```

What is the mistake and how should it be modified? If it matters, the regex should compile under Java (after escaping the necessary characters).

答:
With 123red warehouse.

Your regex matches 1 or more digits 12 then not red or green 3red then any character a space the warehouse.

Add a negative lookahead just after the first digits:

```<code>\d+(?!\d)(?! ?(?:red|green)).*(\bwarehouse\b)
</code>```

DEMO

Body:
I am trying to build a regex to match the following style of lines:

123 warehouse
124 token warehouse.
153token token abc123; etc. - warehouse
223abdc token abc green warehouse

But not these lines:

53red warehouse.
323 green token token etc warehouse.

The regex I build uses negative lookahead, but testing it on https://regex101.com/ matches all lines:

\d+(?!( ?red| ?green)).*(\bwarehouse\b)

What is the mistake and how should it be modified? If it matters, the regex should compile under Java (after escaping the necessary characters).

Body:
With 123red warehouse.

Your regex matches 1 or more digits 12 then not red or green 3red then any character a space the warehouse.

Add a negative lookahead just after the first digits:

\d+(?!\d)(?! ?(?:red|green)).*(\bwarehouse\b)

DEMO


问:
How to set up server authentication in Apache MINA sshd?
I have set up an ssh server using Apache MINA sshd for SFTP. I want to enable server authentication so clients cannot be spoofed. In the documentation page all it says is to use the following method (Apache MINA sshd doc):

```<code>sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("hostkey.ser"));
</code>```

But as I understand, that generates a keypair on its own. What if I want to use an existing certificate file for this server?

答:
FileKeyPairProvider is simpler</p>

```<code>Path path = Paths.get(getClass().getClassLoader().getResource("server-key.pem").toURI());
sshd.setKeyPairProvider(new FileKeyPairProvider(path));
</code>```

Body:
I have set up an ssh server using Apache MINA sshd for SFTP. I want to enable server authentication so clients cannot be spoofed. In the documentation page all it says is to use the following method (Apache MINA sshd doc):

sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("hostkey.ser"));

But as I understand, that generates a keypair on its own. What if I want to use an existing certificate file for this server?

Body:
FileKeyPairProvider is simpler

Path path = Paths.get(getClass().getClassLoader().getResource("server-key.pem").toURI());
sshd.setKeyPairProvider(new FileKeyPairProvider(path));


问:
How to see keyboard modifiers when program launched from windows?
I have a Qt application and would like to determine if Shift (or Ctrl) key was held down when the application was launched.  My goal is to implement a "safe mode" for the application.

I have tried using QApplication::keyboardModifiers() but that function always returns 0 (no modifiers) no matter what keys I have held down when start the app, either by double-clicking it or starting from the command line.

```<code>int main(int argc, char *argv[]) {

    QString homeDocs = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)+"/";
    QCoreApplication::setApplicationName(getAppName());
    QCoreApplication::setOrganizationName(getDeveloperName());
    QCoreApplication::setOrganizationDomain(getDeveloperDomain());

    QSettings settings;

    QApplication a(argc, argv);
    QStringList args = a.arguments();

    Qt::KeyboardModifiers test = QApplication::keyboardModifiers();

</code>```

Receiving a code of 0 but was expecting bit flags indicating which keys were held down.

答:
Use QApplication::queryKeyboardModifiers() instead of QApplication::keyboardModifiers().

See the docs for more details.

Example:

Qt::KeyboardModifiers key = QApplication::queryKeyboardModifiers();

if(key == Qt::ShiftModifier){
    qDebug() << "Shift key is pressed";
}

if(key == Qt::ControlModifier){
    qDebug() << "Ctrl key is pressed";
}
```

Body:
I have a Qt application and would like to determine if Shift (or Ctrl) key was held down when the application was launched.  My goal is to implement a "safe mode" for the application.

I have tried using QApplication::keyboardModifiers() but that function always returns 0 (no modifiers) no matter what keys I have held down when start the app, either by double-clicking it or starting from the command line.

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

    QString homeDocs = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)+"/";
    QCoreApplication::setApplicationName(getAppName());
    QCoreApplication::setOrganizationName(getDeveloperName());
    QCoreApplication::setOrganizationDomain(getDeveloperDomain());

    QSettings settings;

    QApplication a(argc, argv);
    QStringList args = a.arguments();

    Qt::KeyboardModifiers test = QApplication::keyboardModifiers();

Receiving a code of 0 but was expecting bit flags indicating which keys were held down.


问:
how can i add a css file to body of a page?
I am working on a page which has a print view so when the user clicks on "Print" a new window pops up and I want to add a .css file just for that window. </p>

<p>Thanks </p>

答:
```<code>$(document).ready(function () {
    $(".print").click(function () {
        $("head").append("<link>");
        css = $("head").children(":last");
        css.attr({
            rel: "stylesheet",
            type: "text/css",
            href: "css/ecsPrint.css"
        });
        return false;
    });
});
</code>```

Unless this is a Internal Web Application, i wouldnt recommend loading css with JS.

Body:
I am working on a page which has a print view so when the user clicks on "Print" a new window pops up and I want to add a .css file just for that window.

Thanks

Body:
$(document).ready(function () {
    $(".print").click(function () {
        $("head").append("<link>");
        css = $("head").children(":last");
        css.attr({
            rel: "stylesheet",
            type: "text/css",
            href: "css/ecsPrint.css"
        });
        return false;
    });
});

Unless this is a Internal Web Application, i wouldnt recommend loading css with JS.


问:
Pandas - group by one column, sort by another, get value from the third column
I would like to take pandas dataframe, group it by one column, sort it by another column and take first element from third column and populate original dataframe.

Here is my original df. I would to group by col_1, sort by col_2 (ascending) and take first element from col_3 and populate col_4 with results.

```<code>df_in = pd.DataFrame({'col_1':['A', 'A', 'A', 'B', 'B', 'B'], 'col_2': [5,9,2, 3,7,1],
                   'col_3': ['c','d','k','n','l','f']})
</code>```

[

Here is how output df should look like:

```<code>df_out = pd.DataFrame({'col_1':['A', 'A', 'A', 'B', 'B', 'B'], 'col_2': [5,9,2, 3,7,1],
                   'col_3': ['c','d','k','n','l','f'], 'col_4': ['k','k','k','f','f','f'], })
</code>```

I can accomplish grouping and sorting with group and transform, but how to extract first element is not clear.

Sorry SO does not display images correctly ;-(

答:
```<code> df['col_4']=df.sort_values(['col_1','col_2']).groupby('col_1')['col_3'].transform(lambda x: x.iloc[0])
</code>```

Output:

```<code>  col_1  col_2 col_3 col_4
0     A      5     c     k
1     A      9     d     k
2     A      2     k     k
3     B      3     n     f
4     B      7     l     f
5     B      1     f     f
</code>```

Body:
I would like to take pandas dataframe, group it by one column, sort it by another column and take first element from third column and populate original dataframe.

Here is my original df. I would to group by col_1, sort by col_2 (ascending) and take first element from col_3 and populate col_4 with results.

df_in = pd.DataFrame({'col_1':['A', 'A', 'A', 'B', 'B', 'B'], 'col_2': [5,9,2, 3,7,1],
                   'col_3': ['c','d','k','n','l','f']})

[

Here is how output df should look like:

df_out = pd.DataFrame({'col_1':['A', 'A', 'A', 'B', 'B', 'B'], 'col_2': [5,9,2, 3,7,1],
                   'col_3': ['c','d','k','n','l','f'], 'col_4': ['k','k','k','f','f','f'], })

I can accomplish grouping and sorting with group and transform, but how to extract first element is not clear.

Sorry SO does not display images correctly ;-(

Body:
 df['col_4']=df.sort_values(['col_1','col_2']).groupby('col_1')['col_3'].transform(lambda x: x.iloc[0])

Output:

  col_1  col_2 col_3 col_4
0     A      5     c     k
1     A      9     d     k
2     A      2     k     k
3     B      3     n     f
4     B      7     l     f
5     B      1     f     f


问:
Having trouble understanding output of line of code -
I don't understand the use of return 0* statement??

Tried looking for answers on Google

```<code>return 0*printf("%d",a[i]);
</code>```

I don't understand the outcome.

答:
TL/DR - it's writing the value of a[i] to standard output, multiplying the number of characters written by 0, and returning the result...which is always 0.

I'd like to see the rest of the code for context - based on this single line of code it doesn't make sense, but maybe in context it would look a little less nonsensical.

printf returns the number of characters (bytes) written to the output stream, so this is writing the value of a[i] to standard output, multiplying the number of characters written by 0, and returning the result ... which is always 0, so again, this line in isolation doesn't make a ton of sense.

I'm hard-pressed to think of a use case where this would be logical, but that doesn't mean there isn't one.  Perhaps the author wants to make sure the value of a[i] gets displayed even in the event of an error, but why not just do

```<code>if ( error_occurred )
{
  printf( "%d", a[i] );
  return 0;
}
</code>```

in that case?

It could be the author intends the print statement to be executed concurrent with the return, in which case they don't understand how C works.  It could be the author confuses terse code with fast code, in which case they still don't understand how C works.

Or maybe the author is being tricky for tricky's sake.

Body:
I don't understand the use of return 0* statement??

Tried looking for answers on Google

return 0*printf("%d",a[i]);

I don't understand the outcome.

Body:
TL/DR - it's writing the value of a[i] to standard output, multiplying the number of characters written by 0, and returning the result...which is always 0.

I'd like to see the rest of the code for context - based on this single line of code it doesn't make sense, but maybe in context it would look a little less nonsensical.

printf returns the number of characters (bytes) written to the output stream, so this is writing the value of a[i] to standard output, multiplying the number of characters written by 0, and returning the result ... which is always 0, so again, this line in isolation doesn't make a ton of sense.

I'm hard-pressed to think of a use case where this would be logical, but that doesn't mean there isn't one.  Perhaps the author wants to make sure the value of a[i] gets displayed even in the event of an error, but why not just do

if ( error_occurred )
{
  printf( "%d", a[i] );
  return 0;
}

in that case?

It could be the author intends the print statement to be executed concurrent with the return, in which case they don't understand how C works.  It could be the author confuses terse code with fast code, in which case they still don't understand how C works.

Or maybe the author is being tricky for tricky's sake.


问:
Why ng build just doesn’t work in the Angular app?
Created a new project, did not change anything. I started ng build, took the dist folder (only it) and ran it on the local server. In the end, nothing. What's wrong?</p>

答:
I think your question miss some precisions.
You are trying to run your angular app on a local server. Which ?

When you build your app with ng build you build a static app. (And when you use the option --prod you app will be optimized for production)

Try simply with the npm library http-server AND note that currently there is a bug in the latest version of this library ! So try the version @0.9 for example.

Maybe this is it you already try with the latest version and you see nothing so..

Hope this helps.