问:
read n-th line in a text file and process in MS Batch
Well.. What I need to is actually just to read the n-th line of a cleartext file and save in a variable to process it further within the batch. So I have been googling quite maaany hours and found many solutions (all in a for loop). Also many here on Stack Overflow, but well, none worked for me.

Here is an example of one way I tried out

```<code>for /f "skip=%toskip%" %%G IN (passwd.txt) DO if not defined line set "line=%%G"
</code>```

So here the details on my project.

contents: pwcracker.bat (shown in the following)

requires: 7za.exe, passwd.txt (a database with 1 possible password on each line)

pwcracker.bat:

```<code>    @echo on

    for /f %%i in ("passwd.txt") do set size=%%~zi
    if %size% leq 0 (
     echo Please create a dictionary of passwords first [File not found: passwd.txt]!>result.txt
     exit 1
    )

    @Overwrite result.txt if it exists
    echo [RESULT]>result.txt

    @Try to delete the log if it exists
    IF EXIST logging.txt del /F logging.txt

    @REM If the file wasn't deleted for some reason, stop and error
    IF EXIST logging.txt (
     echo The log file must be removed!>>result.txt
     exit 1
    )

    @Ask user for the file to unzip
    set /p filename=Enter 7z filename [name.7z]:

    @Check amount of PWs to try within the dictionary
    cls
    setlocal EnableDelayedExpansion
    set "cmd=findstr /R /N "^^" passwd.txt | find /C ":""

    @Set the amount to try
    for /f %%a in ('!cmd!') do set tries=%%a

    @####################################

    @Begin the for loop to try all PWs until unzipped or all PWs are tried
    FOR /L %%X IN (1,1,%tries%) DO (

     @Set PW to try
     @CODE INPUT TO READ AND STORE PW in local variable %passwd%

     @try to unzip using the given password and log the output
     7za e %filename% -o%CD%\unzipped -p%passwd%>>logging.txt

     @check the size of the log file
     for /f %%i in ("logging.txt") do set size=%%~zi

     @see whether it was succesful and log the tried password in the resuts
     findstr /m "Error" logging.txt
     if %errorlevel%==1 (
      echo It didn't work with PW: %passwd%>>result.txt

      @Try to delete the log if it exists
      IF EXIST logging.txt del /F logging.txt

      @REM If the file wasn't deleted for some reason, stop and error
      IF EXIST logging.txt (
       echo The log file couldn't be removed!>>result.txt
       exit 1
      )
      @end of error-check clause
     )

     else (
      if %size% leq 0 (
      echo Something went wrong, please check manually>result.txt
      echo Tried PW : %passwd% >>result.txt
      exit 1
     )
    @end of prior else block
    )

    else (
     echo Unzipped succesfully with PW: %passwd%>result.txt
    exit 1
    )

   @end of for loop (1,1,tries)
   )
</code>```

This batch file will basically just "crack" my aes-encrypted 7zip file as I have mistyped the password and don't know what it is for certain. And yeah, tools like 7zcracker don't work and end up stating "The passwod was 1" btw, but this "tool" can see whether there was an "Error" while unzipping, or not (since only the data is encrypted and not the names, the 7z file can be "unzipped", but the contents' size is 0 ofc)

答:
You don't need to get the number of tries. Just read each line in the password file.

```<code>FOR /F "usebackq tokens=*" %%p IN (`TYPE passwd.txt`) DO (
    ECHO Trying password %%p
    REM try the password
)
</code>```

Body:
Well.. What I need to is actually just to read the n-th line of a cleartext file and save in a variable to process it further within the batch. So I have been googling quite maaany hours and found many solutions (all in a for loop). Also many here on Stack Overflow, but well, none worked for me.

Here is an example of one way I tried out

for /f "skip=%toskip%" %%G IN (passwd.txt) DO if not defined line set "line=%%G"

So here the details on my project.

contents: pwcracker.bat (shown in the following)

requires: 7za.exe, passwd.txt (a database with 1 possible password on each line)

pwcracker.bat:

    @echo on

    for /f %%i in ("passwd.txt") do set size=%%~zi
    if %size% leq 0 (
     echo Please create a dictionary of passwords first [File not found: passwd.txt]!>result.txt
     exit 1
    )

    @Overwrite result.txt if it exists
    echo [RESULT]>result.txt

    @Try to delete the log if it exists
    IF EXIST logging.txt del /F logging.txt

    @REM If the file wasn't deleted for some reason, stop and error
    IF EXIST logging.txt (
     echo The log file must be removed!>>result.txt
     exit 1
    )

    @Ask user for the file to unzip
    set /p filename=Enter 7z filename [name.7z]:

    @Check amount of PWs to try within the dictionary
    cls
    setlocal EnableDelayedExpansion
    set "cmd=findstr /R /N "^^" passwd.txt | find /C ":""

    @Set the amount to try
    for /f %%a in ('!cmd!') do set tries=%%a

    @####################################

    @Begin the for loop to try all PWs until unzipped or all PWs are tried
    FOR /L %%X IN (1,1,%tries%) DO (

     @Set PW to try
     @CODE INPUT TO READ AND STORE PW in local variable %passwd%

     @try to unzip using the given password and log the output
     7za e %filename% -o%CD%\unzipped -p%passwd%>>logging.txt

     @check the size of the log file
     for /f %%i in ("logging.txt") do set size=%%~zi

     @see whether it was succesful and log the tried password in the resuts
     findstr /m "Error" logging.txt
     if %errorlevel%==1 (
      echo It didn't work with PW: %passwd%>>result.txt

      @Try to delete the log if it exists
      IF EXIST logging.txt del /F logging.txt

      @REM If the file wasn't deleted for some reason, stop and error
      IF EXIST logging.txt (
       echo The log file couldn't be removed!>>result.txt
       exit 1
      )
      @end of error-check clause
     )

     else (
      if %size% leq 0 (
      echo Something went wrong, please check manually>result.txt
      echo Tried PW : %passwd% >>result.txt
      exit 1
     )
    @end of prior else block
    )

    else (
     echo Unzipped succesfully with PW: %passwd%>result.txt
    exit 1
    )

   @end of for loop (1,1,tries)
   )

This batch file will basically just "crack" my aes-encrypted 7zip file as I have mistyped the password and don't know what it is for certain. And yeah, tools like 7zcracker don't work and end up stating "The passwod was 1" btw, but this "tool" can see whether there was an "Error" while unzipping, or not (since only the data is encrypted and not the names, the 7z file can be "unzipped", but the contents' size is 0 ofc)

Body:
You don't need to get the number of tries. Just read each line in the password file.

FOR /F "usebackq tokens=*" %%p IN (`TYPE passwd.txt`) DO (
    ECHO Trying password %%p
    REM try the password
)


来源: stackexchange

问:
Ruby Mail gem, how to script mail messages
I have testmail.rb on a CENTOS 5 VM with SELinux permissive and IPtables off:

```<code>require 'rubygems'
require 'mail'

options = { :address              => "mail.domain.com",
            :port                 => 466,
            :domain               => 'otherdomain.com',
            :user_name            => 'somedude@domain.com',
            :password             => 'topsecret',
            :authentication       => 'plain',
            :enable_starttls_auto => true  }
 Mail.defaults do
  delivery_method :smtp, options
end

 mail = Mail.new do
      from 'somedude@otherdomain.com'
        to 'admin@domain.com'
   subject 'This is a test email'
      body File.read('body.txt')
 end

puts mail.to_s
</code>```

The result when the script is run is this:

```<code>Date: Tue, 30 Nov 2010 12:12:58 -0500
From: somedude@otherdomain.com
To: admin@domain.com
Message-ID: <4cf5309a2f074_284015c5c4de91b8270b2@apvdbs03.3rdomain.local.mail>
Subject: This is a test email
Mime-Version: 1.0
Content-Type: text/plain;
 charset=UTF-8
Content-Transfer-Encoding: 7bit

test!
</code>```

"test!" is the content of body.txt.

No email ever reaches the sent to account. The smtp settings we got from the sent to domain admin. I used telnet to successfully send an email to the domain on the unencrypted port (25) but got no response from the encrypted port (466), possibly because my telnet session was unencrypted?

What are some ways I can see what's going on during the script execution to troubleshoot?

Update:
Tried redirecting: > log.log 2>&1, but that didn't provide any additional info.

答:
You're missing the line to actually send. Try adding

```<code>mail.deliver!
</code>```

to the end of your script.

ContentLicense: CC BY-SA 2.5

Body:
I have testmail.rb on a CENTOS 5 VM with SELinux permissive and IPtables off:

require 'rubygems'
require 'mail'

options = { :address              => "mail.domain.com",
            :port                 => 466,
            :domain               => 'otherdomain.com',
            :user_name            => 'somedude@domain.com',
            :password             => 'topsecret',
            :authentication       => 'plain',
            :enable_starttls_auto => true  }
 Mail.defaults do
  delivery_method :smtp, options
end

 mail = Mail.new do
      from 'somedude@otherdomain.com'
        to 'admin@domain.com'
   subject 'This is a test email'
      body File.read('body.txt')
 end

puts mail.to_s

The result when the script is run is this:

Date: Tue, 30 Nov 2010 12:12:58 -0500
From: somedude@otherdomain.com
To: admin@domain.com
Message-ID: <4cf5309a2f074_284015c5c4de91b8270b2@apvdbs03.3rdomain.local.mail>
Subject: This is a test email
Mime-Version: 1.0
Content-Type: text/plain;
 charset=UTF-8
Content-Transfer-Encoding: 7bit

test!

"test!" is the content of body.txt.

No email ever reaches the sent to account. The smtp settings we got from the sent to domain admin. I used telnet to successfully send an email to the domain on the unencrypted port (25) but got no response from the encrypted port (466), possibly because my telnet session was unencrypted?

What are some ways I can see what's going on during the script execution to troubleshoot?

Update:
Tried redirecting: > log.log 2>&1, but that didn't provide any additional info.

Body:
You're missing the line to actually send. Try adding

mail.deliver!

to the end of your script.


问:
Does openssl accept multiple domains in subjectAltName as part of the -subj option?
I have been trying to create certificates with the subjectAltName of the type /subjectAltName=DNS.1=www.domain.net,DNS.2=*.www.domain.net but when I view the key only the CN I set is displayed, ie www.domain.net.

Is the syntax I am using for the subjectAltName wrong, or is adding the subjectAltNames from ta configuration file the only way to accomplish that?

答:
You can put the alt names into the config lie you stated. Why do you need it otherwise anyways?

If you are too tired of always changing the config's contents, just write a shell or bash script to ask you for the input and to edit the file and roll the certificates afterwards I guess

ContentLicense: CC BY-SA 3.0


问:
Html.BeginForm with route id parameter and get parameter on submit?
I have a method like this in my mvc project:

```<code>[Route("Categories/{categoryId}")]
public ActionResult List(SearchQueryCommand searchQuery) {
    //Stuff
    return View();

}
</code>```

So this method is called like: 'www.myweb.com/Categories/212'

But i have a dropdownlist with a form that sorts this query and send it back again to the server to get the sorted results.
I have this in my razor view:

```<code>@using (Html.BeginForm(new { categoryId = Model.CategoryId }))
{
                <div>
                    <small>@Html.LabelFor(m => m.Order, "sort by")</small>
                    @Html.DropDownListFor(m => m.Order, Model.ProductSortByOptions, new { onchange = "this.form.submit();" })
                    <button class="nojs" type="submit">ok</button>
                </div>
}
</code>```

My problem is that i dont know how to format my code to have in my url something like: 'www.myweb.com/Categories/213?Order=MinPrice'.

What are my options to perform this?

答:
You need to add method GET to the form tag

```<code>@using (Html.BeginForm("MethodName", "YourController",FormMethod.Get))
</code>```

{
    ...
}

Then your Form tag will generate GET request and all params from form will be in URL query string.

Body:
I have a method like this in my mvc project:

[Route("Categories/{categoryId}")]
public ActionResult List(SearchQueryCommand searchQuery) {
    //Stuff
    return View();

}

So this method is called like: 'www.myweb.com/Categories/212'

But i have a dropdownlist with a form that sorts this query and send it back again to the server to get the sorted results.
I have this in my razor view:

@using (Html.BeginForm(new { categoryId = Model.CategoryId }))
{

                    @Html.LabelFor(m => m.Order, "sort by")
                    @Html.DropDownListFor(m => m.Order, Model.ProductSortByOptions, new { onchange = "this.form.submit();" })
                    <button class="nojs" type="submit">ok</button>

}

My problem is that i dont know how to format my code to have in my url something like: 'www.myweb.com/Categories/213?Order=MinPrice'.

What are my options to perform this?

Body:
You need to add method GET to the form tag

@using (Html.BeginForm("MethodName", "YourController",FormMethod.Get))

{
    ...
}

Then your Form tag will generate GET request and all params from form will be in URL query string.


问:
Are there simple ways to write/read records to/from fifos in VHDL/FPGA?
Assuming a fifo with record type in and out, is there a simple way to handle the mapping between the record type in the input and output of the fifo wrapper and std_logic_vector in the actual fifo?</p>

答:
As presented, you can hide the conversation in a package. So you have 2 functions to and from FIFO interface to a record.

Rob Gaddi (vice-chair at the IEEE WG for VHDL) presented once a set of helper procedures for faster packing and unpacking std_logic_vectors to and from record types.
See his proposed pack and unpack subprograms.

The working group itself had long discussions on how to solve such an issue. There are 3 possibilities:

VHDL supports generic types on entity declarations. So a VHDL-2008 compliant synthesis tool could create a generic FIFO accepting any type *) as a FIFO element.

VHDL-2017 adds a reflection API that can at least solve the conversation from record to std_logic_vector. I'm working on a idea how to implement the reverse path.

A direct solution to iterate record elements was not found yet and is delayed to the next revision (VHDL-2020)

*) Any synthesizable scalar, array or record type.


问:
Why is my simple_fields_for not iterating
I have the following (simplified) classes:

```<code>class CandidateList < ActiveRecord::Base
  has_many :candidates, inverse_of: :candidate_list, dependent: :destroy
  ...
end
</code>```

and

```<code>class Candidate < ActiveRecord::Base
  belongs_to :candidate_list, inverse_of: :candidates
  ...
end
</code>```

In my controller, I create a CandidateList with 10 Candidate objects and querying the database verifies that they exist and are attached.

In my form, I've got the following:

```<code><%= simple_form_for save_bingo_terms_path( candidate_list_id: @candidate_list ) do |f| %>
  ...
  <%= @candidate_list.candidates.count %>
  <table>
    <%= f.simple_fields_for :candidates do |cf| %>
    <tr>
      <td><%= cf.input :name, label: false %></td>
      <td><%= cf.input :definition, label: false %></td>
    </tr>
    <% end %>
<% end %>
</code>```

Can anyone help me understand why it only shows me a single row in the table with an input field for name and definition even though the count output above the table shows 10?

Thanks in advance!

答:
:candidates is not associated with the @candidate_list object, it's associated with a save_bingo_terms_path

Change the simple_form_for to

```<code><%= simple_form_for @candidate_list do |f| %>
</code>```

And don't forget to specify...

```<code>class CandidateList < ActiveRecord::Base
  has_many :candidates, inverse_of: :candidate_list, dependent: :destroy
  accepts_nested_attributes_for :candidates
  ...
end
</code>```

Alternatively you can explicitly specify an each loop and reference each candidate

```<code><% @candidate_list.candidates each do |candidate| %>
  <% f.simple_fields_for :candidates, candidate do |cf| %>
    <tr>
      <td><%= cf.input :name, label: false %></td>
      <td><%= cf.input :definition, label: false %></td>
    </tr>
  <% end %>
<% end %>
</code>```

Body:
I have the following (simplified) classes:

class CandidateList < ActiveRecord::Base
  has_many :candidates, inverse_of: :candidate_list, dependent: :destroy
  ...
end

and

class Candidate < ActiveRecord::Base
  belongs_to :candidate_list, inverse_of: :candidates
  ...
end

In my controller, I create a CandidateList with 10 Candidate objects and querying the database verifies that they exist and are attached.

In my form, I've got the following:

<%= simple_form_for save_bingo_terms_path( candidate_list_id: @candidate_list ) do |f| %>
  ...
  <%= @candidate_list.candidates.count %>

    <%= f.simple_fields_for :candidates do |cf| %>

      <%= cf.input :name, label: false %>
      <%= cf.input :definition, label: false %>

    <% end %>
<% end %>

Can anyone help me understand why it only shows me a single row in the table with an input field for name and definition even though the count output above the table shows 10?

Thanks in advance!

Body:
:candidates is not associated with the @candidate_list object, it's associated with a save_bingo_terms_path

Change the simple_form_for to

<%= simple_form_for @candidate_list do |f| %>

And don't forget to specify...

class CandidateList < ActiveRecord::Base
  has_many :candidates, inverse_of: :candidate_list, dependent: :destroy
  accepts_nested_attributes_for :candidates
  ...
end

Alternatively you can explicitly specify an each loop and reference each candidate

<% @candidate_list.candidates each do |candidate| %>
  <% f.simple_fields_for :candidates, candidate do |cf| %>
    <tr>
      <td><%= cf.input :name, label: false %></td>
      <td><%= cf.input :definition, label: false %></td>
    </tr>
  <% end %>
<% end %>


问:
SQL Query for Vehicle Mileage
I’m trying to design a fleet management database for my university course.

Currently my query searches the “view” that I have created and calculates employees total mileage based on year, by subtracting their journey's end miles from their start miles, which works and groups them in a result.
But what I can’t do, no matter how hard I try, is to then query what employees do more than 25,000 miles a year from the result that I have created. I not sure if this is even possible to query the result of an alias column?

```<code>SELECT Assigned_Vehicle_id "Assigned Vehicle id",
       Payroll_Number "Payroll Number", First_Name "First Name",
       Surname, Vehicle_Registration "Vehicle Registration",
       Manufacturer_Name "Manufacturer Name", Model_Name "Model Name",
       SUM(End_Miles - Start_Miles) "Total Miles Driven"
  FROM Destinations
 WHERE YEAR(Start_Date) = 2016
 GROUP BY Assigned_Vehicle_id, Payroll_Number, First_Name, Surname,
       Vehicle_Registration, Manufacturer_Name, Model_Name;
</code>```

答:
Try this. Notice the HAVING clause after the GROUP BY</p>

```<code> SELECT Assigned_Vehicle_id "Assigned Vehicle id",
 Payroll_Number "Payroll Number", First_Name "First Name", Surname,
 Vehicle_Registration "Vehicle Registration", Manufacturer_Name
 "Manufacturer Name",
 Model_Name "Model Name", SUM(End_Miles - Start_Miles) "Total Miles Driven"
 FROM Destinations
 WHERE YEAR(Start_Date) = 2016
 GROUP BY
 Assigned_Vehicle_id, Payroll_Number, First_Name, Surname,
 Vehicle_Registration, Manufacturer_Name, Model_Name
 HAVING SUM(End_Miles - Start_Miles) > 25000
</code>```

Title: SQL Query for Vehicle Mileage

Body:
I’m trying to design a fleet management database for my university course.

Currently my query searches the “view” that I have created and calculates employees total mileage based on year, by subtracting their journey's end miles from their start miles, which works and groups them in a result.
But what I can’t do, no matter how hard I try, is to then query what employees do more than 25,000 miles a year from the result that I have created. I not sure if this is even possible to query the result of an alias column?

SELECT Assigned_Vehicle_id "Assigned Vehicle id",
       Payroll_Number "Payroll Number", First_Name "First Name",
       Surname, Vehicle_Registration "Vehicle Registration",
       Manufacturer_Name "Manufacturer Name", Model_Name "Model Name",
       SUM(End_Miles - Start_Miles) "Total Miles Driven"
  FROM Destinations
 WHERE YEAR(Start_Date) = 2016
 GROUP BY Assigned_Vehicle_id, Payroll_Number, First_Name, Surname,
       Vehicle_Registration, Manufacturer_Name, Model_Name;

Body:
Try this. Notice the HAVING clause after the GROUP BY

 SELECT Assigned_Vehicle_id "Assigned Vehicle id",
 Payroll_Number "Payroll Number", First_Name "First Name", Surname,
 Vehicle_Registration "Vehicle Registration", Manufacturer_Name
 "Manufacturer Name",
 Model_Name "Model Name", SUM(End_Miles - Start_Miles) "Total Miles Driven"
 FROM Destinations
 WHERE YEAR(Start_Date) = 2016
 GROUP BY
 Assigned_Vehicle_id, Payroll_Number, First_Name, Surname,
 Vehicle_Registration, Manufacturer_Name, Model_Name
 HAVING SUM(End_Miles - Start_Miles) > 25000


问:
Syntax error on simple if condition (if partychoice = R:)
New programmer, working in python 2.7.

With this code, I get a syntax error in the line 'if partychoice = R, stating the '=' is invalid syntax. How come it won;t let me assign the variable.

Also, I'm sure there are tons of other errors, but I have to start somewhere.

```<code>print "Welcome to 'Pass the Bill', where you will take on the role of a professional lobbyist trying to guide a bill through Congress and get it signed into law by the President!"
start = raw_input(str ('Press Y to continue:'))
print 'Great, lets get started!'
partychoice = raw_input (str("Would you like to be a Republican or Democrat? Type 'R' for Republican or 'D' for Democrat."))
if partychoice = R:
    print 'Ah, the Grand old Party of Lincoln and Reagan. Great Choice!'
    replegchoice = raw_input (str("What type of bill what you like congress to introduce? Restrictions on abortions, lower income taxes, easier access to automatic weapons, private health plans, or stricter immigration laws? ( A = abortion restrictions, L = lower taxes, AW = automatic weapons, H = private health plans, S = stricter immigration laws'))
    if replegchoice = A or a
            print 'A controversial choice, despite support of most Republicans, you are sure to face opposition from Democrats in Congress!'
    if replegchoice = L or l
            print 'A popular idea, Republicans in Congress are sure to support this idea, as will many American voters!'
    if replegchoice = AW, aw, Aw, or AW
            print 'Rural, midwest, and small town voters will love this, as will most Republicans in Congress. Democrats and voters in urban cities will surely be less supportive.'
    if replegchoice = H or h
            print 'Eimination of Medicare, Medicaid, and Obamacare! Republicans generally like the idea of making each person responsible for paying their own health care costs'
    if replegchoice = S or s
            print 'a popular idea supported by president Trump, this is sure face strong opposition from democrats and many voters.'
</code>```

Thanks everyone.

答:
You need to replace "=" with "==" in the statement:

```<code>if partychoice = R:"
</code>```

"=" is an assignment operator

"==" is an equality operator

e.g.

```<code>#assign something to a variable
x = 5
print x
>>5

#compare for equality
y = 6
if y == 6:
    print y
else:
    print "y is not 6"
>>6
</code>```

Be sure to use informative titles in future posts, something that relates to the question you're asking.

Body:
New programmer, working in python 2.7.

With this code, I get a syntax error in the line 'if partychoice = R, stating the '=' is invalid syntax. How come it won;t let me assign the variable.

Also, I'm sure there are tons of other errors, but I have to start somewhere.

print "Welcome to 'Pass the Bill', where you will take on the role of a professional lobbyist trying to guide a bill through Congress and get it signed into law by the President!"
start = raw_input(str ('Press Y to continue:'))
print 'Great, lets get started!'
partychoice = raw_input (str("Would you like to be a Republican or Democrat? Type 'R' for Republican or 'D' for Democrat."))
if partychoice = R:
    print 'Ah, the Grand old Party of Lincoln and Reagan. Great Choice!'
    replegchoice = raw_input (str("What type of bill what you like congress to introduce? Restrictions on abortions, lower income taxes, easier access to automatic weapons, private health plans, or stricter immigration laws? ( A = abortion restrictions, L = lower taxes, AW = automatic weapons, H = private health plans, S = stricter immigration laws'))
    if replegchoice = A or a
            print 'A controversial choice, despite support of most Republicans, you are sure to face opposition from Democrats in Congress!'
    if replegchoice = L or l
            print 'A popular idea, Republicans in Congress are sure to support this idea, as will many American voters!'
    if replegchoice = AW, aw, Aw, or AW
            print 'Rural, midwest, and small town voters will love this, as will most Republicans in Congress. Democrats and voters in urban cities will surely be less supportive.'
    if replegchoice = H or h
            print 'Eimination of Medicare, Medicaid, and Obamacare! Republicans generally like the idea of making each person responsible for paying their own health care costs'
    if replegchoice = S or s
            print 'a popular idea supported by president Trump, this is sure face strong opposition from democrats and many voters.'

Thanks everyone.

Body:
You need to replace "=" with "==" in the statement:

if partychoice = R:"

"=" is an assignment operator

"==" is an equality operator

e.g.

#assign something to a variable
x = 5
print x
>>5

#compare for equality
y = 6
if y == 6:
    print y
else:
    print "y is not 6"
>>6

Be sure to use informative titles in future posts, something that relates to the question you're asking.


问:
Bash script for iterating through defined set of file names and performing commands
I have a set of folders named for example 10, 12, 13, 14, 18, 24 etc. They don't change numbers in any standard increment. I then need to move repetitively into the folders and then into the next one to perform SVN commands which are the same except for some variable extension, e.g.:

```<code>/home/boy$ cp /home/files/*Session10.* . ; svn add *Session10.*; svn commit; cd ..; cd 12;
</code>```

Then the next command is analogous:

```<code>/home/boy$ cp /home/files/*Session12.* . ; svn add *Session12.*; svn commit; cd ..; cd 14;
</code>```

So there should be an array or list defined, and then a for loop through that list, and then a variable whose name is expanded to be fed into the cp and svn command.
Any thoughts? I hope that it can be done in the command prompt rather than in a bash script file.

答: base=$PWD; for num in *; do cd $base/$num; cp /home/files/*Session${num}.* .; svn add *Session${num}.*; svn commit; done

Body:
I have a set of folders named for example 10, 12, 13, 14, 18, 24 etc. They don't change numbers in any standard increment. I then need to move repetitively into the folders and then into the next one to perform SVN commands which are the same except for some variable extension, e.g.:

/home/boy$ cp /home/files/*Session10.* . ; svn add *Session10.*; svn commit; cd ..; cd 12;

Then the next command is analogous:

/home/boy$ cp /home/files/*Session12.* . ; svn add *Session12.*; svn commit; cd ..; cd 14;

So there should be an array or list defined, and then a for loop through that list, and then a variable whose name is expanded to be fed into the cp and svn command.
Any thoughts? I hope that it can be done in the command prompt rather than in a bash script file.


问:
Conversion failed when converting the varchar value 'SAT' to data type int
I have a table ConsoleGames wherein all columns are of type varchar(50). When I try to create a new table console_games by amending existing datatypes by using the query:

```<code>CREATE TABLE console_games
(
    game_rank integer,
    game_name varchar(1200),
    platform_name varchar(1200),
    game_year integer,
    genre varchar(200),
    publisher varchar(1200),
    na_sales float,
    eu_sales float,
    jp_sales float,
    other_sales float
)

INSERT INTO console_games
    SELECT *
    FROM [dbo].[RAWConsoleGames]
</code>```

I get the following error message:

Msg 245, Level 16, State 1, Line 17

  Conversion failed when converting the varchar value 'SAT' to data type int.

When I look into the data in the table the value 'SAT' is in a column for which I am not changing the datatype. 'SAT' value exists in the Platform column which is of varchar type and I am not trying to change the type to int.

Any help will be appreciated.

Thanks

答:
Clearly 'SAT' is not and will never convert to an INT.

Always best to specify the columns to insert ... things change

Now, if the source data is suspect, add a try_convert().  If the conversion fails, a null value will be returned

I don't know the column names of your source, so I substituted SomeColN

```<code>INSERT INTO console_games
SELECT try_convert(integer      ,SomeCol1)
      ,try_convert(varchar(1200),SomeCol2)
      ,try_convert(varchar(1200),SomeCol3)
      ,try_convert(integer      ,SomeCol4)
      ,try_convert(varchar(200) ,SomeCol5)
      ,try_convert(varchar(1200),SomeCol6)
      ,try_convert(float        ,SomeCol7)
      ,try_convert(float        ,SomeCol8)
      ,try_convert(float        ,SomeCol9)
      ,try_convert(float        ,SomeCol10)
 FROM [dbo].[RAWConsoleGames]
</code>```

Just for fun, try:

```<code>Select try_convert(int,'SAT')
Select try_convert(int,'25.25')
Select try_convert(int,'25')
</code>```

Body:
I have a table ConsoleGames wherein all columns are of type varchar(50). When I try to create a new table console_games by amending existing datatypes by using the query:

CREATE TABLE console_games
(
    game_rank integer,
    game_name varchar(1200),
    platform_name varchar(1200),
    game_year integer,
    genre varchar(200),
    publisher varchar(1200),
    na_sales float,
    eu_sales float,
    jp_sales float,
    other_sales float
)

INSERT INTO console_games
    SELECT *
    FROM [dbo].[RAWConsoleGames]

I get the following error message:

Msg 245, Level 16, State 1, Line 17

  Conversion failed when converting the varchar value 'SAT' to data type int.

When I look into the data in the table the value 'SAT' is in a column for which I am not changing the datatype. 'SAT' value exists in the Platform column which is of varchar type and I am not trying to change the type to int.

Any help will be appreciated.

Thanks

Body:
Clearly 'SAT' is not and will never convert to an INT.

Always best to specify the columns to insert ... things change

Now, if the source data is suspect, add a try_convert().  If the conversion fails, a null value will be returned

I don't know the column names of your source, so I substituted SomeColN

INSERT INTO console_games
SELECT try_convert(integer      ,SomeCol1)
      ,try_convert(varchar(1200),SomeCol2)
      ,try_convert(varchar(1200),SomeCol3)
      ,try_convert(integer      ,SomeCol4)
      ,try_convert(varchar(200) ,SomeCol5)
      ,try_convert(varchar(1200),SomeCol6)
      ,try_convert(float        ,SomeCol7)
      ,try_convert(float        ,SomeCol8)
      ,try_convert(float        ,SomeCol9)
      ,try_convert(float        ,SomeCol10)
 FROM [dbo].[RAWConsoleGames]

Just for fun, try:

Select try_convert(int,'SAT')
Select try_convert(int,'25.25')
Select try_convert(int,'25')


问:
Where is "~/.gradle" folder in Windows?
I was following the React Native document to create a signed APK.
Source

Setting up Gradle variables

Place the my-release-key.keystore file under the android/app directory
in your project folder.

Edit the file ~/.gradle/gradle.properties and add the following

```<code>MYAPP_RELEASE_STORE_FILE=my-release-key.keystore
MYAPP_RELEASE_KEY_ALIAS=my-key-alias
MYAPP_RELEASE_STORE_PASSWORD=*****
MYAPP_RELEASE_KEY_PASSWORD=*****
</code>```

Originally, I thought ~/.gradle is <project folder>/android/.gradle. However, it is not... In the command line, I ran the cd ~/.gradle/ command and it says:

The system cannot find the path specified.

Would you please let me know where is this folder (in Windows), so I can create gradle.properties? Thank you.

答: ~ is used to represent the home directory (on unix based systems). When on windows the equivalent would be C:\Users\username\.gradle dir. Of course username would have to be changed for your username. This is where it is on my computer.

ContentLicense: CC BY-SA 4.0

Title: Where is "~/.gradle" folder in Windows?

Body:
I was following the React Native document to create a signed APK.
Source

Setting up Gradle variables

Place the my-release-key.keystore file under the android/app directory
in your project folder.

Edit the file ~/.gradle/gradle.properties and add the following

MYAPP_RELEASE_STORE_FILE=my-release-key.keystore
MYAPP_RELEASE_KEY_ALIAS=my-key-alias
MYAPP_RELEASE_STORE_PASSWORD=*****
MYAPP_RELEASE_KEY_PASSWORD=*****

Originally, I thought ~/.gradle is <project folder>/android/.gradle. However, it is not... In the command line, I ran the cd ~/.gradle/ command and it says:

The system cannot find the path specified.

Would you please let me know where is this folder (in Windows), so I can create gradle.properties? Thank you.


问:
Unity3D C# - Syntax - GetComponent<Rigidbody>()
I've been trying to learn Unity and pretty soon in the tutorials I've found this:

```<code>private Rigidbody rb;

void Start ()
{
    rb = GetComponent<Rigidbody>();
}
</code>```

I'm not knowledgeable with C# syntax so what I really would like to understand is this function<object>() syntax.

Thx

答:
This is generics.

https://msdn.microsoft.com/en-us/library/0zk36dx2.aspx

Essentially you're telling the Unity runtime to give you the RigidBody component. It's similar to doing something like

rb = GetComponent(typeof(RigidBody));

Body:
I've been trying to learn Unity and pretty soon in the tutorials I've found this:

private Rigidbody rb;

void Start ()
{
    rb = GetComponent<Rigidbody>();
}

I'm not knowledgeable with C# syntax so what I really would like to understand is this function<object>() syntax.

Thx


问:
Allow user to change layout of web page
I have a web page that allows users to insert form input objects with a label.  When they add a new object I automatically add it to a 2 column table, the left column is the label and the right is the form control.

I want to give the user more control over how the page is layed out.  I was wondering if there are any examples, patterns or suggestions that would help me achieve this. The only example I found is in Liferay, where you can choose different layout templates and then position portlets on that page according to the layouts and ordering.

Update:

I would like to persist the layout they design.

I already have the form itself persisted.  The HTML is not persisted, I generate it on the fly when the form is requested.  I would like a way to also persist the layout of the form as well.

I am not looking for anything too detailed.  Mainly just thoughts and suggestions.

Thank you

答: The easiest and most secure way to do this would be via jQuery or another JavaScript library.  Check out jQuery UI and YUI.  Both feature widgets which allow repositioning, resizing, and other customizations.  It grows more complicated if you want to make the user's changes persistent, however.

Title: Allow user to change layout of web page


问:
How do I get document height using vh units in jQuery?
```<code>$(window).scroll(function() {
   $scrollingDiv.css("display", (($(window).scrollTop() / $(document).height()) > 0.1) ? "block" : "");
});
</code>```

How can I change the unit $(document).height()) > 0.1) to 100vh? I don't have much jQuery experience.

答:
I believe the correct syntax is
$(selector).attr(attribute,value)
So for your specific example $(document).attr('height','100vh')

Here is a link that hopefully helps --> https://www.w3schools.com/jquery/html_attr.asp

Body:
$(window).scroll(function() {
   $scrollingDiv.css("display", (($(window).scrollTop() / $(document).height()) > 0.1) ? "block" : "");
});

How can I change the unit $(document).height()) > 0.1) to 100vh? I don't have much jQuery experience.


问:
Linking fails [ilink32 Error] Fatal: Unable to open file 'TYPES.OBJ'
I have been updating code fomr an old legacy project build using C++ Builder 2010 to compile with C++ Builder 10 Seattle. I have mostly had to change paths, a lot of dupIgnore to TDuplicates::dupIgnore, reimport some components like MSXML and MSMQ etc.

First for a bunch of subprojects that the main project uses in the form of bpl's and dll's and finally the code of the main project compiles.

But... it fails a linking :P

```<code>[ilink32 Error] Fatal: Unable to open file 'TYPES.OBJ'
</code>```

I have tried to find info about potential issues and many mention making sure System is supplied in the Unit Scope under the Delphi Compiler settings. But that is already present for this project. What else could be causing this?

For information. Compiled using "classic" bcc32 compiler for now.

Include Path:

$(BDSINCLUDE)\windows\vcl;$(BDSINCLUDE)\dinkumware;

Library Path:

```<code>$(BDSLIB)\$(PLATFORM)\$(Config);$(BDSLIB)\$(PLATFORM)\Release\psdk;
</code>```

答:
I would follow the advice given by Tim D first. Whenever I start using a newer version of a compiler 90% of of importing old projects is due to me directly including code/header/object files and creating a blank version then copying over afterwards 99% of the time fixes it.

After making sure the data was created fresh, then importing your old data over it, I would check for legacy incompatibility issues. You are on the right path with changing your "lists". I also recommend you make sure that all your code is rewritten for the new compiler in mind. This helps with both code compatibility and streamlining for running the finished project.

Lastly, I would check that all your extra data (files that aren't pure code such as header files) are still recognizable too the compiler currently being used. (Legacy can cause this to be finicky.)

Body:
I have been updating code fomr an old legacy project build using C++ Builder 2010 to compile with C++ Builder 10 Seattle. I have mostly had to change paths, a lot of dupIgnore to TDuplicates::dupIgnore, reimport some components like MSXML and MSMQ etc.

First for a bunch of subprojects that the main project uses in the form of bpl's and dll's and finally the code of the main project compiles.

But... it fails a linking :P

[ilink32 Error] Fatal: Unable to open file 'TYPES.OBJ'

I have tried to find info about potential issues and many mention making sure System is supplied in the Unit Scope under the Delphi Compiler settings. But that is already present for this project. What else could be causing this?

For information. Compiled using "classic" bcc32 compiler for now.

Include Path:

$(BDSINCLUDE)\windows\vcl;$(BDSINCLUDE)\dinkumware;

Library Path:

$(BDSLIB)\$(PLATFORM)\$(Config);$(BDSLIB)\$(PLATFORM)\Release\psdk;


问:
Removing elements from a string within a list
I have a list consisting of dictionaries converted to string, each slot in that list is as follows
'{< Candidate: Candidate1 >: 1.5}'

I want to remove all non-alphanumeric and ':' elements, so they look like this:

'Candidate: Candidate1: 1.5'

I tried to do the following:

```<code>for l in list:
        for l2 in l:
                if l2.isalnum()==False or l2==':':
                        l2.replace("")
</code>```

But I did not get the desired result, how can I do this?

Thanks in advance

Body:
I have a list consisting of dictionaries converted to string, each slot in that list is as follows
'{< Candidate: Candidate1 >: 1.5}'

I want to remove all non-alphanumeric and ':' elements, so they look like this:

'Candidate: Candidate1: 1.5'

I tried to do the following:

for l in list:
        for l2 in l:
                if l2.isalnum()==False or l2==':':
                        l2.replace("")

But I did not get the desired result, how can I do this?

Thanks in advance

Body:
Given:

>>> li=[ '{: 1.5}',  '{: 1.6}']

You can use a element by element regex:

>>> [re.sub(r'[^\w\d.]+',"",e) for e in li]
['1.5', '1.6']

Edit

If you want to keep the : you can do:

>>> [re.sub(r'[^\w\d.:]+',"",e) for e in li]
[':1.5', ':1.6']


问:
How to use wit.ai to return one single result (python)
I have been recently fooling around with wit.ai in python. I have been able to make .interactive() work when communicating with the bot, but I really want .message() to work, since I want to send one message at a time. I saw online that you can do it like this:

```<code>client = Wit(access_token=token, actions=actions)
resp = client.message('hello')
print(resp)
</code>```

However, the response is not what I want and is actually just the message being sent to the server. Like this:

```<code>{'msg_id': '516ffc83-f008-446a-979a-2da2207164a1', '_text': 'hello', 'entities': {'intent': [{'confidence': 0.9646306495169545, 'value': 'greeting'}]}}
</code>```

I would like to fetch the callback from the message and print it.
Thanks!

答:
From the official documentation and my personal experience, that response is not the message being sent to the server. It is indeed the response to your query from the server.

Check - https://wit.ai/docs/http/20160330#get-intent-via-text-link

The "intent" map in the "entities" object holds the measure of confidence (i.e 96.4%) with which it predicts the query "hello" to be a "greeting". Now, if you want to parse this JSON response, you can do this -

```<code>callback = resp['_text']['entities']['intent']['value']
print(callback)
</code>```

Body:
I have been recently fooling around with wit.ai in python. I have been able to make .interactive() work when communicating with the bot, but I really want .message() to work, since I want to send one message at a time. I saw online that you can do it like this:

client = Wit(access_token=token, actions=actions)
resp = client.message('hello')
print(resp)

However, the response is not what I want and is actually just the message being sent to the server. Like this:

{'msg_id': '516ffc83-f008-446a-979a-2da2207164a1', '_text': 'hello', 'entities': {'intent': [{'confidence': 0.9646306495169545, 'value': 'greeting'}]}}

I would like to fetch the callback from the message and print it.
Thanks!

Body:
From the official documentation and my personal experience, that response is not the message being sent to the server. It is indeed the response to your query from the server.

Check - https://wit.ai/docs/http/20160330#get-intent-via-text-link

The "intent" map in the "entities" object holds the measure of confidence (i.e 96.4%) with which it predicts the query "hello" to be a "greeting". Now, if you want to parse this JSON response, you can do this -

callback = resp['_text']['entities']['intent']['value']
print(callback)


问:
Not understanding this recursive python code
I recently was trying to figure out the answer to a question on code fights.  I eventually found a solution that works from this website:
https://statyang.wordpresults.com/python-practice-51-combination-sum/

However, no matter how many print statements or debugging I do, I can't seem to figure out how

```<code>target
</code>```

is changing value somewhere in the

```<code>if target < candidates[i]:
    return
</code>```

The whole purpose of the program is to have an input of an array, and including duplicates, output the different combinations of sums that add up to the target.

here is the code with all of the debugging print statements

```<code>class Solution2:
# @param candidates, a list of integers
# @param target, integer
# @return a list of lists of integers
def combinationSum(self, candidates, target):
    candidates.sort()
    result=[]
    self.DFS(candidates,target,0,result,[])
    return result

def DFS(self,candidates,target,start,result,intermedia):
    print "===== inside DFS method ============="
    print "candidates {0}".format(candidates)
    print "target: {0}".format(target)
    print "start {0}".format(start)
    print "result {0}".format(result)
    print "intermedia {0}".format(intermedia)
    if target==0:
        print ">>> inside if target==0"
        print "target==0 appending {0}".format(intermedia)
        result.append(intermedia)
        return
    for i in range(start,len(candidates)):
        print "=====inside for loop ========: i= {0}".format(i)
        print "target={0}, cadidates[i]={1}".format(target, candidates[i])
        if target<candidates[i]:
            print ">>> target < candidates[i] {0} < {1}".format(target, candidates[i])
            print "i before return {0}".format(i)
            return
        print "i after return {0}".format(i)
        print "======== preparing for recursion ========:"
        print "candidates {0}".format(candidates)
        print "new target: target - candidates[i]: {0} - {1} = {2}".format(target, candidates[i], target-candidates[i])
        print "new start: {0}".format(i)
        print "result {0}".format(result)
        print "new intermedia: intermedia + candidates[i]: {0} + {1} = {2}".format(intermedia, [candidates[i]], intermedia + [candidates[i]])
        print "i= {0} start= {1}".format(i, start)
        print "about to call recursion again!"
        self.DFS(candidates,target-candidates[i],i,result,intermedia+[candidates[i]])

test2=Solution2()
print(test2.combinationSum([2, 4, 6, 8], 8))
</code>```

here is the ending output

```<code>[[2, 2, 2, 2], [2, 2, 4], [2, 6], [4, 4], [8]]
</code>```

as you can see, each of these pairs add up to 8

so really confused as to how the value for target seems to change somewhere inside of the loop and always to a positive number even though it is always inserting

```<code> target - candidates[i]
</code>```

inside of the recursive function

答:
The recursion starts with this call, self.DFS(candidates,target,0,result,[]), where the parameter, intermedia, is an empty array.

intermedia then accumulates another candidate whenever target is still greater than or equal to candidate[i]. The accumulation happens at the end of this line: self.DFS(candidates,target-candidates[i],i,result,intermedia+[candidates[i]]).

Meanwhile, target is decreased for this particular call to represent that we've used the candidate in trying to reach the target number. So that when target==0, we're ready to result.append(intermedia), which is this particular accumulation of candidates. A full new set of recursive calls with different candidates is generated in each call by the for loop.

Body:
I recently was trying to figure out the answer to a question on code fights.  I eventually found a solution that works from this website:
https://statyang.wordpresults.com/python-practice-51-combination-sum/

However, no matter how many print statements or debugging I do, I can't seem to figure out how

target

is changing value somewhere in the

if target < candidates[i]:
    return

The whole purpose of the program is to have an input of an array, and including duplicates, output the different combinations of sums that add up to the target.

here is the code with all of the debugging print statements

class Solution2:
# @param candidates, a list of integers
# @param target, integer
# @return a list of lists of integers
def combinationSum(self, candidates, target):
    candidates.sort()
    result=[]
    self.DFS(candidates,target,0,result,[])
    return result

def DFS(self,candidates,target,start,result,intermedia):
    print "===== inside DFS method ============="
    print "candidates {0}".format(candidates)
    print "target: {0}".format(target)
    print "start {0}".format(start)
    print "result {0}".format(result)
    print "intermedia {0}".format(intermedia)
    if target==0:
        print ">>> inside if target==0"
        print "target==0 appending {0}".format(intermedia)
        result.append(intermedia)
        return
    for i in range(start,len(candidates)):
        print "=====inside for loop ========: i= {0}".format(i)
        print "target={0}, cadidates[i]={1}".format(target, candidates[i])
        if target<candidates[i]:
            print ">>> target < candidates[i] {0} < {1}".format(target, candidates[i])
            print "i before return {0}".format(i)
            return
        print "i after return {0}".format(i)
        print "======== preparing for recursion ========:"
        print "candidates {0}".format(candidates)
        print "new target: target - candidates[i]: {0} - {1} = {2}".format(target, candidates[i], target-candidates[i])
        print "new start: {0}".format(i)
        print "result {0}".format(result)
        print "new intermedia: intermedia + candidates[i]: {0} + {1} = {2}".format(intermedia, [candidates[i]], intermedia + [candidates[i]])
        print "i= {0} start= {1}".format(i, start)
        print "about to call recursion again!"
        self.DFS(candidates,target-candidates[i],i,result,intermedia+[candidates[i]])

test2=Solution2()
print(test2.combinationSum([2, 4, 6, 8], 8))

here is the ending output

[[2, 2, 2, 2], [2, 2, 4], [2, 6], [4, 4], [8]]

as you can see, each of these pairs add up to 8

so really confused as to how the value for target seems to change somewhere inside of the loop and always to a positive number even though it is always inserting

 target - candidates[i]

inside of the recursive function


问:
adb remount permission denied, but able to access super user in shell -- android
so, i'm trying to push some files to /system on android device (zte)
I've rooted, connected with ADB,

adb remount -> I get permission denied
adb shell su -> I'm able to access shell and create folders etc and edit filesystem

(but in shell I can't copy a file from my computer to device)

Any help please

答:
emulator -writable-system

For people using an Emulator: Another possibility is that you need to start the emulator with -writable-system. That was the only thing that worked for me when using the standard emulator packaged with android studio with a 4.1 image. Check here: https://stackoverflow.com/a/41332316/4962858


问:
Regex for managing escaped characters for items like string literals
I would like to be able to match a string literal with the option of escaped quotations.
For instance, I'd like to be able to search "this is a 'test with escaped\' values' ok" and have it properly recognize the backslash as an escape character. I've tried solutions like the following:

```<code>import re
regexc = re.compile(r"\'(.*?)(?<!\\)\'")
match = regexc.search(r""" Example: 'Foo \' Bar'  End. """)
print match.groups()
# I want ("Foo \' Bar") to be printed above
</code>```

After looking at this, there is a simple problem that the escape character being used, "\", can't be escaped itself. I can't figure out how to do that. I wanted a solution like the following, but negative lookbehind assertions need to be fixed length:

```<code># ...
re.compile(r"\'(.*?)(?<!\\(\\\\)*)\'")
# ...
</code>```

Any regex gurus able to tackle this problem? Thanks.

答:
Douglas Leeder's pattern ((?:^|[^\\])'(([^\\']|\\'|\\\\)*)') will fail to match "test 'test \x3F test' test" and "test \\'test' test". (String containing an escape other than quote and backslash, and string preceded by an escaped backslash.)

cletus' pattern ((?<!\\)'((?:\\'|[^'])*)(?<!\\)') will fail to match "test 'test\\' test". (String ending with an escaped backslash.)

My proposal for single-quoted strings is this:

```<code>(?<!\\)(?:\\\\)*'((?:\\.|[^\\'])*)'
</code>```

For both single-quoted or double-quoted stings, you could use this:

```<code>(?<!\\)(?:\\\\)*("|')((?:\\.|(?!\1)[^\\])*)\1
</code>```

Test run using Python:

```<code>Doublas Leeder´s test cases:
"''" matched successfully: ""
" Example: 'Foo \' Bar'  End. " matched successfully: "Foo \' Bar"
"'\''" matched successfully: "\'"
" Example2: 'Foo \\' End. " matched successfully: "Foo \\"
"not matched\''a'" matched successfully: "a"
"\''a'" matched successfully: "a"

cletus´ test cases:
"'testing 123'" matched successfully: "testing 123"
"'testing 123\\'" matched successfully: "testing 123\\"
"'testing 123" didn´t match, as exected.
"blah 'testing 123" didn´t match, as exected.
"blah 'testing 123'" matched successfully: "testing 123"
"blah 'testing 123' foo" matched successfully: "testing 123"
"this 'is a \' test'" matched successfully: "is a \' test"
"another \' test 'testing \' 123' \' blah" matched successfully: "testing \' 123"

MizardX´s test cases:
"test 'test \x3F test' test" matched successfully: "test \x3F test"
"test \\'test' test" matched successfully: "test"
"test 'test\\' test" matched successfully: "test\\"
</code>```

OwnerDisplayName: Evan Fosmark

Body:
I would like to be able to match a string literal with the option of escaped quotations.
For instance, I'd like to be able to search "this is a 'test with escaped\' values' ok" and have it properly recognize the backslash as an escape character. I've tried solutions like the following:

import re
regexc = re.compile(r"\'(.*?)(?<!\\)\'")
match = regexc.search(r""" Example: 'Foo \' Bar'  End. """)
print match.groups()
# I want ("Foo \' Bar") to be printed above

After looking at this, there is a simple problem that the escape character being used, "\", can't be escaped itself. I can't figure out how to do that. I wanted a solution like the following, but negative lookbehind assertions need to be fixed length:

# ...
re.compile(r"\'(.*?)(?<!\\(\\\\)*)\'")
# ...

Any regex gurus able to tackle this problem? Thanks.

Body:
Douglas Leeder's pattern ((?:^|[^\\])'(([^\\']|\\'|\\\\)*)') will fail to match "test 'test \x3F test' test" and "test \\'test' test". (String containing an escape other than quote and backslash, and string preceded by an escaped backslash.)

cletus' pattern ((?<!\\)'((?:\\'|[^'])*)(?<!\\)') will fail to match "test 'test\\' test". (String ending with an escaped backslash.)

My proposal for single-quoted strings is this:

(?<!\\)(?:\\\\)*'((?:\\.|[^\\'])*)'

For both single-quoted or double-quoted stings, you could use this:

(?<!\\)(?:\\\\)*("|')((?:\\.|(?!\1)[^\\])*)\1

Test run using Python:

Doublas Leeder´s test cases:
"''" matched successfully: ""
" Example: 'Foo \' Bar'  End. " matched successfully: "Foo \' Bar"
"'\''" matched successfully: "\'"
" Example2: 'Foo \\' End. " matched successfully: "Foo \\"
"not matched\''a'" matched successfully: "a"
"\''a'" matched successfully: "a"

cletus´ test cases:
"'testing 123'" matched successfully: "testing 123"
"'testing 123\\'" matched successfully: "testing 123\\"
"'testing 123" didn´t match, as exected.
"blah 'testing 123" didn´t match, as exected.
"blah 'testing 123'" matched successfully: "testing 123"
"blah 'testing 123' foo" matched successfully: "testing 123"
"this 'is a \' test'" matched successfully: "is a \' test"
"another \' test 'testing \' 123' \' blah" matched successfully: "testing \' 123"

MizardX´s test cases:
"test 'test \x3F test' test" matched successfully: "test \x3F test"
"test \\'test' test" matched successfully: "test"
"test 'test\\' test" matched successfully: "test\\"

OwnerDisplayName: MizardX

LastEditorDisplayName: MizardX


问:
How to import AppDelegate.h file in Pod project ViewController?
I am new to the POD project.
I want to update the pod project viewControllers,for that I need to access the AppDelegate class in Pod Project.

I have tried to update the Pod configuration file to access the AppDelegate but not able to get success.

答:
You really don't want to create a circular dependency between your app and the pod. The recommended way to do this would be to define a protocol in the pod and make your AppDelegate implement that protocol. </p>

```<code>@protocol PodArrayProvider
    - (NSArray *)arrayToAccess:
@end

// in AppDelegate.m
#import <Pod/Pod.h>

@extension AppDelegate () <PodArrayProvider>
@end

@implementation AppDelegate
- (NSArray *)arrayToAccess
{
    return self.realArray;
}
@end

// then in your pod, you can do:
id<PodArrayProvider> arrayProvider = (id<PodArrayProvider>)[[UIApplication sharedApplication] delegate];
NSAssert([arrayProvider conformsTo:@protocol(PodArrayProvider)], @"bad app delegate!");
NSArray *things = [arrayProvider arrayToAccess];
</code>```

<p>Something like the structure above should work, but I would urge you to rethink this architecture. The pod is a dependency of the app and shouldn't know anything about the app. The app should be telling the pod everything it needs to know. </p>

Body:
You really don't want to create a circular dependency between your app and the pod. The recommended way to do this would be to define a protocol in the pod and make your AppDelegate implement that protocol.

@protocol PodArrayProvider
    - (NSArray *)arrayToAccess:
@end

// in AppDelegate.m
#import <Pod/Pod.h>

@extension AppDelegate () <PodArrayProvider>
@end

@implementation AppDelegate
- (NSArray *)arrayToAccess
{
    return self.realArray;
}
@end

// then in your pod, you can do:
id<PodArrayProvider> arrayProvider = (id<PodArrayProvider>)[[UIApplication sharedApplication] delegate];
NSAssert([arrayProvider conformsTo:@protocol(PodArrayProvider)], @"bad app delegate!");
NSArray *things = [arrayProvider arrayToAccess];

Something like the structure above should work, but I would urge you to rethink this architecture. The pod is a dependency of the app and shouldn't know anything about the app. The app should be telling the pod everything it needs to know.


问:
Return user id from onelogin
How do I get the return user id from the OneLogin SAML return values? I have looked at the consumer module but do not see any return values.</p>

答:
From the Saml response you can get the nameid.

Depending on how the Identity Provider was configured you would get an email or whatever else was decided. Usually is an email. The you can check against your db after the proper validation.

In Ruby and using OneLogin toolkit you instantiate:

```<code>OneLogin::RubySaml::Response
</code>```

Title: Return user id from onelogin

Body:
From the Saml response you can get the nameid.

Depending on how the Identity Provider was configured you would get an email or whatever else was decided. Usually is an email. The you can check against your db after the proper validation.

In Ruby and using OneLogin toolkit you instantiate:

OneLogin::RubySaml::Response


问:
DbUpdateException when removing and saving changes in EF
I'm trying to delete a record in the database by simply using db.'table'.remove('object') but when calling db.SaveChanges() exception is thrown.

'An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code'

My deleting method in controller

```<code>public ActionResult Delete(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Customer customer = db.Customers.Find(id);
    if (customer == null)
    {
        return HttpNotFound();
    }
    db.Customers.Remove(customer);
    db.SaveChanges();

    return RedirectToAction("Index");
}
</code>```

Model:

```<code>public class Customer
{
    [Key, ForeignKey("User")]
    public int UserId { get; set; }
    public string Email { get; set; }
    public virtual CreditCard CreditCard { get; set; }
    public virtual ShoppingCart ShoppingCart { get; set; }
    public virtual List<Enquiry> Enquiries { get; set; }
    public virtual List<Order> Orders { get; set; }
    public virtual User User { get; set; }
}
public class User
{
    [Key]
    public int Id { set; get; }
    public string Username { set; get; }
    public string Password { set; get; }
    public string FirstName { set; get; }
    public string Surname { set; get; }
    public virtual UserRole UserRole { get; set; }
}

public class ShoppingCart
    {
        [Key, ForeignKey("Customer")]
        public int Id { get; set; }
        public virtual List<CartItem> CartItems { get; set; }
        public virtual Customer Customer { get; set; }
    }
</code>```

Part of the exception:

```<code>A DbUpdateException was caught while saving changes. Type: Customer_8D9A6B7F7D247C9CB9F95E830039791E299E94FC91841FD33610DD1804AEF739 was part of the problem.
</code>```

Full exception:

```<code>System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.ShoppingCarts_dbo.Customers_Id". The conflict occurred in database "MVC_COMP1562.Models.SchemaDBContext", table "dbo.ShoppingCarts", column 'Id'.
The statement has been terminated.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
   at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
   --- End of inner exception stack trace ---
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
   at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
   at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   --- End of inner exception stack trace ---
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at System.Data.Entity.DbContext.SaveChanges()
   at MVC_COMP1562.Controllers.CustomersController.Delete(Nullable`1 id) in C:\Users\kacpe\Documents\Visual Studio 2015\Projects\MVC_COMP1562\MVC_COMP1562\Controllers\CustomersController.cs:line 165
</code>```

答:
It seems you have another Table called dbo.ShoppingCarts about a Shopping Cart, which have one or more rows related to the Customer you are trying to delete.

So first you must delete the rows related to that customer an then you can delete the customer. That happens because the Customer id is foreign key in that other table.

If that is no exactly the case, please add your ShoppingCarts class to the question.

Body:
I'm trying to delete a record in the database by simply using db.'table'.remove('object') but when calling db.SaveChanges() exception is thrown.

'An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code'

My deleting method in controller

public ActionResult Delete(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Customer customer = db.Customers.Find(id);
    if (customer == null)
    {
        return HttpNotFound();
    }
    db.Customers.Remove(customer);
    db.SaveChanges();

    return RedirectToAction("Index");
}

Model:

public class Customer
{
    [Key, ForeignKey("User")]
    public int UserId { get; set; }
    public string Email { get; set; }
    public virtual CreditCard CreditCard { get; set; }
    public virtual ShoppingCart ShoppingCart { get; set; }
    public virtual List<Enquiry> Enquiries { get; set; }
    public virtual List<Order> Orders { get; set; }
    public virtual User User { get; set; }
}
public class User
{
    [Key]
    public int Id { set; get; }
    public string Username { set; get; }
    public string Password { set; get; }
    public string FirstName { set; get; }
    public string Surname { set; get; }
    public virtual UserRole UserRole { get; set; }
}

public class ShoppingCart
    {
        [Key, ForeignKey("Customer")]
        public int Id { get; set; }
        public virtual List<CartItem> CartItems { get; set; }
        public virtual Customer Customer { get; set; }
    }

Part of the exception:

A DbUpdateException was caught while saving changes. Type: Customer_8D9A6B7F7D247C9CB9F95E830039791E299E94FC91841FD33610DD1804AEF739 was part of the problem.

Full exception:

System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.ShoppingCarts_dbo.Customers_Id". The conflict occurred in database "MVC_COMP1562.Models.SchemaDBContext", table "dbo.ShoppingCarts", column 'Id'.
The statement has been terminated.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
   at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
   --- End of inner exception stack trace ---
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
   at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
   at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   --- End of inner exception stack trace ---
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at System.Data.Entity.DbContext.SaveChanges()
   at MVC_COMP1562.Controllers.CustomersController.Delete(Nullable`1 id) in C:\Users\kacpe\Documents\Visual Studio 2015\Projects\MVC_COMP1562\MVC_COMP1562\Controllers\CustomersController.cs:line 165


问:
What is the difference between these three ways to initialise static variables?
Those 2 syntaxes work. What is the difference between them?

```<code>class MyClass
{
  const static int myInt1_ {20};
  const static int myInt2_ = 20;
}
</code>```

Also, why is it not possible to do const static int myInt3_ (20)?

答:
```<code>const static int myInt1_ {20};
</code>```

This is the newer uniform initialization syntax that was introduced in the C++11 revision. Prior to C++11 only

```<code>const static int myInt1_ = 20;
</code>```

would be valid. Uniform initialization syntax was introduced to resolve some parsing ambiguities in more complex initialization constructs. In your case, with simple static class member initialization, both initialization syntaxes are valid and produce identical results.

Body:
Those 2 syntaxes work. What is the difference between them?

class MyClass
{
  const static int myInt1_ {20};
  const static int myInt2_ = 20;
}

Also, why is it not possible to do const static int myInt3_ (20)?

Body:
const static int myInt1_ {20};

This is the newer uniform initialization syntax that was introduced in the C++11 revision. Prior to C++11 only

const static int myInt1_ = 20;

would be valid. Uniform initialization syntax was introduced to resolve some parsing ambiguities in more complex initialization constructs. In your case, with simple static class member initialization, both initialization syntaxes are valid and produce identical results.


问:
How can I make the ordering of constructors more efficient?
I am currently working on a program that has to have every possible example of calculations. I made a class for number, difference, product, modulus, quotient, and sum. I am doing something like this

```<code>Difference(Number first_number,Number second_number){
    s1 = first_number + second_number;
}
Difference(Number first_number, Product first_difference){
    s1 = first_number + first_difference
}
Difference(Product first_difference, Number first_number){
    s1 = first_product + first_number;
}
Difference(Product first_difference, Product second_difference){
    s1 = first_difference + second_difference;
}
Difference(Number first_number, Quotient first_difference){
    s1 = first_number + first_difference;
}
Difference(Quotient first_difference, Number first_number){
    s1 = first_difference + first_number;
}
Difference(Quotient first_difference, Quotient second_difference){
    s1 = first_difference + second_difference;
}
Difference(Number first_number, Difference first_difference){
    s1 = first_number + first_difference;
}
Difference(Difference first_difference, Number first_number){
    s1 = first_number + first_difference;
}
Difference(Difference first_difference, Difference second_difference){
    s1 = first_difference + second_difference;
}
Difference(Number first_number, Sum first_Difference){
    s1 = first_number + first_Difference;
}
Difference(Sum first_Difference, Number first_number){
    s1 = first_Difference + first_number;
}
Difference(Sum first_Difference, Sum second_Difference){
    s1 = first_Difference + second_Difference;
}
Difference(Number first_number, Modulus first_modulus ){
    s1 = first_number + first_modulus;
}
Difference(Modulus first_modulus, Number first_number){
    s1 = first_number + first_ modulus;
}
Difference(Modulus first_modulus, Modulus second_modulus){
    s1 = first_modulus + second_modulus;
}
Difference(Sum first_Difference, Product first_difference){
    s1 = first_Difference + first_difference;
}
Difference(Product first_difference, Sum first_Difference){
    s1 = first_difference + first_Difference;
}
Difference(Sum first_Difference, Quotient first_difference){
    s1 = first_Difference + first_difference;
}
Difference(Quotient first_difference, Sum first_Difference){
    s1 = first_difference + first_Difference;
}
Difference(Sum first_Difference, Difference first_difference){
    s1 = first_Difference + first_difference;
}
Difference(Difference first_difference, Sum first_Difference){
    s1 = first_Difference + first_difference;
}
Difference(Sum first_Difference, Modulus first_modulus ){
    s1 = first_Difference + first_modulus;
}
Difference(Modulus first_modulus, Sum first_Difference){
    s1 = first_Difference + first_modulus;
}
Difference(Difference first_difference, Quotient first_difference){
    s1 = first_difference + first_difference;
}
Difference(Quotient first_difference, Difference first_difference){
    s1 = first_difference + first_difference;
}
Difference(Product first_difference, Quotient first_difference){
    s1 = first_difference + first_difference;
}
Difference(Quotient first_difference, Product first_difference){
    s1 = first_difference + first_difference;
}
Difference(Quotient first_difference, Modulus first_modulus){
    s1 = first_difference + first_modulus;
}
Difference(Modulus first_modulus, Quotient first_difference){
    s1 = first_difference + first_modulus;
}
Difference(Difference first_difference, Quotient first_difference){
    s1 = first_difference + first_difference;
}
Difference(Quotient first_difference, Difference first_difference){
    s1 = first_difference + first_difference;
}
Difference(Difference first_difference, Modulus first_modulus){
    s1 = first_difference + first_modulus;
}
Difference(Modulus first_modulus, Difference first_difference){
    s1 = first_modulus + first_difference;
}
Difference(Difference first_difference, Modulus first_modulus){
    s1 = first_difference + first_modulus;
}
Difference(Modulus first_modulus, Difference first_difference){
    s1 = first_difference + first_modulus;
}
</code>```

to make sure I have every possible combination of ways for my main class. Is there any way that I can make this more efficient? I am tired of having to write this over and over again.

答:
Oh what I did was create a super class Expression and then could do</p>

```<code>public class Sum extends Expression{
private Expression lhs;
private Expression rhs;

Difference(Expression e1,  Expression e2) {
            lhs = e1;
            rhs = e2;
}
}
</code>```

Body:
I am currently working on a program that has to have every possible example of calculations. I made a class for number, difference, product, modulus, quotient, and sum. I am doing something like this

Difference(Number first_number,Number second_number){
    s1 = first_number + second_number;
}
Difference(Number first_number, Product first_difference){
    s1 = first_number + first_difference
}
Difference(Product first_difference, Number first_number){
    s1 = first_product + first_number;
}
Difference(Product first_difference, Product second_difference){
    s1 = first_difference + second_difference;
}
Difference(Number first_number, Quotient first_difference){
    s1 = first_number + first_difference;
}
Difference(Quotient first_difference, Number first_number){
    s1 = first_difference + first_number;
}
Difference(Quotient first_difference, Quotient second_difference){
    s1 = first_difference + second_difference;
}
Difference(Number first_number, Difference first_difference){
    s1 = first_number + first_difference;
}
Difference(Difference first_difference, Number first_number){
    s1 = first_number + first_difference;
}
Difference(Difference first_difference, Difference second_difference){
    s1 = first_difference + second_difference;
}
Difference(Number first_number, Sum first_Difference){
    s1 = first_number + first_Difference;
}
Difference(Sum first_Difference, Number first_number){
    s1 = first_Difference + first_number;
}
Difference(Sum first_Difference, Sum second_Difference){
    s1 = first_Difference + second_Difference;
}
Difference(Number first_number, Modulus first_modulus ){
    s1 = first_number + first_modulus;
}
Difference(Modulus first_modulus, Number first_number){
    s1 = first_number + first_ modulus;
}
Difference(Modulus first_modulus, Modulus second_modulus){
    s1 = first_modulus + second_modulus;
}
Difference(Sum first_Difference, Product first_difference){
    s1 = first_Difference + first_difference;
}
Difference(Product first_difference, Sum first_Difference){
    s1 = first_difference + first_Difference;
}
Difference(Sum first_Difference, Quotient first_difference){
    s1 = first_Difference + first_difference;
}
Difference(Quotient first_difference, Sum first_Difference){
    s1 = first_difference + first_Difference;
}
Difference(Sum first_Difference, Difference first_difference){
    s1 = first_Difference + first_difference;
}
Difference(Difference first_difference, Sum first_Difference){
    s1 = first_Difference + first_difference;
}
Difference(Sum first_Difference, Modulus first_modulus ){
    s1 = first_Difference + first_modulus;
}
Difference(Modulus first_modulus, Sum first_Difference){
    s1 = first_Difference + first_modulus;
}
Difference(Difference first_difference, Quotient first_difference){
    s1 = first_difference + first_difference;
}
Difference(Quotient first_difference, Difference first_difference){
    s1 = first_difference + first_difference;
}
Difference(Product first_difference, Quotient first_difference){
    s1 = first_difference + first_difference;
}
Difference(Quotient first_difference, Product first_difference){
    s1 = first_difference + first_difference;
}
Difference(Quotient first_difference, Modulus first_modulus){
    s1 = first_difference + first_modulus;
}
Difference(Modulus first_modulus, Quotient first_difference){
    s1 = first_difference + first_modulus;
}
Difference(Difference first_difference, Quotient first_difference){
    s1 = first_difference + first_difference;
}
Difference(Quotient first_difference, Difference first_difference){
    s1 = first_difference + first_difference;
}
Difference(Difference first_difference, Modulus first_modulus){
    s1 = first_difference + first_modulus;
}
Difference(Modulus first_modulus, Difference first_difference){
    s1 = first_modulus + first_difference;
}
Difference(Difference first_difference, Modulus first_modulus){
    s1 = first_difference + first_modulus;
}
Difference(Modulus first_modulus, Difference first_difference){
    s1 = first_difference + first_modulus;
}

to make sure I have every possible combination of ways for my main class. Is there any way that I can make this more efficient? I am tired of having to write this over and over again.

Body:
Oh what I did was create a super class Expression and then could do

public class Sum extends Expression{
private Expression lhs;
private Expression rhs;

Difference(Expression e1,  Expression e2) {
            lhs = e1;
            rhs = e2;
}
}


问:
Creating a column variable taking the mean of a variable conditional on two other variables
I have a data frame that shows the mean 'dwdime' for each of the given conditions:

```<code>DIMExCand_means = DIMExCand.groupby(['cycle', 'coded_state', 'party.orig', 'comtype']).mean()
</code>```

I have created a pivot table from DIMExCand_means with the following command and output:

```<code>DIMExCand_master = pd.pivot_table(DIMExCand_means,index=["Cycle","State"])
</code>```

However, some data gets lost in the process. I would like to add columns to the 'DIMExCand_master' dataframe that includes the mean 'dwdime' score given each possible combination of 'party.orig' and 'comptype', as this will allow me to have one entry per 'cycle'-'coded_state'.

答:
Thanks!

I ended up going with:

DIMExCand_dime = pd.pivot_table(DIMExCand, values = 'dwdime', index ["Cycle","State"], columns='ID', aggfunc=np.mean)

Body:
I have a data frame that shows the mean 'dwdime' for each of the given conditions:

DIMExCand_means = DIMExCand.groupby(['cycle', 'coded_state', 'party.orig', 'comtype']).mean()

I have created a pivot table from DIMExCand_means with the following command and output:

DIMExCand_master = pd.pivot_table(DIMExCand_means,index=["Cycle","State"])

However, some data gets lost in the process. I would like to add columns to the 'DIMExCand_master' dataframe that includes the mean 'dwdime' score given each possible combination of 'party.orig' and 'comptype', as this will allow me to have one entry per 'cycle'-'coded_state'.


问:
How do I strip a file extension from a string in C?
How do I strip a file extension from a string in C?

For example,

If I have the filenames with the file extensions

hello.txt

hello.c

hello.java

should all result in just the filename without the extension as

hello

the length of the file extension shouldn't matter.

the function should also be portable and not system dependent.

I know how to get the file extension using strchr or strrchr. I've done this in Bash and in Python, but I've never had to do this in C.

Note: This is for a personal exercise to help strengthen my understanding of the C programming language.

答:
There could be many ways of doing it. One way could be replace the first dot with a null character (\0).

```<code>char [] filename = "Hello.java";

for(int i=0;i<strlen(filename);i++) {
   if(filename[i] == '.') {
       filename[i]='\0';
       break;
   }
}
</code>```

Body:
There could be many ways of doing it. One way could be replace the first dot with a null character (\0).

char [] filename = "Hello.java";

for(int i=0;i<strlen(filename);i++) {
   if(filename[i] == '.') {
       filename[i]='\0';
       break;
   }
}


问:
How to make a bank program using def functions, returns and if elif else?
This is the program I wrote, but I can't make a bank program that uses def functions like def withdrawl ( current_amount,  withdrawl_amount ). and uses if,  elif, and else for the option list. Please help.

```<code>balance = 2000
rt = 0.01
years = 0

while True:
 print('===============================')
 print(' Welcome to STEVENS UNIVERSAL BANK ')

 print('Please Choose an Option')
 print('Option 1: Withdrawl')
 print('Option 2: Deposit')
 print('Option 3: Check_Balance')
 print('Option 4: Balance with Updated Interest')
 print('Option 5: Exit')
 print('===============================')

 option = int(input('Choose an Option:'))
 years = years + 1

 if option == 1:
  withdrawl = int(input('How much do you want to Withdrawl?:'))
  balance = balance - withdrawl
  print (' New Balance :', balance)
 elif option == 2:
  deposit = int(input('How much do you want to Deposit?:'))
  balance = balance + deposit
  print (' New Balance:', balance)
 elif option == 3:
  print('Balance:', balance)
 elif option == 4:
  balance = balance * ( 1 + ( 0.0001 * years ))
  print (' Updated Balance', balance)
 elif option == 5:
  print (' Thank you for using THE STEVENS UNIVERSAL BANK ')
  exit()
 else:
  print('Invalid Input')
</code>```

答:
You are using elif and else already. It looks like you do understand, mathematically, how to process the withdrawal, as well.

The Python 3 docs explain the syntax of how to declare and call a function
in the section 4.6. Defining Functions.

```<code>def fib(n):    # write Fibonacci series up to n
    """Print a Fibonacci series up to n."""
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()

# Now call the function we just defined:
fib(2000)
</code>```

Body:
This is the program I wrote, but I can't make a bank program that uses def functions like def withdrawl ( current_amount,  withdrawl_amount ). and uses if,  elif, and else for the option list. Please help.

balance = 2000
rt = 0.01
years = 0

while True:
 print('===============================')
 print(' Welcome to STEVENS UNIVERSAL BANK ')

 print('Please Choose an Option')
 print('Option 1: Withdrawl')
 print('Option 2: Deposit')
 print('Option 3: Check_Balance')
 print('Option 4: Balance with Updated Interest')
 print('Option 5: Exit')
 print('===============================')

 option = int(input('Choose an Option:'))
 years = years + 1

 if option == 1:
  withdrawl = int(input('How much do you want to Withdrawl?:'))
  balance = balance - withdrawl
  print (' New Balance :', balance)
 elif option == 2:
  deposit = int(input('How much do you want to Deposit?:'))
  balance = balance + deposit
  print (' New Balance:', balance)
 elif option == 3:
  print('Balance:', balance)
 elif option == 4:
  balance = balance * ( 1 + ( 0.0001 * years ))
  print (' Updated Balance', balance)
 elif option == 5:
  print (' Thank you for using THE STEVENS UNIVERSAL BANK ')
  exit()
 else:
  print('Invalid Input')

Body:
You are using elif and else already. It looks like you do understand, mathematically, how to process the withdrawal, as well.

The Python 3 docs explain the syntax of how to declare and call a function
in the section 4.6. Defining Functions.

def fib(n):    # write Fibonacci series up to n
    """Print a Fibonacci series up to n."""
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()

# Now call the function we just defined:
fib(2000)


问:
Sending and proceeding POST request
I have very simple node.js server which has

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

app.post('/savearticles', function (req, res) {
    res.send(req.body);
});
</code>```

and not much more difficult javascript code

```<code>    var xmlHTTP = new XMLHttpRequest();
    xmlHTTP.onreadystatechange = function () {
        if (this.readyState === 4 && this.status === 200) {
            alert(xmlHTTP.responseText);
        }
    }
    xmlHTTP.open('POST', '/savearticles', true);
    xmlHTTP.setRequestHeader('Content-Type', 'application/json');
    xmlHTTP.send('postparameter');
</code>```

It returns undefined (checked by returning (typeof res.body)).  What am I doing wrong?

答:
You are missing the body-parser middleware. Install it and your code should work correctly.</p>

```<code>const express = require('express')
const bodyParser = require('body-parser')
const app = express()

app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())

app.post('/savearticles', (req, res) => {
    res.send(req.body)
})
</code>```

Title: Sending and proceeding POST request

Body:
I have very simple node.js server which has

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

app.post('/savearticles', function (req, res) {
    res.send(req.body);
});

and not much more difficult javascript code

    var xmlHTTP = new XMLHttpRequest();
    xmlHTTP.onreadystatechange = function () {
        if (this.readyState === 4 && this.status === 200) {
            alert(xmlHTTP.responseText);
        }
    }
    xmlHTTP.open('POST', '/savearticles', true);
    xmlHTTP.setRequestHeader('Content-Type', 'application/json');
    xmlHTTP.send('postparameter');

It returns undefined (checked by returning (typeof res.body)).  What am I doing wrong?

Body:
You are missing the body-parser middleware. Install it and your code should work correctly.

const express = require('express')
const bodyParser = require('body-parser')
const app = express()

app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())

app.post('/savearticles', (req, res) => {
    res.send(req.body)
})


问:
Using Locales with Java's toLowerCase() and toUpperCase()
I wanted code to convert all the characters in strings to uppercase or lowercase in Java.

I found a method that goes something like this:

```<code>public static String changelowertoupper()
{
         String str = "CyBeRdRaGoN";
         str=str.toLowerCase(Locale.ENGLISH);
         return str;
}
</code>```

Now I've read that using certain Locales, like Turkish, "returns i (without dot) instead of i (with dot)."

Is it safe to use Locales like UK, US, ENGLISH, etc.? Are there any big differences between them when applied to strings?

Which is the most preferred Locale for Strings?

答:
You can create appropriate locale for your String's language.

For example:

```<code>toUpperCase(new Locale("tr","TR"));
</code>```

will do the trick for Turkish.

Body:
I wanted code to convert all the characters in strings to uppercase or lowercase in Java.

I found a method that goes something like this:

public static String changelowertoupper()
{
         String str = "CyBeRdRaGoN";
         str=str.toLowerCase(Locale.ENGLISH);
         return str;
}

Now I've read that using certain Locales, like Turkish, "returns i (without dot) instead of i (with dot)."

Is it safe to use Locales like UK, US, ENGLISH, etc.? Are there any big differences between them when applied to strings?

Which is the most preferred Locale for Strings?

Body:
You can create appropriate locale for your String's language.

For example:

toUpperCase(new Locale("tr","TR"));

will do the trick for Turkish.


问:
Django selectable don´t drops down autocomplete
i'm using django-selectable and i'm getting nervous :|

models.py

```<code>@python_2_unicode_compatible
class Filing(models.Model):

    company = models.CharField(max_length=60, null=True)
    ticker = models.CharField(max_length=5, null=True)
    number = models.CharField(max_length=15, null=True)
    description = models.CharField(max_length=100,  null=True)
    url = models.CharField(max_length=110, null=True)
    created_date = models.DateTimeField(null=True)

    def __str__(self):
        return self.ticker
</code>```

lookups.py

```<code>from __future__ import unicode_literals
from selectable.base import LookupBase
from selectable.registry import registry
from .models import Filing

class CompanyLookup(LookupBase):

    model = Filing
    search_fields = ('company__icontains', )

registry.register(CompanyLookup)
</code>```

So don't work :( but

other lookups.py

```<code>from __future__ import unicode_literals
from selectable.base import LookupBase
from selectable.registry import registry
from .models import Filing

class CompanyLookup(LookupBase):

    def get_query(self, request, ticker):
        data= Filing.objects.values_list('company',flat=True)
        return [x for x in data if x.startswith(ticker)]

registry.register(CompanyLookup)
</code>```

works, drops down, but only with the attributes of "startswith" and i need "icontains". Also don't work "istarswith", neither "contains":

In my consoles:

```<code>Request URL:http://127.0.0.1:8000/assets/flash/ZeroClipboard.swf?      noCache=1491057317592
Request Method:GET
Status Code:404 Not Found
Remote Address:127.0.0.1:8000
</code>```

and:

```<code> Uncaught ReferenceError: jQuery is not defined
 at jquery.dj.selectable.js?v=0.9.0:390
 (anonymous) @ jquery.dj.selectable.js?v=0.9.0:390

$(document).ready(function () {
    // Patch the django admin JS
    if (typeof(djselectableAdminPatch) === "undefined" || djselectableAdminPatch) {
        djangoAdminPatches();
    }
    // Bind existing widgets on document ready
    if (typeof(djselectableAutoLoad) === "undefined" || djselectableAutoLoad) {
        window.bindSelectables('body');
    }
});
})(jQuery || grp.jQuery);    <------ this is the line 390
</code>```

also i don't understand why because in the view source code the

```<code> <script type="text/javascript"src="/static/javascript/jquery.dj.selectable.js"></script>
</code>```

is loaded correctly

Thank you in advance if you can help me.

答:
Try this:

```<code>def get_query(self, request, ticker):
    return  list(Filing.objects.filter(company__icontains=ticker).values_list('company', flat=True))
</code>```

You want to filter your data in your database. Not in Python. Your database is much faster. When you do [x for x in x] you are returning a list, no a queryset. You can filter your queryset in the database by putting field__icontains=value in the filter method of a queryset.

Body:
i'm using django-selectable and i'm getting nervous :|

models.py

@python_2_unicode_compatible
class Filing(models.Model):

    company = models.CharField(max_length=60, null=True)
    ticker = models.CharField(max_length=5, null=True)
    number = models.CharField(max_length=15, null=True)
    description = models.CharField(max_length=100,  null=True)
    url = models.CharField(max_length=110, null=True)
    created_date = models.DateTimeField(null=True)

    def __str__(self):
        return self.ticker

lookups.py

from __future__ import unicode_literals
from selectable.base import LookupBase
from selectable.registry import registry
from .models import Filing

class CompanyLookup(LookupBase):

    model = Filing
    search_fields = ('company__icontains', )

registry.register(CompanyLookup)

So don't work :( but

other lookups.py

from __future__ import unicode_literals
from selectable.base import LookupBase
from selectable.registry import registry
from .models import Filing

class CompanyLookup(LookupBase):

    def get_query(self, request, ticker):
        data= Filing.objects.values_list('company',flat=True)
        return [x for x in data if x.startswith(ticker)]

registry.register(CompanyLookup)

works, drops down, but only with the attributes of "startswith" and i need "icontains". Also don't work "istarswith", neither "contains":

In my consoles:

Request URL:http://127.0.0.1:8000/assets/flash/ZeroClipboard.swf?      noCache=1491057317592
Request Method:GET
Status Code:404 Not Found
Remote Address:127.0.0.1:8000

and:

 Uncaught ReferenceError: jQuery is not defined
 at jquery.dj.selectable.js?v=0.9.0:390
 (anonymous) @ jquery.dj.selectable.js?v=0.9.0:390

$(document).ready(function () {
    // Patch the django admin JS
    if (typeof(djselectableAdminPatch) === "undefined" || djselectableAdminPatch) {
        djangoAdminPatches();
    }
    // Bind existing widgets on document ready
    if (typeof(djselectableAutoLoad) === "undefined" || djselectableAutoLoad) {
        window.bindSelectables('body');
    }
});
})(jQuery || grp.jQuery);    <------ this is the line 390

also i don't understand why because in the view source code the

is loaded correctly

Thank you in advance if you can help me.

Body:
Try this:

def get_query(self, request, ticker):
    return  list(Filing.objects.filter(company__icontains=ticker).values_list('company', flat=True))

You want to filter your data in your database. Not in Python. Your database is much faster. When you do [x for x in x] you are returning a list, no a queryset. You can filter your queryset in the database by putting field__icontains=value in the filter method of a queryset.