问:
Powershell search path with wildcard-string-wildcard
I am trying to search a log file for updates that were not installed, then using the returned array install the updates. Problem is my files are named:

```<code>Windows6.1-KB3102429-v2-x64.msu
</code>```

My parsed array has a item of KB3102429 how can I use a wild card - call the array item - then another wildcard .msu

my code is listed below:

```<code># Read KBLIST.txt and create array of KB Updates that were not installed
$Failed = Get-Content -Path C:/Updates/KBLIST.txt | Where-Object {$_ -like '*NOT*'}

# create a list of all items in Updates folder
$dir = (Get-Item -Path "C:\Updates" -Verbose).FullName

# Parse the $Failed array down to just the KB#######
for($i = $Failed.GetLowerBound(0); $i -le $Failed.GetUpperBound(0); $i++)
{
    $Failed[$i][1..9] -join ""

    # Search the $dir list for files that contain KB####### and end in .msu then quiet install
    Foreach($item in (ls $dir *$Failed[$i]*.msu -Name))
    {
        echo $item
        $item = "C:\Updates\" + $item
        wusa $item /quiet /norestart | Out-Null
    }
}
</code>```

It works down to the Foreach($item in (ls $dir *$Failed[$i]*.msu -Name)).

If I just use * instead of the wildcard,string,wildcard it returns a list of all the .msu files for the basic syntax it correct.

答:
It was hard to follow your work since you used aliases, but I think this should be able to accomplish what you're looking for.</p>

```<code>$UpdateFolder = 'C:\Updates'
$FailedUpdates = Get-Content -Path C:/Updates/KBLIST.txt | Where-Object {$_ -like '*NOT*'}

foreach ( $Update in $FailedUpdates )
{
    Write-Host -Object "Update $Update failed"
    $UpdatePath = Get-Item -Path "$UpdateFolder\*$Update*.msu" | Select-Object -ExpandProperty FullName
    Write-Host -Object "`tReinstalling from path: $UpdatePath"
    wusa $UpdatePath /quiet /norestart | Out-Null
}
</code>```

Body:
I am trying to search a log file for updates that were not installed, then using the returned array install the updates. Problem is my files are named:

Windows6.1-KB3102429-v2-x64.msu

My parsed array has a item of KB3102429 how can I use a wild card - call the array item - then another wildcard .msu

my code is listed below:

# Read KBLIST.txt and create array of KB Updates that were not installed
$Failed = Get-Content -Path C:/Updates/KBLIST.txt | Where-Object {$_ -like '*NOT*'}

# create a list of all items in Updates folder
$dir = (Get-Item -Path "C:\Updates" -Verbose).FullName

# Parse the $Failed array down to just the KB#######
for($i = $Failed.GetLowerBound(0); $i -le $Failed.GetUpperBound(0); $i++)
{
    $Failed[$i][1..9] -join ""

    # Search the $dir list for files that contain KB####### and end in .msu then quiet install
    Foreach($item in (ls $dir *$Failed[$i]*.msu -Name))
    {
        echo $item
        $item = "C:\Updates\" + $item
        wusa $item /quiet /norestart | Out-Null
    }
}

It works down to the Foreach($item in (ls $dir *$Failed[$i]*.msu -Name)).

If I just use * instead of the wildcard,string,wildcard it returns a list of all the .msu files for the basic syntax it correct.

Body:
It was hard to follow your work since you used aliases, but I think this should be able to accomplish what you're looking for.

$UpdateFolder = 'C:\Updates'
$FailedUpdates = Get-Content -Path C:/Updates/KBLIST.txt | Where-Object {$_ -like '*NOT*'}

foreach ( $Update in $FailedUpdates )
{
    Write-Host -Object "Update $Update failed"
    $UpdatePath = Get-Item -Path "$UpdateFolder\*$Update*.msu" | Select-Object -ExpandProperty FullName
    Write-Host -Object "`tReinstalling from path: $UpdatePath"
    wusa $UpdatePath /quiet /norestart | Out-Null
}


来源: stackexchange

问:
Generic lambda and its argument as constant expression
The following code is accepted by GCC 7.2 and clang 5.0.0, but is rejected by Microsoft VS 2017 15.5.0 Preview 5 and Intel C++ compiler 19:

```<code>struct S { };

constexpr int f(S)
{
    return 0;
}

int main()
{
    auto lambda = [](auto x)
    {
        constexpr int e = f(x);
    };

    lambda(S{});
}
</code>```

Microsoft:

```<code><source>(12): error C2131: expression did not evaluate to a constant
</code>```

Intel:

```<code><source>(12): error: expression must have a constant value
    constexpr int e = f(x);
                      ^
<source>(12): note: the value of parameter "x" (declared at line 10) cannot be used as a constant
    constexpr int e = f(x);
                        ^
</code>```

If I replace f(x) with f(decltype(x){}), both Microsoft and Intel do not complain. I understand that x is not a constant expression, but it is not used inside f. This is probably why GCC and clang do not complain.

I guess that Microsoft and Intel compilers are correct in rejecting this code. What do you think?

答:
From [expr.const]:

An expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine, would evaluate one of the following expressions:

[...]

an lvalue-to-rvalue conversion unless it is applied to

a non-volatile glvalue of integral or enumeration type that refers to a complete non-volatile const object with a preceding initialization, initialized with a constant expression, or

a non-volatile glvalue that refers to a subobject of a string literal, or

a non-volatile glvalue that refers to a non-volatile object defined with constexpr, or that refers to a non-mutable subobject of such an object, or

a non-volatile glvalue of literal type that refers to a non-volatile object whose lifetime began within the evaluation of e;

[...]

In f(x), we do an lvalue-to-rvalue conversion on x. x isn't of integral or enumeration type, it's not a subobject of a string-literal, it's not an object defined with constexpr, and its lifetime did not begin with the evaluation of f(x).

That seems to make this not a core constant expression.

However, as Casey points out, since S is empty, nothing in its implicitly-generated copy constructor would actually trigger this lvalue-to-rvalue conversion. That would mean that nothing in this expression actually violates any of the core constant expression restrictions, and hence gcc and clang are correct in accepting it. This interpretation seems correct to me. constexpr is fun.

ContentLicense: CC BY-SA 3.0

Body:
The following code is accepted by GCC 7.2 and clang 5.0.0, but is rejected by Microsoft VS 2017 15.5.0 Preview 5 and Intel C++ compiler 19:

struct S { };

constexpr int f(S)
{
    return 0;
}

int main()
{
    auto lambda = [](auto x)
    {
        constexpr int e = f(x);
    };

    lambda(S{});
}

Microsoft:

<source>(12): error C2131: expression did not evaluate to a constant

Intel:

<source>(12): error: expression must have a constant value
    constexpr int e = f(x);
                      ^
<source>(12): note: the value of parameter "x" (declared at line 10) cannot be used as a constant
    constexpr int e = f(x);
                        ^

If I replace f(x) with f(decltype(x){}), both Microsoft and Intel do not complain. I understand that x is not a constant expression, but it is not used inside f. This is probably why GCC and clang do not complain.

I guess that Microsoft and Intel compilers are correct in rejecting this code. What do you think?


问:
Using identical list comprehensions on two separate lists

This feels like a simple question, but I haven't been able to figure it out and I haven't been able to find the answer anywhere.

In one line, how can I use two identical list comprehensions on two different lists, and return the results as two seperate lists?

I am trying to do this:

```<code>listx = [x for x in listx if x != None]
listy = [y for y in listy if y != None]
</code>```

Is there a way to do this in one line? Perhaps using map() or a list comprehension?

答:
Though I don't get why it has to be a one-liner, this should do what you want:</p>

```<code>listx, listy = [[x for x in alist if x != None] for alist in [listx, listy]]
</code>```

Body:
This feels like a simple question, but I haven't been able to figure it out and I haven't been able to find the answer anywhere.

In one line, how can I use two identical list comprehensions on two different lists, and return the results as two seperate lists?

I am trying to do this:

listx = [x for x in listx if x != None]
listy = [y for y in listy if y != None]

Is there a way to do this in one line? Perhaps using map() or a list comprehension?

Body:
Though I don't get why it has to be a one-liner, this should do what you want:

listx, listy = [[x for x in alist if x != None] for alist in [listx, listy]]


问:
Setting a negative margin which is a percentage of its height. Pure CSS
I have a series of images, which have different captions.
each of these captions needs to appear to float halfway over the bottom of the image.
Here is a mockup of how this looks and also how I have structured it in divs.
because there needs to be space between the bottom of the caption and whatever div is beneath, the caption cannot be absolutely positioned.

I am aware this could be done in javascript but this would be a hack so I'd prefer to find a CSS only solution.

...and here is the code so far: JS FIDDLE

.outer {
  position: relative;
  width: 320px;
  margin-bottom:24px // this needs to be the space between the bottom of the caption and the next image or whatever div is beneath.
}

.image {
  background-color: blue;
  width: 320px;
  height: 380px;
  position: relative;
  border-radius: 5px;
}

.caption {
  position: relative;
  margin-top: -24px;
  /* THIS NEEDS TO BE 50% of the Captions variable height */
}

.card {
  margin-right: 25%;
  margin-left: 5%;
  position: relative;
  background-color: #FFFFFF;
  padding: 24px;
  line-height: 24px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer">
  <div class="image">
  </div>
  <div class="caption">
    <div class="card">
      Lorem ipsum dolar sit amet consectetur idipiscine ipsumd lorem ipsum dolar sit amet. a
    </div>
  </div>
</div></code>```

答:
So you're looking to always have this caption adhere to the bottom of the image, while sitting 50% below of the parent container based on the captions height?

```<code>.outer {
  display:block;
  position:relative;
  width:320px;
}

.image {
  background-color:blue;
  width:320px;
  height:380px;
  display:block;
  position:relative;
  border-radius:5px;
}

/* Swapped the caption div to absolute, so it's always adhered to the bottom of the 'outer' container */

.caption {
  display:block;
  width: 100%;
  position: absolute;
  left: 0;
  bottom: 0;
}

/* Setup the 'block' div to do the actual '50%' manuevering based on the height of the  'caption' container with 'transform: translate(50%)' */

.block {
  transform: translateY(50%);
  background-color:#FFFFFF;
  padding:24px;
  line-height:24px;
}
</code>```

I've setup a jsfiddle here to demonstrate the changes @ https://jsfiddle.net/evanbriggs/v7rxqtcz/. Let me know if this is what you were thinking.

Body:
I have a series of images, which have different captions.
each of these captions needs to appear to float halfway over the bottom of the image.
Here is a mockup of how this looks and also how I have structured it in divs.
because there needs to be space between the bottom of the caption and whatever div is beneath, the caption cannot be absolutely positioned.

I am aware this could be done in javascript but this would be a hack so I'd prefer to find a CSS only solution.

...and here is the code so far: JS FIDDLE

.outer {
  position: relative;
  width: 320px;
  margin-bottom:24px // this needs to be the space between the bottom of the caption and the next image or whatever div is beneath.
}

.image {
  background-color: blue;
  width: 320px;
  height: 380px;
  position: relative;
  border-radius: 5px;
}

.caption {
  position: relative;
  margin-top: -24px;
  /* THIS NEEDS TO BE 50% of the Captions variable height */
}

.card {
  margin-right: 25%;
  margin-left: 5%;
  position: relative;
  background-color: #FFFFFF;
  padding: 24px;
  line-height: 24px;
}

      Lorem ipsum dolar sit amet consectetur idipiscine ipsumd lorem ipsum dolar sit amet. a

Body:
So you're looking to always have this caption adhere to the bottom of the image, while sitting 50% below of the parent container based on the captions height?

.outer {
  display:block;
  position:relative;
  width:320px;
}

.image {
  background-color:blue;
  width:320px;
  height:380px;
  display:block;
  position:relative;
  border-radius:5px;
}

/* Swapped the caption div to absolute, so it's always adhered to the bottom of the 'outer' container */

.caption {
  display:block;
  width: 100%;
  position: absolute;
  left: 0;
  bottom: 0;
}

/* Setup the 'block' div to do the actual '50%' manuevering based on the height of the  'caption' container with 'transform: translate(50%)' */

.block {
  transform: translateY(50%);
  background-color:#FFFFFF;
  padding:24px;
  line-height:24px;
}

I've setup a jsfiddle here to demonstrate the changes @ https://jsfiddle.net/evanbriggs/v7rxqtcz/. Let me know if this is what you were thinking.


问:
Linq Query: Distinct Year + Dynamic Name
I'm trying to take a DateTime field and create a List of DateObject, where DateObject has 2 properties (Year and Range). I want to identify the year of the DateTime field then... If it's even, I want to retain that year for Year. If it's odd, I want to change it to year - 1 for Year.

Then, based off that, I want to identify a string for Range that will look like "[EvenYear] to [EvenYear + 1]".

My data looks like this:

TableData

ID (i.e., 1)

Date (i.e., 12/7/2017)

If the records look like:

ID: 1, Date: 12/7/2017 (2017 should change to 2016)

ID: 2, Date: 1/1/2016 (keeps 2016)

ID: 3, Date: 1/2/2016 (keeps 2016)

ID: 4, Date: 10/5/2015 (2015 would be 2014)

I want the output List of DateObjects to look like this (distinct based off the Year):

Year: 2014, Range: 2014 to 2015

Year: 2016, Range: 2016 to 2017

I am so frustrated with figuring this out. I've tried a lot of code.

This is the code I left off with that kept failing:

```<code>var sessionYears = db.tblDates.GroupBy(x => (x.Date.Year % 2 == 0 ? x.Date.Year : x.Date.Year - 1)).ToList();

return sessionYears.Select(x => new List<DateObject>                {
StartYear= x.Key,
Range = x.Select(y => y.Date.Year + " to " + (y.Date.Year + 1))
}
</code>```

I've tried messing around with distinct and groupby, but I am clearly missing some steps, etc. I can't find anything online. Any help would be greatly appreciated!!! Thanks in advance.

答:
You could create the list of DateRangeObject first and after that get the distinct values. This will make your query much simpler.

```<code>return db.tblDates
    .Select(x => new DateRangeObject {
        StartYear = x.Date.Year % 2 == 0 ? x.Date.Year : x.Date.Year - 1,
        EndYear = (x.Date.Year % 2 == 0 ? x.Date.Year : x.Date.Year - 1) + " - " + ((x.Date.Year % 2 == 0 ? x.Date.Year : x.Date.Year - 1) + 1);
    })
    .GroupBy(x => x.StartYear)
    .Select(x => x.First())
    .ToList();
</code>```

Body:
I'm trying to take a DateTime field and create a List of DateObject, where DateObject has 2 properties (Year and Range). I want to identify the year of the DateTime field then... If it's even, I want to retain that year for Year. If it's odd, I want to change it to year - 1 for Year.

Then, based off that, I want to identify a string for Range that will look like "[EvenYear] to [EvenYear + 1]".

My data looks like this:

TableData

ID (i.e., 1)

Date (i.e., 12/7/2017)

If the records look like:

ID: 1, Date: 12/7/2017 (2017 should change to 2016)

ID: 2, Date: 1/1/2016 (keeps 2016)

ID: 3, Date: 1/2/2016 (keeps 2016)

ID: 4, Date: 10/5/2015 (2015 would be 2014)

I want the output List of DateObjects to look like this (distinct based off the Year):

Year: 2014, Range: 2014 to 2015

Year: 2016, Range: 2016 to 2017

I am so frustrated with figuring this out. I've tried a lot of code.

This is the code I left off with that kept failing:

var sessionYears = db.tblDates.GroupBy(x => (x.Date.Year % 2 == 0 ? x.Date.Year : x.Date.Year - 1)).ToList();

return sessionYears.Select(x => new List<DateObject>                {
StartYear= x.Key,
Range = x.Select(y => y.Date.Year + " to " + (y.Date.Year + 1))
}

I've tried messing around with distinct and groupby, but I am clearly missing some steps, etc. I can't find anything online. Any help would be greatly appreciated!!! Thanks in advance.

Body:
You could create the list of DateRangeObject first and after that get the distinct values. This will make your query much simpler.

return db.tblDates
    .Select(x => new DateRangeObject {
        StartYear = x.Date.Year % 2 == 0 ? x.Date.Year : x.Date.Year - 1,
        EndYear = (x.Date.Year % 2 == 0 ? x.Date.Year : x.Date.Year - 1) + " - " + ((x.Date.Year % 2 == 0 ? x.Date.Year : x.Date.Year - 1) + 1);
    })
    .GroupBy(x => x.StartYear)
    .Select(x => x.First())
    .ToList();


问:
Kohana Hierarchical Routes with Subpages
I'd like to set up some kind of hierarchical routing in Kohana 3.0.9. The routing should support pages and sub-pages, which could look something like this:

URL called: http://example.com/company/contact/

Possible Route: <page>(/<subpage>(/<action>))

The problem with above mentioned route is that it only supports a hierarchy with two levels. If the site needed to be able to handle "sub-sub-pages" like http://example.com/company/contact/sub, I would have to change the route.

Also, I'd like one single page controller to handle the request. It could, for example, accept company/contact/sub as a string parameter. I'm aware of the <directory> key and I'm not planning to use it.

Is there any way to make the route "compatible" with unlimited nested pages?

Thanks in advance for your answers.

答:
If you look at the ROUTING section, you can create custom REGEX patterns.
(read here)  http://kohanaframework.org/guide/kohana/routing

By default, routing "parameters" removes punctuation.

You can setup a regex to accept "/".

Then you can grab the last parameter and explode it with
$pieces = explode("/", $pizza);

Example:
http://example.com/company/contact/subpage/subsubpage/action

```<code>Route::set('multilevel', '(<controller>(/<page_levels>/<action>))'
, array('page_levels' => '.*'))
    ->defaults(array(
        'controller' => 'page_controller',
        'action'     => 'index',
    ));
</code>```

Doublecheck the REGEX, but basically it grabs all "/" except the very last one (which should be your ACTION parameter separator.

In your ACTION_[action] function (in Controller_Contact for this example),
you would then call

```<code>$page_levels = Request::instance()->param('page_levels');
$page_array  = explode("/",$page_levels);
</code>```

This should get you

```<code> $page_array = array ( [1] => 'contact',
                       [2] => 'subpage',
                       [3] => 'subsubpage')
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If you look at the ROUTING section, you can create custom REGEX patterns.
(read here)  http://kohanaframework.org/guide/kohana/routing

By default, routing "parameters" removes punctuation.

You can setup a regex to accept "/".

Then you can grab the last parameter and explode it with
$pieces = explode("/", $pizza);

Example:
http://example.com/company/contact/subpage/subsubpage/action

Route::set('multilevel', '(<controller>(/<page_levels>/<action>))'
, array('page_levels' => '.*'))
    ->defaults(array(
        'controller' => 'page_controller',
        'action'     => 'index',
    ));

Doublecheck the REGEX, but basically it grabs all "/" except the very last one (which should be your ACTION parameter separator.

In your ACTION_[action] function (in Controller_Contact for this example),
you would then call

$page_levels = Request::instance()->param('page_levels');
$page_array  = explode("/",$page_levels);

This should get you

 $page_array = array ( [1] => 'contact',
                       [2] => 'subpage',
                       [3] => 'subsubpage')


问:
Pandoc conversion from wiki file to Docx with table of content
I am using Pandoc to convert my document into different format

https://pandoc.org/

i create WIKI document and by using Pandoc i convert them to different format

lets suppose we have created wiki file with following content

```<code>=test =

{|
|-
! width="40%"| '''g1'''
! width="60%"|
|-
|'''''Activity0'''''
|Item 1
|}
{|
|-
! width="40%"| '''g2'''
! width="60%"| ''''''
|-
|'''''Activity4'''''
|Item 2
|}
</code>```

when i convert this command

pandoc -s a.wiki -o a.docx

it generate docx and word file is opening without any issue

but when i want to have TOC (table of content) in my word file i use

pandoc --toc -s a.wiki -o a.docx

it generate docx and word file is opening with this issue

i am not sure what and why this is coming

is there any solution or link where it guide me to solution , i have tried to google it but not able to find it yet

答: I had the same problem with wrong links in the text. In my case, i tried to make internal link on image, which based under the text. Link didn't work, but when i past 2-3 new line symbols before and after image link, it became ok. I don't know why, but pandoc need's some empty lines before and after image link. </p>

Body:
I am using Pandoc to convert my document into different format

https://pandoc.org/

i create WIKI document and by using Pandoc i convert them to different format

lets suppose we have created wiki file with following content

=test =

{|
|-
! width="40%"| '''g1'''
! width="60%"|
|-
|'''''Activity0'''''
|Item 1
|}
{|
|-
! width="40%"| '''g2'''
! width="60%"| ''''''
|-
|'''''Activity4'''''
|Item 2
|}

when i convert this command

pandoc -s a.wiki -o a.docx

it generate docx and word file is opening without any issue

but when i want to have TOC (table of content) in my word file i use

pandoc --toc -s a.wiki -o a.docx

it generate docx and word file is opening with this issue

i am not sure what and why this is coming

is there any solution or link where it guide me to solution , i have tried to google it but not able to find it yet


问:
AesManaged determine if password is wrong
I've been working with the AesManaged class to encrypt some data and I have everything working properly when the correct password is provided.  However, if the wrong password is supplied for decrypt, even if it's the same length, I get the error "Padding is invalid and cannot be removed".

My question is: If I supply the wrong password, will I always get this message?  If not, is there a way to tell if the data was decrypted properly without knowing what the original data was?

答:
Bad padding error messages generally mean that the decryption failed, it is a really poor error message. The padding is bad because the decryption failed and as a result the padding which is encrypted is incorrect. But as bartonjs points out the encreyption can fail with no padding error (by chnace).

If you need to detect incorrect decryption you need to add authentication, this generally means an HMAC of the encrypted data. Then prior to decryption the HMAC is  run over the encrypted data and compared.

For an implementation example see RNCryptor-Spec.


答:
Just use position: absolute and transform property to do the trick.

Here is an example:
https://jsfiddle.net/nawLywc9/1/

The .block classs must be like this:

```<code>.block {
    position:relative; // This is important
    background-color:#FFFFFF;
    padding:24px;
    line-height:24px;
    bottom: -50%; // This is important
    transform: translateY(-50px); // This is important
    width: 60%;
    border-radius: 5px;
    margin: 0 auto; // Only if you need to be centered
}
</code>```

Here is the preview: https://jsfiddle.net/nawLywc9/1/

Title: Setting a negative margin which is a percentage of its height. Pure CSS

Body:
Just use position: absolute and transform property to do the trick.

Here is an example:
https://jsfiddle.net/nawLywc9/1/

The .block classs must be like this:

.block {
    position:relative; // This is important
    background-color:#FFFFFF;
    padding:24px;
    line-height:24px;
    bottom: -50%; // This is important
    transform: translateY(-50px); // This is important
    width: 60%;
    border-radius: 5px;
    margin: 0 auto; // Only if you need to be centered
}

Here is the preview: https://jsfiddle.net/nawLywc9/1/


问:
Java JSP Jquery AJAX Servlet
UPDATE

I disagree that the answer for the suggested question will directly apply to this question because I am using a non standard directory structure.

```<code>/opt/tomcat/webapps/nothing/
    /public/
        /views/
            /home/
                home.jsp
            /nothing/
                nothing01.jsp
            /partials/
                header.jsp
                footer.jsp
        /logic/
            /nothing/
                nothing01.js
                nothing01test.java
                nothing01test.class
        /resources/
    /WEB-INF/
        web.xml
</code>```

I'm having a bit of confusion trying to use a JSP Servlet in my application using Jquery AJAX.

I'm most likely missing a step (or doing it completely wrong).

I have my view

```<code>/public/view/nothing/nothing01.jsp

<% include file="../partials/header.jsp" %>
<button id="buttTest">Test</button>
<% include file="../partials/footer.jsp" %>
</code>```

Which is linked to a Javascript file intended to use in making a Jquery AJAX call to my Java Servlet

```<code>/public/logic/nothing/nothing01.js

$(document).ready(function() {
    $("#buttTest").on("click", function() {
       ajaxTest();
    });
});

function ajaxTest() {

    $.ajax ({
        url      : "nothing01test",
        type     : "GET",
        cache    : false,
        dataType : "json",
        success  : function(results) {
                       console.log("success");
                       console.log(JSON.stringify(results));
                   },
        error    : function(results) {
                       console.log("error");
                       console.log(JSON.stringify(results));
                   }
    });

}
</code>```

Then I have my source and compiled Java Servlet

```<code>/public/logic/nothing/nothing01test.java
/public/logic/nothing/nothing01test.class

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class nothing01test extends HttpServlet {
    protected void doGet (
        HttpServletRequest request,
        HttpServletResponse response
    ) throws
        ServletException,
        IOException
    {
        PrintWriter out = response.getWriter();
        out.println("AJAX RESPONSE");
     }
}
</code>```

The compile works fine without any errors but I'm not sure how to make it available to the Jquery AJAX request because the request is responding with a 404 not found error. If I try specifying the AJAX url to point to the java and class file it just pulls in the contents instead of executing.

UPDATE

I'm going to include the web.xml file just in case

```<code>/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
      Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0"
  metadata-complete="true">

  <display-name>Java Web App</display-name>
  <description>
     Welcome to Java Web App
  </description>

  <welcome-file-list>
    <welcome-file>public/views/home/home.jsp</welcome-file>
  </welcome-file-list>

</web-app>
</code>```

答:
Your AJAX call is incorrect, try replacing it with the code below</p>

```<code>$(document).ready(function() {
    $("#buttTest").on("click", function() {
       ajaxTest();
    });
});

function ajaxTest() {
    $.ajax({
        url      : "nothing01test",
        type     : "GET",
        cache    : false,
        dataType : "json",
        success  : function(results) {
                       console.log("success");
                       console.log(JSON.stringify(results));
                   },
        error    : function(results) {
                       console.log("error");
                       console.log(JSON.stringify(results));
                   }
    });
}
</code>```

Title: Java JSP Jquery AJAX Servlet

Body:
UPDATE

I disagree that the answer for the suggested question will directly apply to this question because I am using a non standard directory structure.

/opt/tomcat/webapps/nothing/
    /public/
        /views/
            /home/
                home.jsp
            /nothing/
                nothing01.jsp
            /partials/
                header.jsp
                footer.jsp
        /logic/
            /nothing/
                nothing01.js
                nothing01test.java
                nothing01test.class
        /resources/
    /WEB-INF/
        web.xml

I'm having a bit of confusion trying to use a JSP Servlet in my application using Jquery AJAX.

I'm most likely missing a step (or doing it completely wrong).

I have my view

/public/view/nothing/nothing01.jsp

<% include file="../partials/header.jsp" %>
<button id="buttTest">Test</button>
<% include file="../partials/footer.jsp" %>

Which is linked to a Javascript file intended to use in making a Jquery AJAX call to my Java Servlet

/public/logic/nothing/nothing01.js

$(document).ready(function() {
    $("#buttTest").on("click", function() {
       ajaxTest();
    });
});

function ajaxTest() {

    $.ajax ({
        url      : "nothing01test",
        type     : "GET",
        cache    : false,
        dataType : "json",
        success  : function(results) {
                       console.log("success");
                       console.log(JSON.stringify(results));
                   },
        error    : function(results) {
                       console.log("error");
                       console.log(JSON.stringify(results));
                   }
    });

}

Then I have my source and compiled Java Servlet

/public/logic/nothing/nothing01test.java
/public/logic/nothing/nothing01test.class

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class nothing01test extends HttpServlet {
    protected void doGet (
        HttpServletRequest request,
        HttpServletResponse response
    ) throws
        ServletException,
        IOException
    {
        PrintWriter out = response.getWriter();
        out.println("AJAX RESPONSE");
     }
}

The compile works fine without any errors but I'm not sure how to make it available to the Jquery AJAX request because the request is responding with a 404 not found error. If I try specifying the AJAX url to point to the java and class file it just pulls in the contents instead of executing.

UPDATE

I'm going to include the web.xml file just in case

/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0"
  metadata-complete="true">

  <display-name>Java Web App</display-name>
  <description>
     Welcome to Java Web App
  </description>

  <welcome-file-list>
    <welcome-file>public/views/home/home.jsp</welcome-file>
  </welcome-file-list>

</web-app>

Body:
Your AJAX call is incorrect, try replacing it with the code below

$(document).ready(function() {
    $("#buttTest").on("click", function() {
       ajaxTest();
    });
});

function ajaxTest() {
    $.ajax({
        url      : "nothing01test",
        type     : "GET",
        cache    : false,
        dataType : "json",
        success  : function(results) {
                       console.log("success");
                       console.log(JSON.stringify(results));
                   },
        error    : function(results) {
                       console.log("error");
                       console.log(JSON.stringify(results));
                   }
    });
}


问:
Read and Write Uploaded File with Wand
Here is my code:

```<code>class ToPng(APIView):
    def post(self, request, *args, **kwargs):

        revision = request.data.get('revision', None)
        file = request.data.get('file', None)

        with tempfile.TemporaryFile() as tmp:
            tmp.write(file.read())
            all_pages = Image(file=tmp)
            single_image = all_pages.sequence[0]
            with Image(single_image) as img:
                img.format = 'png'
                img.background_color = Color('white')
                img.alpha_channel = 'remove'
                MyModel.objects.create(revision=revision, file=img)
                return Response(HTTP_200_OK)
</code>```

I get the error: "no decode delegate for this image format `' @ error/blob.c/BlobToImage/353"

Obviously I am making a grave mistake since wand, with imagemagick and ghostscript installed, can convert Pdf to Png right away. I am probably reading the wrong thing but I don't know what else to do.

答:
You just need to reset the tempfile back to the beginning of the file before reading.

    with tempfile.TemporaryFile() as tmp:
        tmp.write(file.read())
        tmp.seek(0)
        all_pages = Image(file=tmp)
```

<p><strong>Updated</strong></p>

<p>I haven't used django in a view years, but you should be able to create an <code>InMemoryUploadedFile</code> with <code>StringIO</code>. Example from here</p>

<pre class="lang-py prettyprint-override"><code>import StringIO
# ... Skip to after img work ...
img_io=StringIO.StringIO()
img.save(file=img_io)
img_file=InMemoryUploadedFile(img_io,
                              None,
                              'first_page.jpg',
                              'image/jpeg',
                              img_io.len,
                              None)
MyModel.objects.create(revision=revision, file=img_file)
</code>```

Title: Read and Write Uploaded File with Wand

Body:
Here is my code:

class ToPng(APIView):
    def post(self, request, *args, **kwargs):

        revision = request.data.get('revision', None)
        file = request.data.get('file', None)

        with tempfile.TemporaryFile() as tmp:
            tmp.write(file.read())
            all_pages = Image(file=tmp)
            single_image = all_pages.sequence[0]
            with Image(single_image) as img:
                img.format = 'png'
                img.background_color = Color('white')
                img.alpha_channel = 'remove'
                MyModel.objects.create(revision=revision, file=img)
                return Response(HTTP_200_OK)

I get the error: "no decode delegate for this image format `' @ error/blob.c/BlobToImage/353"

Obviously I am making a grave mistake since wand, with imagemagick and ghostscript installed, can convert Pdf to Png right away. I am probably reading the wrong thing but I don't know what else to do.

Body:
You just need to reset the tempfile back to the beginning of the file before reading.

    with tempfile.TemporaryFile() as tmp:
        tmp.write(file.read())
        tmp.seek(0)
        all_pages = Image(file=tmp)

Updated

I haven't used django in a view years, but you should be able to create an InMemoryUploadedFile with StringIO. Example from here

import StringIO
# ... Skip to after img work ...
img_io=StringIO.StringIO()
img.save(file=img_io)
img_file=InMemoryUploadedFile(img_io,
                              None,
                              'first_page.jpg',
                              'image/jpeg',
                              img_io.len,
                              None)
MyModel.objects.create(revision=revision, file=img_file)


问:
How do I align icons from the start of a line to the end of a line which is evenly distributed horizontally?
How can I have the icon display from the beginning of the line to the end of the line and and have it evenly distributed?  The icons should be evenly distributed and an icon should be at the start and end of the line.  I can't figure out how to get it to the end.

Thanks for any help!

.steps {
    width: 100%;
    display: -webkit-flex;
    display: flex;
    -webkit-justify-content: space-between;
    justify-content: space-between;
    align-items: stretch;
}

.steps div {
    line-height: 3em;
    display: flex;
    justify-content: space-between;
    flex: 1 1 auto;
    align-items: stretch;
}

.steps .complete-step {
    border-bottom: 4px solid #95CA3E;
}

.steps .incomplete-step {
    border-bottom: 4px solid #0369B3;
}

.steps div:after {
    content: "\00a0\00a0";
}

.steps div:before {
    position: relative;
    bottom: -2.5em;
    float: none;
    line-height: 1em;
}

.steps .complete-step:before {
    font-family: 'FontAwesome';
    content: "\f111";
    color: #95CA3E;
    background-color: #95CA3E;
    height: 1.2em;
    width: 1.2em;
    border-radius: 1.2em;
}

.steps .incomplete-step:before {
    font-family: 'FontAwesome';
    content: "\f192";
    font-size: 1.5em;
    bottom: -1.6em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>

<div class="steps">
    <div class="complete-step"></div>
    <div class="complete-step"></div>
    <div class="incomplete-step"></div>
    <div class="incomplete-step"></div>
    <div class="incomplete-step"></div>
    <div class="incomplete-step"></div>
    <div class="incomplete-step"></div>
</div></code>```

答:
You cannot do that because the flexbox computes the size of its children.
Your icons aren't the children, they are in the children (in the :before pseudo-element). What you can quickly do though, is to trick it and remove the line on the last child ;) Else, you'll have to review your DOM I think.

Using the :last-child selector, you can also hack the width of the last element or anything you'll like to improve the design on the end of the line!

.steps {
            width: 100%;
            display: -webkit-flex;
            display: flex;
            -webkit-justify-content: space-between;
            justify-content: space-between;
            align-items: stretch;
        }

        .steps div {
            line-height: 3em;
            display: flex;
            justify-content: space-between;
            flex: 1 1 auto;
            align-items: stretch;
        }

        .steps .complete-step {
            border-bottom: 4px solid #95CA3E;
        }

        .steps .incomplete-step {
            border-bottom: 4px solid #0369B3;
        }

        .steps .complete-step:last-child {
            border-bottom: none;
        }

        .steps .incomplete-step:last-child {
            border-bottom: none;
        }

        .steps div:after {
            content: "\00a0\00a0";
        }

        .steps div:before {
            position: relative;
            bottom: -2.5em;
            float: none;
            line-height: 1em;
        }

        .steps .complete-step:before {
            font-family: 'FontAwesome';
            content: "\f111";
            color: #95CA3E;
            background-color: #95CA3E;
            height: 1.2em;
            width: 1.2em;
            border-radius: 1.2em;
        }

        .steps .incomplete-step:before {
            font-family: 'FontAwesome';
            content: "\f192";
            font-size: 1.5em;
            bottom: -1.6em;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>

<div class="steps">
        <div class="complete-step"></div>
        <div class="complete-step"></div>
        <div class="incomplete-step"></div>
        <div class="incomplete-step"></div>
        <div class="incomplete-step"></div>
        <div class="incomplete-step"></div>
        <div class="incomplete-step"></div>
    </div></code>```

Body:
How can I have the icon display from the beginning of the line to the end of the line and and have it evenly distributed?  The icons should be evenly distributed and an icon should be at the start and end of the line.  I can't figure out how to get it to the end.

Thanks for any help!

.steps {
    width: 100%;
    display: -webkit-flex;
    display: flex;
    -webkit-justify-content: space-between;
    justify-content: space-between;
    align-items: stretch;
}

.steps div {
    line-height: 3em;
    display: flex;
    justify-content: space-between;
    flex: 1 1 auto;
    align-items: stretch;
}

.steps .complete-step {
    border-bottom: 4px solid #95CA3E;
}

.steps .incomplete-step {
    border-bottom: 4px solid #0369B3;
}

.steps div:after {
    content: "\00a0\00a0";
}

.steps div:before {
    position: relative;
    bottom: -2.5em;
    float: none;
    line-height: 1em;
}

.steps .complete-step:before {
    font-family: 'FontAwesome';
    content: "\f111";
    color: #95CA3E;
    background-color: #95CA3E;
    height: 1.2em;
    width: 1.2em;
    border-radius: 1.2em;
}

.steps .incomplete-step:before {
    font-family: 'FontAwesome';
    content: "\f192";
    font-size: 1.5em;
    bottom: -1.6em;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>

Body:
You cannot do that because the flexbox computes the size of its children.
Your icons aren't the children, they are in the children (in the :before pseudo-element). What you can quickly do though, is to trick it and remove the line on the last child ;) Else, you'll have to review your DOM I think.

Using the :last-child selector, you can also hack the width of the last element or anything you'll like to improve the design on the end of the line!

.steps {
            width: 100%;
            display: -webkit-flex;
            display: flex;
            -webkit-justify-content: space-between;
            justify-content: space-between;
            align-items: stretch;
        }

        .steps div {
            line-height: 3em;
            display: flex;
            justify-content: space-between;
            flex: 1 1 auto;
            align-items: stretch;
        }

        .steps .complete-step {
            border-bottom: 4px solid #95CA3E;
        }

        .steps .incomplete-step {
            border-bottom: 4px solid #0369B3;
        }

        .steps .complete-step:last-child {
            border-bottom: none;
        }

        .steps .incomplete-step:last-child {
            border-bottom: none;
        }

        .steps div:after {
            content: "\00a0\00a0";
        }

        .steps div:before {
            position: relative;
            bottom: -2.5em;
            float: none;
            line-height: 1em;
        }

        .steps .complete-step:before {
            font-family: 'FontAwesome';
            content: "\f111";
            color: #95CA3E;
            background-color: #95CA3E;
            height: 1.2em;
            width: 1.2em;
            border-radius: 1.2em;
        }

        .steps .incomplete-step:before {
            font-family: 'FontAwesome';
            content: "\f192";
            font-size: 1.5em;
            bottom: -1.6em;
        }

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>

<div class="steps">
        <div class="complete-step"></div>
        <div class="complete-step"></div>
        <div class="incomplete-step"></div>
        <div class="incomplete-step"></div>
        <div class="incomplete-step"></div>
        <div class="incomplete-step"></div>
        <div class="incomplete-step"></div>
    </div>


问:
Failed to decode base64 in javascript
I receive an id_token as part of my current href. It is encoded in base64. I try to decode it using atob(extractedIdToken), but get the following error:

Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded

When I copy and paste the extracted id_token in my code and go to an online decoding site, it decodes correctly. Do you have suggestion?

答: In my case, the issue was that the encoded string should have been treated as segments. Just separate the code with the separator "." or whatever your case is. Then, decode only the different parts separately. This resolved my issue and I was able to decode using window.atob(). Hope this helps.</p>

Title: Failed to decode base64 in javascript


问:
Dataframe for textfile Spark
I'm trying to create a data frame on a text file. For a sample input (Input1)
 below Code is working fine

Input1

```<code>1,5

2,6

3,7

4,8
</code>```

Output1

```<code>+---+----+
| id|name|
+---+----+
|  1|   5|
|  2|   6|
|  3|   7|
|  4|   8|
+---+----+
</code>```

However when I changed the input(Input2), I'm not getting any output.

Input2

```<code>1,"a,b,c"

2,"d,e,f"

3,"a,b,c"

4,"a,d,f"
</code>```

Output2

```<code>+---+----+
| id|name|
+---+----+
+---+----+
</code>```

Code

```<code>    {
        val input = sc.textFile(inputFile).map(x=>x.split(",")).collect {
                            case Array(id,name) => Record(id.toInt, name)
                    }
                    input.toDF().show()
    }
case class Record(id: Int, name: String)
</code>```

Expected output format for Input2

```<code>+---+-----+------+-----+
| id|name1| name2|name3|
+---+-----+------+-----+
|  1|    a|     b|    c|
|  2|    d|     e|    d|
|  3|    a|     b|    c|
|  4|    a|     d|    f|
+---+-----+------+-----+
</code>```

I should make changes to the code and case class as well so that compiler understands the data format for Input2, but I'm not getting what changes I need to do.  Please advice.

答:
I tried with the below code and got the output as per the need.</p>

```<code>    {
        val input = sc.textFile(inputFile).map(x=>x.replaceAll("\"",""))
        val input1 = input.map(x=>x.split(",")).collect { case Array(id,name,name1, name2) => Record(id.toInt, name, name1, name2) }
    }
    case class Record(id: Int, name: String, name1 : String, name2 : String)
</code>```

Title: Dataframe for textfile Spark

Body:
I'm trying to create a data frame on a text file. For a sample input (Input1)
 below Code is working fine

Input1

1,5

2,6

3,7

4,8

Output1

+---+----+
| id|name|
+---+----+
|  1|   5|
|  2|   6|
|  3|   7|
|  4|   8|
+---+----+

However when I changed the input(Input2), I'm not getting any output.

Input2

1,"a,b,c"

2,"d,e,f"

3,"a,b,c"

4,"a,d,f"

Output2

+---+----+
| id|name|
+---+----+
+---+----+

Code

    {
        val input = sc.textFile(inputFile).map(x=>x.split(",")).collect {
                            case Array(id,name) => Record(id.toInt, name)
                    }
                    input.toDF().show()
    }
case class Record(id: Int, name: String)

Expected output format for Input2

+---+-----+------+-----+
| id|name1| name2|name3|
+---+-----+------+-----+
|  1|    a|     b|    c|
|  2|    d|     e|    d|
|  3|    a|     b|    c|
|  4|    a|     d|    f|
+---+-----+------+-----+

I should make changes to the code and case class as well so that compiler understands the data format for Input2, but I'm not getting what changes I need to do.  Please advice.

Body:
I tried with the below code and got the output as per the need.

    {
        val input = sc.textFile(inputFile).map(x=>x.replaceAll("\"",""))
        val input1 = input.map(x=>x.split(",")).collect { case Array(id,name,name1, name2) => Record(id.toInt, name, name1, name2) }
    }
    case class Record(id: Int, name: String, name1 : String, name2 : String)


问:
Memcpy a str[ ] to str*
I'm trying to create a xoring function ( I want to XOR 2 strings and return the result).

For that, I need to copy the content a an array (str[ ]) to a string (str* ).

```<code>char* xor(char* str1, char* str2)
{
    char temp[strlen(str1)];
    char* result = NULL;
    int i;

    for(i=0; i<=strlen(str1); i++)
    {
        temp[i] = str1[i] ^ str2[i];
    }
    memcpy(result,temp,sizeof(temp)+1);
    return result;
}
</code>```

I'm getting a seg fault for my memcpy.

Am I missing something ? Can you help me ?

答:
Taking all comments into account, I believe your function should be:

```<code>char* xor(char* str1, char* str2)
{
    int len= strlen(str1)
    char temp[len];

    if (strlen(str2) != len) return 0;
    char *result = malloc(len);

    for(int i=0; i<len; i++)
    {
        temp[i] = str1[i] ^ str2[i];
    }
    memcpy(result,temp,len);
    return result;
}
</code>```

which can be simplified to:

```<code>char* xor(char* str1, char* str2)
{
    int len= strlen(str1)

    if (strlen(str2) != len) return 0;
    char *result = malloc(len);

    for(int i=0; i<len; i++)
    {
        result[i] = str1[i] ^ str2[i];
    }
    return result;
}
</code>```

Title: Memcpy a str[ ] to str*

Body:
I'm trying to create a xoring function ( I want to XOR 2 strings and return the result).

For that, I need to copy the content a an array (str[ ]) to a string (str* ).

char* xor(char* str1, char* str2)
{
    char temp[strlen(str1)];
    char* result = NULL;
    int i;

    for(i=0; i<=strlen(str1); i++)
    {
        temp[i] = str1[i] ^ str2[i];
    }
    memcpy(result,temp,sizeof(temp)+1);
    return result;
}

I'm getting a seg fault for my memcpy.

Am I missing something ? Can you help me ?

Body:
Taking all comments into account, I believe your function should be:

char* xor(char* str1, char* str2)
{
    int len= strlen(str1)
    char temp[len];

    if (strlen(str2) != len) return 0;
    char *result = malloc(len);

    for(int i=0; i<len; i++)
    {
        temp[i] = str1[i] ^ str2[i];
    }
    memcpy(result,temp,len);
    return result;
}

which can be simplified to:

char* xor(char* str1, char* str2)
{
    int len= strlen(str1)

    if (strlen(str2) != len) return 0;
    char *result = malloc(len);

    for(int i=0; i<len; i++)
    {
        result[i] = str1[i] ^ str2[i];
    }
    return result;
}


问:
Q/A level in game not picking up correct answer
I am trying to make a question / answer level in C# for my coursework. Here is the code:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Linq;

namespace frmSplashScreen
{
    public partial class frmLevel3 : Form
    {
        public frmLevel3()
        {
            InitializeComponent();
        }
        string currentq = null;
        int questionsshown = 1; //to go up to 4
        int questionno = 0;

        public void randomq() //new question function... generating number, using it as index, putting it on lblQ
        {
            Random ran = new Random();
            questionno = ran.Next(20);

            label1.Text = questionno.ToString(); //debug
            label2.Text = gameClass.answers[questionno];//debug

            lblQ.Text = gameClass.questions[questionno];
            gameClass.questions.RemoveAt(questionno);
        }

        private void frmLevel3_Load(object sender, EventArgs e) // Load //
        {
            btnNext.Hide();
            using (StreamReader sr = new StreamReader("l3questions.txt")) //reading all questions from text file
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    gameClass.questions.Add(line);
                }

            }
            using (StreamReader sr = new StreamReader("l3answers.txt")) //reading all answers from text file
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    gameClass.answers.Add(line);
                }
            }
            randomq();
        }

        private void btnNext_Click(object sender, EventArgs e) // Next Button //
        {
            btnNext.Hide();
            btnCheck.Show();
            if (questionsshown >= 4) // Checking no. of questions shown
            {
                frmMainMenu menu = new frmMainMenu(); //Go to Menu
                this.Hide();
                menu.Show();
            }
            else
            {
                questionsshown++;
                randomq(); //if less than 4 questions have been shown, show another.
            }
            txt1a.BackColor = Color.White; //Setting txts back to normal
            txt1a.Text = null;
        }
        private void btnCheck_Click(object sender, EventArgs e) // Check Button //
        {
            btnCheck.Hide();
            btnNext.Show();
            if (txt1a.Text.ToLower() == gameClass.answers[questionno]) //checking question
            {
                gameClass.score++;
                txt1a.BackColor = Color.Green;
            }
            else
            {
                txt1a.BackColor = Color.Red;
            }
        }
    }
}
</code>```

gameClass is a class that stores a question list and an answer list.

My problem is that when I go to run the level, it is picking up the correct questions / answers from the list for the first 2 times but for the next two times after that, the answer that it is trying to check is something completely random from the list, not the answer that it should take from the index number in the variable questionno.

Any help would be greatly appreciated.

答:
In your randomq function you remove your question from the file, but not the answer. When you click the button though, you check in your answer test file with a matching index number. After the first loop, your text files will go out of sync, you'll have less questions than answers and their index will not match.

```<code>public void randomq() //new question function... generating number, using it as index, putting it on lblQ
    {
        Random ran = new Random();
        questionno = ran.Next(20);

        label1.Text = questionno.ToString(); //debug
        label2.Text = gameClass.answers[questionno];//debug

        lblQ.Text = gameClass.questions[questionno];
        //Add this
        someStringAnswer = gameClass.answers[questionno];
        gameClass.questions.RemoveAt(questionno);
        //And this
        gameClass.answers.RemoveAt(questionno);
    }
</code>```

After this, use someStringAnswer to look if you have the right answer in btnCheck_Click

Body:
I am trying to make a question / answer level in C# for my coursework. Here is the code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Linq;

namespace frmSplashScreen
{
    public partial class frmLevel3 : Form
    {
        public frmLevel3()
        {
            InitializeComponent();
        }
        string currentq = null;
        int questionsshown = 1; //to go up to 4
        int questionno = 0;

        public void randomq() //new question function... generating number, using it as index, putting it on lblQ
        {
            Random ran = new Random();
            questionno = ran.Next(20);

            label1.Text = questionno.ToString(); //debug
            label2.Text = gameClass.answers[questionno];//debug

            lblQ.Text = gameClass.questions[questionno];
            gameClass.questions.RemoveAt(questionno);
        }

        private void frmLevel3_Load(object sender, EventArgs e) // Load //
        {
            btnNext.Hide();
            using (StreamReader sr = new StreamReader("l3questions.txt")) //reading all questions from text file
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    gameClass.questions.Add(line);
                }

            }
            using (StreamReader sr = new StreamReader("l3answers.txt")) //reading all answers from text file
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    gameClass.answers.Add(line);
                }
            }
            randomq();
        }

        private void btnNext_Click(object sender, EventArgs e) // Next Button //
        {
            btnNext.Hide();
            btnCheck.Show();
            if (questionsshown >= 4) // Checking no. of questions shown
            {
                frmMainMenu menu = new frmMainMenu(); //Go to Menu
                this.Hide();
                menu.Show();
            }
            else
            {
                questionsshown++;
                randomq(); //if less than 4 questions have been shown, show another.
            }
            txt1a.BackColor = Color.White; //Setting txts back to normal
            txt1a.Text = null;
        }
        private void btnCheck_Click(object sender, EventArgs e) // Check Button //
        {
            btnCheck.Hide();
            btnNext.Show();
            if (txt1a.Text.ToLower() == gameClass.answers[questionno]) //checking question
            {
                gameClass.score++;
                txt1a.BackColor = Color.Green;
            }
            else
            {
                txt1a.BackColor = Color.Red;
            }
        }
    }
}

gameClass is a class that stores a question list and an answer list.

My problem is that when I go to run the level, it is picking up the correct questions / answers from the list for the first 2 times but for the next two times after that, the answer that it is trying to check is something completely random from the list, not the answer that it should take from the index number in the variable questionno.

Any help would be greatly appreciated.

Body:
In your randomq function you remove your question from the file, but not the answer. When you click the button though, you check in your answer test file with a matching index number. After the first loop, your text files will go out of sync, you'll have less questions than answers and their index will not match.

public void randomq() //new question function... generating number, using it as index, putting it on lblQ
    {
        Random ran = new Random();
        questionno = ran.Next(20);

        label1.Text = questionno.ToString(); //debug
        label2.Text = gameClass.answers[questionno];//debug

        lblQ.Text = gameClass.questions[questionno];
        //Add this
        someStringAnswer = gameClass.answers[questionno];
        gameClass.questions.RemoveAt(questionno);
        //And this
        gameClass.answers.RemoveAt(questionno);
    }

After this, use someStringAnswer to look if you have the right answer in btnCheck_Click


问:
Laravel Sold Items Count
I want count the Sold items for every Seller.
I try to change this Code:

```<code><?php $count = DB::table('purchases')->whereIn('seller_id', [4])->count(); echo $count; ?>
</code>```

Can i add an other $DB command in it?

```<code>{{$product->seller->id}}
</code>```

Like this for example instead of [4]:

```<code><?php $count = DB::table('purchases')->whereIn('seller_id', [{{$product->seller->id}}])->count(); echo $count; ?>
</code>```

答:
Try this :

In your Seller Model

```<code>public function purchases(){
    return $this->hasMany(Purchase::class)
}
</code>```

then

```<code>$seller = Seller::withCount('purchases')->find(4);

echo $seller->purchases_count;
</code>```

or

```<code>$purchases = Seller::find(4)->purchases;

echo $purchases->count();
</code>```

Title: Laravel Sold Items Count

Body:
I want count the Sold items for every Seller.
I try to change this Code:

<?php $count = DB::table('purchases')->whereIn('seller_id', [4])->count(); echo $count; ?>

Can i add an other $DB command in it?

{{$product->seller->id}}

Like this for example instead of [4]:

<?php $count = DB::table('purchases')->whereIn('seller_id', [{{$product->seller->id}}])->count(); echo $count; ?>

Body:
Try this :

In your Seller Model

public function purchases(){
    return $this->hasMany(Purchase::class)
}

then

$seller = Seller::withCount('purchases')->find(4);

echo $seller->purchases_count;

or

$purchases = Seller::find(4)->purchases;

echo $purchases->count();


问:
Is it possible to compile a single C# code file with the .NET Core Roslyn compiler?
In old .NET we used to be able to run the csc compiler to compile a single .cs file or several files.

With .NET Core we have dotnet build that insists on having a proper project file. Is there a stand-alone  command line compiler that would allow to compile source code files without having a project (and listing referenced dependencies on the same command line)?

On Linux, when I have the old csc and the new .NET Core installed, I get these timings:

```<code>[root@li1742-80 test]# time dotnet build
Microsoft (R) Build Engine version 15.3.409.57025 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

  test -> /root/test/bin/Debug/netcoreapp2.0/test.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:03.94

real    0m7.027s
user    0m5.714s
sys     0m0.838s

[root@li1742-80 test]# time csc Program.cs
Microsoft (R) Visual C# Compiler version 2.3.0.61801 (3722bb71)
Copyright (C) Microsoft Corporation. All rights reserved.

real    0m0.613s
user    0m0.522s
sys     0m0.071s
[root@li1742-80 test]#
</code>```

Note 7 seconds with .NET Core versus several hundred milliseconds with the old csc for the same file, Program.cs.

I'd like to be able to compile as fast with .NET Core as I used to be able with csc.

答:
Yes, it is possible to compile a single file with csc or vbc compilers in .NET Core.

To invoke the Roslyn compiler directly it is necessary to use the command line driver csc.{exe|dll} and since Roslyn in contrast to the old csc.exe does not reference mscorlib.dll implicitly it is necessary to pass a reference to the required dependencies, i.e. System.Runtime and System.Private.CoreLib libraries and any other required references. The following listing shows how to compile the following Hello, World! program.

```<code>using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}
</code>```

Using WSL with Ubuntu 16.04 (Xenial Xerus) and dotnet-sdk-2.0.0 installed:

```<code>time dotnet /usr/share/dotnet/sdk/2.0.0/Roslyn/csc.exe -r:/usr/share/dotnet/shared/Microsoft.NETCore.App/2.0.0/System.Private.CoreLib.dll -r:/usr/share/dotnet/shared/Microsoft.NETCore.App/2.0.0/System.Console.dll -r:/usr/share/dotnet/shared/Microsoft.NETCore.App/2.0.0/System.Runtime.dll HelloWorld.cs
Microsoft (R) Visual C# Compiler version 2.3.2.61921 (ad0efbb6)
Copyright (C) Microsoft Corporation. All rights reserved.

real    0m0.890s
user    0m0.641s
sys     0m0.250s

ls -li
total 4
 4785074604720852 -rw-rw-rw- 1 developer developer  178 Dec  7 15:07 HelloWorld.cs
11821949022487213 -rw-rw-rw- 1 developer developer 4096 Dec  7 15:13 HelloWorld.exe
</code>```

The required dependencies, which are passed to the compiler, are different on different platforms, i.e. on Windows it is enough to pass System.Runtime.dll and System.Console.dll while on Ubuntu 16.04 it is necessary to pass in addition System.Private.CoreLib.dll. Different SDK versions will have Roslyn and command line drivers located in different places - the SDK layout changes between versions - and the newest 2.2.2 SDK ships with csc.dll and vbc.dll instead of csc.exe and vbc.exe. Therefore, before using this method it is necessary to check your SDK layout.

Detailed explanation

The Roslyn compiler was designed in a bit different way than the previously used csc.exe and vbc.exe compilers. First of all, Roslyn is written in C# and VB.NET and is a managed .NET application. On Windows it used mainly as a common service running in a server process VBCSCompiler.exe (.dll). However, Roslyn ships with managed command line drivers, csc.exe and vbc.exe (the latest .NET SDK versions ship with csc.dll and vbc.dll) which can be used to compile source files directly from the command line. Anyway, it is exactly what the build system in .NET does, invoking Roslyn via the command line. Running a simple dotnet csc.exe -help command will print usage information which will guide in using the compiler directly from the command line (see the last listing).

The major difference between old native compilers and Roslyn is due to the fact that the latter is a managed application is a startup time. Roslyn, even after being compiled to R2R native assemblies (Ready To Run), would need to start by loading the whole .NET framework, initializing it and then loading Roslyn assemblies and starting the compilation process. It is always a bit slower than running the native compiler, however, as can be seen from above timings, not that much slower.

There was a new documentation article added to the corefx repository describing Advanced scenario - Build and run application code with csc/vbc and CoreRun. Anyone interested can use it as a guideline how to work at the low level of .NET Core.

```<code>    Microsoft (R) Visual C# Compiler version 2.3.2.61921 (ad0efbb6)
Copyright (C) Microsoft Corporation. All rights reserved.

                              Visual C# Compiler Options

                        - OUTPUT FILES -
 /out:<file>                   Specify output file name (default: base name of
                               file with main class or first file)
 /target:exe                   Build a console executable (default) (Short
                               form: /t:exe)
 /target:winexe                Build a Windows executable (Short form:
                               /t:winexe)
 /target:library               Build a library (Short form: /t:library)
 /target:module                Build a module that can be added to another
                               assembly (Short form: /t:module)
 /target:appcontainerexe       Build an Appcontainer executable (Short form:
                               /t:appcontainerexe)
 /target:winmdobj              Build a Windows Runtime intermediate file that
                               is consumed by WinMDExp (Short form: /t:winmdobj)
 /doc:<file>                   XML Documentation file to generate
 /refout:<file>                Reference assembly output to generate
 /platform:<string>            Limit which platforms this code can run on: x86,
                               Itanium, x64, arm, anycpu32bitpreferred, or
                               anycpu. The default is anycpu.

                        - INPUT FILES -
 /recurse:<wildcard>           Include all files in the current directory and
                               subdirectories according to the wildcard
                               specifications
 /reference:<alias>=<file>     Reference metadata from the specified assembly
                               file using the given alias (Short form: /r)
 /reference:<file list>        Reference metadata from the specified assembly
                               files (Short form: /r)
 /addmodule:<file list>        Link the specified modules into this assembly
 /link:<file list>             Embed metadata from the specified interop
                               assembly files (Short form: /l)
 /analyzer:<file list>         Run the analyzers from this assembly
                               (Short form: /a)
 /additionalfile:<file list>   Additional files that don't directly affect code
                               generation but may be used by analyzers for producing
                               errors or warnings.
 /embed                        Embed all source files in the PDB.
 /embed:<file list>            Embed specific files in the PDB

                        - RESOURCES -
 /win32res:<file>              Specify a Win32 resource file (.res)
 /win32icon:<file>             Use this icon for the output
 /win32manifest:<file>         Specify a Win32 manifest file (.xml)
 /nowin32manifest              Do not include the default Win32 manifest
 /resource:<resinfo>           Embed the specified resource (Short form: /res)
 /linkresource:<resinfo>       Link the specified resource to this assembly
                               (Short form: /linkres) Where the resinfo format
                               is <file>[,<string name>[,public|private]]

                        - CODE GENERATION -
 /debug[+|-]                   Emit debugging information
 /debug:{full|pdbonly|portable|embedded}
                               Specify debugging type ('full' is default,
                               'portable' is a cross-platform format,
                               'embedded' is a cross-platform format embedded into
                               the target .dll or .exe)
 /optimize[+|-]                Enable optimizations (Short form: /o)
 /deterministic                Produce a deterministic assembly
                               (including module version GUID and timestamp)
 /refonly                      Produce a reference assembly in place of the main output
 /instrument:TestCoverage      Produce an assembly instrumented to collect
                               coverage information
 /sourcelink:<file>            Source link info to embed into PDB.

                        - ERRORS AND WARNINGS -
 /warnaserror[+|-]             Report all warnings as errors
 /warnaserror[+|-]:<warn list> Report specific warnings as errors
 /warn:<n>                     Set warning level (0-4) (Short form: /w)
 /nowarn:<warn list>           Disable specific warning messages
 /ruleset:<file>               Specify a ruleset file that disables specific
                               diagnostics.
 /errorlog:<file>              Specify a file to log all compiler and analyzer
                               diagnostics.
 /reportanalyzer               Report additional analyzer information, such as
                               execution time.

                        - LANGUAGE -
 /checked[+|-]                 Generate overflow checks
 /unsafe[+|-]                  Allow 'unsafe' code
 /define:<symbol list>         Define conditional compilation symbol(s) (Short
                               form: /d)
 /langversion:<string>         Specify language version mode: ISO-1, ISO-2, 3,
                               4, 5, 6, 7, 7.1, Default, or Latest

                        - SECURITY -
 /delaysign[+|-]               Delay-sign the assembly using only the public
                               portion of the strong name key
 /publicsign[+|-]              Public-sign the assembly using only the public
                               portion of the strong name key
 /keyfile:<file>               Specify a strong name key file
 /keycontainer:<string>        Specify a strong name key container
 /highentropyva[+|-]           Enable high-entropy ASLR

                        - MISCELLANEOUS -
 @<file>                       Read response file for more options
 /help                         Display this usage message (Short form: /?)
 /nologo                       Suppress compiler copyright message
 /noconfig                     Do not auto include CSC.RSP file
 /parallel[+|-]                Concurrent build.
 /version                      Display the compiler version number and exit.

                        - ADVANCED -
 /baseaddress:<address>        Base address for the library to be built
 /checksumalgorithm:<alg>      Specify algorithm for calculating source file
                               checksum stored in PDB. Supported values are:
                               SHA1 (default) or SHA256.
 /codepage:<n>                 Specify the codepage to use when opening source
                               files
 /utf8output                   Output compiler messages in UTF-8 encoding
 /main:<type>                  Specify the type that contains the entry point
                               (ignore all other possible entry points) (Short
                               form: /m)
 /fullpaths                    Compiler generates fully qualified paths
 /filealign:<n>                Specify the alignment used for output file
                               sections
 /pathmap:<K1>=<V1>,<K2>=<V2>,...
                               Specify a mapping for source path names output by
                               the compiler.
 /pdb:<file>                   Specify debug information file name (default:
                               output file name with .pdb extension)
 /errorendlocation             Output line and column of the end location of
                               each error
 /preferreduilang              Specify the preferred output language name.
 /nostdlib[+|-]                Do not reference standard library (mscorlib.dll)
 /subsystemversion:<string>    Specify subsystem version of this assembly
 /lib:<file list>              Specify additional directories to search in for
                               references
 /errorreport:<string>         Specify how to handle internal compiler errors:
                               prompt, send, queue, or none. The default is
                               queue.
 /appconfig:<file>             Specify an application configuration file
                               containing assembly binding settings
 /moduleassemblyname:<string>  Name of the assembly which this module will be
                               a part of
 /modulename:<string>          Specify the name of the source module
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In old .NET we used to be able to run the csc compiler to compile a single .cs file or several files.

With .NET Core we have dotnet build that insists on having a proper project file. Is there a stand-alone  command line compiler that would allow to compile source code files without having a project (and listing referenced dependencies on the same command line)?

On Linux, when I have the old csc and the new .NET Core installed, I get these timings:

[root@li1742-80 test]# time dotnet build
Microsoft (R) Build Engine version 15.3.409.57025 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

  test -> /root/test/bin/Debug/netcoreapp2.0/test.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:03.94

real    0m7.027s
user    0m5.714s
sys     0m0.838s

[root@li1742-80 test]# time csc Program.cs
Microsoft (R) Visual C# Compiler version 2.3.0.61801 (3722bb71)
Copyright (C) Microsoft Corporation. All rights reserved.

real    0m0.613s
user    0m0.522s
sys     0m0.071s
[root@li1742-80 test]#

Note 7 seconds with .NET Core versus several hundred milliseconds with the old csc for the same file, Program.cs.

I'd like to be able to compile as fast with .NET Core as I used to be able with csc.

Body:
Yes, it is possible to compile a single file with csc or vbc compilers in .NET Core.

To invoke the Roslyn compiler directly it is necessary to use the command line driver csc.{exe|dll} and since Roslyn in contrast to the old csc.exe does not reference mscorlib.dll implicitly it is necessary to pass a reference to the required dependencies, i.e. System.Runtime and System.Private.CoreLib libraries and any other required references. The following listing shows how to compile the following Hello, World! program.

using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

Using WSL with Ubuntu 16.04 (Xenial Xerus) and dotnet-sdk-2.0.0 installed:

time dotnet /usr/share/dotnet/sdk/2.0.0/Roslyn/csc.exe -r:/usr/share/dotnet/shared/Microsoft.NETCore.App/2.0.0/System.Private.CoreLib.dll -r:/usr/share/dotnet/shared/Microsoft.NETCore.App/2.0.0/System.Console.dll -r:/usr/share/dotnet/shared/Microsoft.NETCore.App/2.0.0/System.Runtime.dll HelloWorld.cs
Microsoft (R) Visual C# Compiler version 2.3.2.61921 (ad0efbb6)
Copyright (C) Microsoft Corporation. All rights reserved.

real    0m0.890s
user    0m0.641s
sys     0m0.250s

ls -li
total 4
 4785074604720852 -rw-rw-rw- 1 developer developer  178 Dec  7 15:07 HelloWorld.cs
11821949022487213 -rw-rw-rw- 1 developer developer 4096 Dec  7 15:13 HelloWorld.exe

The required dependencies, which are passed to the compiler, are different on different platforms, i.e. on Windows it is enough to pass System.Runtime.dll and System.Console.dll while on Ubuntu 16.04 it is necessary to pass in addition System.Private.CoreLib.dll. Different SDK versions will have Roslyn and command line drivers located in different places - the SDK layout changes between versions - and the newest 2.2.2 SDK ships with csc.dll and vbc.dll instead of csc.exe and vbc.exe. Therefore, before using this method it is necessary to check your SDK layout.

Detailed explanation

The Roslyn compiler was designed in a bit different way than the previously used csc.exe and vbc.exe compilers. First of all, Roslyn is written in C# and VB.NET and is a managed .NET application. On Windows it used mainly as a common service running in a server process VBCSCompiler.exe (.dll). However, Roslyn ships with managed command line drivers, csc.exe and vbc.exe (the latest .NET SDK versions ship with csc.dll and vbc.dll) which can be used to compile source files directly from the command line. Anyway, it is exactly what the build system in .NET does, invoking Roslyn via the command line. Running a simple dotnet csc.exe -help command will print usage information which will guide in using the compiler directly from the command line (see the last listing).

The major difference between old native compilers and Roslyn is due to the fact that the latter is a managed application is a startup time. Roslyn, even after being compiled to R2R native assemblies (Ready To Run), would need to start by loading the whole .NET framework, initializing it and then loading Roslyn assemblies and starting the compilation process. It is always a bit slower than running the native compiler, however, as can be seen from above timings, not that much slower.

There was a new documentation article added to the corefx repository describing Advanced scenario - Build and run application code with csc/vbc and CoreRun. Anyone interested can use it as a guideline how to work at the low level of .NET Core.

    Microsoft (R) Visual C# Compiler version 2.3.2.61921 (ad0efbb6)
Copyright (C) Microsoft Corporation. All rights reserved.

                              Visual C# Compiler Options

                        - OUTPUT FILES -
 /out:<file>                   Specify output file name (default: base name of
                               file with main class or first file)
 /target:exe                   Build a console executable (default) (Short
                               form: /t:exe)
 /target:winexe                Build a Windows executable (Short form:
                               /t:winexe)
 /target:library               Build a library (Short form: /t:library)
 /target:module                Build a module that can be added to another
                               assembly (Short form: /t:module)
 /target:appcontainerexe       Build an Appcontainer executable (Short form:
                               /t:appcontainerexe)
 /target:winmdobj              Build a Windows Runtime intermediate file that
                               is consumed by WinMDExp (Short form: /t:winmdobj)
 /doc:<file>                   XML Documentation file to generate
 /refout:<file>                Reference assembly output to generate
 /platform:<string>            Limit which platforms this code can run on: x86,
                               Itanium, x64, arm, anycpu32bitpreferred, or
                               anycpu. The default is anycpu.

                        - INPUT FILES -
 /recurse:<wildcard>           Include all files in the current directory and
                               subdirectories according to the wildcard
                               specifications
 /reference:<alias>=<file>     Reference metadata from the specified assembly
                               file using the given alias (Short form: /r)
 /reference:<file list>        Reference metadata from the specified assembly
                               files (Short form: /r)
 /addmodule:<file list>        Link the specified modules into this assembly
 /link:<file list>             Embed metadata from the specified interop
                               assembly files (Short form: /l)
 /analyzer:<file list>         Run the analyzers from this assembly
                               (Short form: /a)
 /additionalfile:<file list>   Additional files that don't directly affect code
                               generation but may be used by analyzers for producing
                               errors or warnings.
 /embed                        Embed all source files in the PDB.
 /embed:<file list>            Embed specific files in the PDB

                        - RESOURCES -
 /win32res:<file>              Specify a Win32 resource file (.res)
 /win32icon:<file>             Use this icon for the output
 /win32manifest:<file>         Specify a Win32 manifest file (.xml)
 /nowin32manifest              Do not include the default Win32 manifest
 /resource:<resinfo>           Embed the specified resource (Short form: /res)
 /linkresource:<resinfo>       Link the specified resource to this assembly
                               (Short form: /linkres) Where the resinfo format
                               is <file>[,<string name>[,public|private]]

                        - CODE GENERATION -
 /debug[+|-]                   Emit debugging information
 /debug:{full|pdbonly|portable|embedded}
                               Specify debugging type ('full' is default,
                               'portable' is a cross-platform format,
                               'embedded' is a cross-platform format embedded into
                               the target .dll or .exe)
 /optimize[+|-]                Enable optimizations (Short form: /o)
 /deterministic                Produce a deterministic assembly
                               (including module version GUID and timestamp)
 /refonly                      Produce a reference assembly in place of the main output
 /instrument:TestCoverage      Produce an assembly instrumented to collect
                               coverage information
 /sourcelink:<file>            Source link info to embed into PDB.

                        - ERRORS AND WARNINGS -
 /warnaserror[+|-]             Report all warnings as errors
 /warnaserror[+|-]:<warn list> Report specific warnings as errors
 /warn:<n>                     Set warning level (0-4) (Short form: /w)
 /nowarn:<warn list>           Disable specific warning messages
 /ruleset:<file>               Specify a ruleset file that disables specific
                               diagnostics.
 /errorlog:<file>              Specify a file to log all compiler and analyzer
                               diagnostics.
 /reportanalyzer               Report additional analyzer information, such as
                               execution time.

                        - LANGUAGE -
 /checked[+|-]                 Generate overflow checks
 /unsafe[+|-]                  Allow 'unsafe' code
 /define:<symbol list>         Define conditional compilation symbol(s) (Short
                               form: /d)
 /langversion:<string>         Specify language version mode: ISO-1, ISO-2, 3,
                               4, 5, 6, 7, 7.1, Default, or Latest

                        - SECURITY -
 /delaysign[+|-]               Delay-sign the assembly using only the public
                               portion of the strong name key
 /publicsign[+|-]              Public-sign the assembly using only the public
                               portion of the strong name key
 /keyfile:<file>               Specify a strong name key file
 /keycontainer:<string>        Specify a strong name key container
 /highentropyva[+|-]           Enable high-entropy ASLR

                        - MISCELLANEOUS -
 @<file>                       Read response file for more options
 /help                         Display this usage message (Short form: /?)
 /nologo                       Suppress compiler copyright message
 /noconfig                     Do not auto include CSC.RSP file
 /parallel[+|-]                Concurrent build.
 /version                      Display the compiler version number and exit.

                        - ADVANCED -
 /baseaddress:<address>        Base address for the library to be built
 /checksumalgorithm:<alg>      Specify algorithm for calculating source file
                               checksum stored in PDB. Supported values are:
                               SHA1 (default) or SHA256.
 /codepage:<n>                 Specify the codepage to use when opening source
                               files
 /utf8output                   Output compiler messages in UTF-8 encoding
 /main:<type>                  Specify the type that contains the entry point
                               (ignore all other possible entry points) (Short
                               form: /m)
 /fullpaths                    Compiler generates fully qualified paths
 /filealign:<n>                Specify the alignment used for output file
                               sections
 /pathmap:<K1>=<V1>,<K2>=<V2>,...
                               Specify a mapping for source path names output by
                               the compiler.
 /pdb:<file>                   Specify debug information file name (default:
                               output file name with .pdb extension)
 /errorendlocation             Output line and column of the end location of
                               each error
 /preferreduilang              Specify the preferred output language name.
 /nostdlib[+|-]                Do not reference standard library (mscorlib.dll)
 /subsystemversion:<string>    Specify subsystem version of this assembly
 /lib:<file list>              Specify additional directories to search in for
                               references
 /errorreport:<string>         Specify how to handle internal compiler errors:
                               prompt, send, queue, or none. The default is
                               queue.
 /appconfig:<file>             Specify an application configuration file
                               containing assembly binding settings
 /moduleassemblyname:<string>  Name of the assembly which this module will be
                               a part of
 /modulename:<string>          Specify the name of the source module


问:
Multiple key names, same pair value
I'm trying to setup an object literal in a JavaScript script that has a key with multiple names. referring to the same object value i.e. something like these that I have already tried:

```<code>var holidays: {
    "thanksgiving day", "thanksgiving", "t-day": {
        someValue : "foo"
    }
}

var holidays: {
    ["thanksgiving day", "thanksgiving", "t-day"]: {
        someValue : "foo"
    }
}
</code>```

Is there a way I can accomplish this?

答:
Same reponse (ES6 Proxy, RegExp), but in a shorter way (and significantly less legible)</p>

```<code>let align = new Proxy({

    'start|top|left': -1,
    'middle|center': 0,
    'end|bottom|right': 1,

}, { get: (t, p) => Object.keys(t).reduce((r, v) => r !== undefined ? r : (new RegExp(v).test(p) ? t[v] : undefined), undefined) })

align.start     // -1
align.top       // -1
align.left      // -1

align.middle    // 0
align.center    // 0

align.end       // 1
align.bottom    // 1
align.right     // 1
</code>```

Title: Multiple key names, same pair value

Body:
I'm trying to setup an object literal in a JavaScript script that has a key with multiple names. referring to the same object value i.e. something like these that I have already tried:

var holidays: {
    "thanksgiving day", "thanksgiving", "t-day": {
        someValue : "foo"
    }
}

var holidays: {
    ["thanksgiving day", "thanksgiving", "t-day"]: {
        someValue : "foo"
    }
}

Is there a way I can accomplish this?

Body:
Same reponse (ES6 Proxy, RegExp), but in a shorter way (and significantly less legible)

let align = new Proxy({

    'start|top|left': -1,
    'middle|center': 0,
    'end|bottom|right': 1,

}, { get: (t, p) => Object.keys(t).reduce((r, v) => r !== undefined ? r : (new RegExp(v).test(p) ? t[v] : undefined), undefined) })

align.start     // -1
align.top       // -1
align.left      // -1

align.middle    // 0
align.center    // 0

align.end       // 1
align.bottom    // 1
align.right     // 1


问:
Predefined squareroot function without using sqrt() from math.h in C
Homework question:

Cygwin GNU GDB

Cygwin GNU GCC

Attempting to establish the length of the hypotenuse C from the square root of A power of 2 and B power of 2.

Example input:

Enter the length of two sides of a right-angled triangle: 2.25  8.33

Answer:

The length of the hypotenuse is: 8.628523

Question: when I specify the same input as above, the result is not the same - output is 19.84.9596

Full code below:

```<code>float squareRoots(float *s)
{
    float cx;
    float nx;
    float e;

    cx = 1;
    nx = (cx +*s/cx)/2;
    e = nx - cx;
    cx = nx;

    if (e*e > 0.001)
    {
        nx = (cx +*s/cx)/2;
        return nx;
    } else {
        return nx;
    }
}

float hypotenuse(float *a, float *b)
{
    float c;
    //raise a to power of 2
    *a = (*a * *a);
    *b = (*b * *b);
    //add a and b
    float y = *a + *b;
    c = squareRoots(&y);

    return c;
}

int main()
{
    float x,y;

    printf("Enter the length of two sides of a right-angled triangle:");
    scanf("%f %f", &x, &y);
    float k=hypotenuse(&x,&y);

    printf("The length of the hypotenuse is: %f", k);

    exit(0);
}
</code>```

答:
Want a super-duper square root implementation?  Check out John Carmack's magic square root from Quake III.</p>

```<code>float Q_rsqrt( float number )
{
  long i;
  float x2, y;
  const float threehalfs = 1.5F;

  x2 = number * 0.5F;
  y  = number;
  i  = * ( long * ) &y;  // evil floating point bit level hacking
  i  = 0x5f3759df - ( i >> 1 ); // what the ****?
  y  = * ( float * ) &i;
  y  = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
  // y  = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed

  #ifndef Q3_VM
  #ifdef __linux__
    assert( !isnan(y) ); // bk010122 - FPE?
  #endif
  #endif
  return y;
}
</code>```

OwnerDisplayName: Nefeli

LastEditorDisplayName: Nefeli

Body:
Homework question:

Cygwin GNU GDB

Cygwin GNU GCC

Attempting to establish the length of the hypotenuse C from the square root of A power of 2 and B power of 2.

Example input:

Enter the length of two sides of a right-angled triangle: 2.25  8.33

Answer:

The length of the hypotenuse is: 8.628523

Question: when I specify the same input as above, the result is not the same - output is 19.84.9596

Full code below:

float squareRoots(float *s)
{
    float cx;
    float nx;
    float e;

    cx = 1;
    nx = (cx +*s/cx)/2;
    e = nx - cx;
    cx = nx;

    if (e*e > 0.001)
    {
        nx = (cx +*s/cx)/2;
        return nx;
    } else {
        return nx;
    }
}

float hypotenuse(float *a, float *b)
{
    float c;
    //raise a to power of 2
    *a = (*a * *a);
    *b = (*b * *b);
    //add a and b
    float y = *a + *b;
    c = squareRoots(&y);

    return c;
}

int main()
{
    float x,y;

    printf("Enter the length of two sides of a right-angled triangle:");
    scanf("%f %f", &x, &y);
    float k=hypotenuse(&x,&y);

    printf("The length of the hypotenuse is: %f", k);

    exit(0);
}

Body:
Want a super-duper square root implementation?  Check out John Carmack's magic square root from Quake III.

float Q_rsqrt( float number )
{
  long i;
  float x2, y;
  const float threehalfs = 1.5F;

  x2 = number * 0.5F;
  y  = number;
  i  = * ( long * ) &y;  // evil floating point bit level hacking
  i  = 0x5f3759df - ( i >> 1 ); // what the ****?
  y  = * ( float * ) &i;
  y  = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
  // y  = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed

  #ifndef Q3_VM
  #ifdef __linux__
    assert( !isnan(y) ); // bk010122 - FPE?
  #endif
  #endif
  return y;
}

OwnerDisplayName: cletus