问:
css margin: auto issue in footer
My problem is to split the space inside my footer bar in 3 part (each with same width)

footer {
  width: 100%;
  /*breite: 100%*/
  padding: 0;
  margin: 0;
  background-color: darkcyan;
  /*Hintergrundfarbe*/
  margin-bottom: 0;
  bottom: 0;
}

.footer-items {
  width: 80%;
  margin: auto;
  display: flex;
  /*bringt alle Teile in eine Linie*/
  text-align: center;
  /*zentriert ganzen Text im footer*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="footer-items">

  <div class="company-items">
    <h3 class="company">Company</h3>
    <ul>
      <li>Text1</li>
      <li>Text2</li>
      <li>Text3</li>
    </ul>
  </div>

  <div class="social-items">
    <h3 class="social">Social</h3>
    <ul>
      <li><a>Twitter</a></li>
      <li><a>Instagram</a></li>
      <li><a>Reddit</a></li>
    </ul>
  </div>

  <div class="other-items">
    <h3 class="text">Text4</h3>
    <ul>
      <li><a>other1</a></li>
      <li><a>other2</a></li>
    </ul>
  </div>

</div></code>```

If I try to do sth like margin-left: 33% for my 3 items in footer this is not gonna work.

thanks for your help

答:
You can do it using flex properties of CSS and I have added snippet below. Please check :

footer{
            width: 100%; /*breite: 100%*/
            padding: 0;
            margin: 0;
            background-color: darkcyan; /*Hintergrundfarbe*/
            margin-bottom: 0;
            bottom: 0;
          }

          .footer-items{
            width: 80%;
            margin: auto;
            display: flex; /*bringt alle Teile in eine Linie*/
            text-align: center; /*zentriert ganzen Text im footer*/
            flex-direction: row;
            justify-content: space-between;
            align-items: flex-start;
          }

          .footer-items .company-items, .footer-items .social-items, .footer-items .other-items {
            display: block;
            width: 100%;
            text-align: left;
          }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="footer-items">
        <div class="company-items">
          <h3 class="company">Company</h3>
            <ul>
              <li>Text1</li>
              <li>Text2</li>
              <li>Text3</li>
            </ul>
        </div>

        <div class="social-items">
          <h3 class="social">Social</h3>
            <ul>
              <li><a>Twitter</a></li>
              <li><a>Instagram</a></li>
              <li><a>Reddit</a></li>
            </ul>
        </div>

        <div class="other-items">
          <h3 class="text">Text4</h3>
            <ul>
              <li><a>other1</a></li>
              <li><a>other2</a></li>
            </ul>
        </div>
  </div> </code>```

Title: css margin: auto issue in footer

Body:
My problem is to split the space inside my footer bar in 3 part (each with same width)

footer {
  width: 100%;
  /*breite: 100%*/
  padding: 0;
  margin: 0;
  background-color: darkcyan;
  /*Hintergrundfarbe*/
  margin-bottom: 0;
  bottom: 0;
}

.footer-items {
  width: 80%;
  margin: auto;
  display: flex;
  /*bringt alle Teile in eine Linie*/
  text-align: center;
  /*zentriert ganzen Text im footer*/
}

Company

Text1

Text2

Text3

Social

Twitter

Instagram

Reddit

Text4

other1

other2

If I try to do sth like margin-left: 33% for my 3 items in footer this is not gonna work.

thanks for your help

Body:
You can do it using flex properties of CSS and I have added snippet below. Please check :

footer{
            width: 100%; /*breite: 100%*/
            padding: 0;
            margin: 0;
            background-color: darkcyan; /*Hintergrundfarbe*/
            margin-bottom: 0;
            bottom: 0;
          }

          .footer-items{
            width: 80%;
            margin: auto;
            display: flex; /*bringt alle Teile in eine Linie*/
            text-align: center; /*zentriert ganzen Text im footer*/
            flex-direction: row;
            justify-content: space-between;
            align-items: flex-start;
          }

          .footer-items .company-items, .footer-items .social-items, .footer-items .other-items {
            display: block;
            width: 100%;
            text-align: left;
          }

    <div class="footer-items">
        <div class="company-items">
          <h3 class="company">Company</h3>
            <ul>
              <li><a href="text1.html">Text1</a></li>
              <li><a href="text2.html">Text2</a></li>
              <li><a href="text3.html">Text3</a></li>
            </ul>
        </div>

        <div class="social-items">
          <h3 class="social">Social</h3>
            <ul>
              <li><a>Twitter</a></li>
              <li><a>Instagram</a></li>
              <li><a>Reddit</a></li>
            </ul>
        </div>

        <div class="other-items">
          <h3 class="text">Text4</h3>
            <ul>
              <li><a>other1</a></li>
              <li><a>other2</a></li>
            </ul>
        </div>
  </div>


来源: stackexchange

问:
I want to make a have a datepicker(calendar) to filter my database record base on timestamps (Laravel 6)
How to add a date picker for my reports data (Laravel6)
I still have no idea on where to start.

Here is my  report controller(index):

```<code>  public function index()
{
    $reports=Report::orderBy('id', 'DESC')->paginate(10);

    return view('reports.index',['reports' => $reports]);
}
</code>```

Here is my index on my report.index html

```<code><div class="table-responsive">
                    <table class="table align-items-center table-flush">
                        <thead class="thead-light">
                        <tr>
                            <th scope="col">Name</th>
                            <th scope="col">Student number</th>
                            <th scope="col">Transaction</th>
                            <th scope="col">Remarks</th>
                            <th scope="col">Queue number</th>
                            <th scope="col">Created at</th>
                            <th scope="col"></th>
                        </tr>
                        </thead>
                        <tbody>
                        @foreach ($reports as $report)
                            <tr>
                                <td>{{ $report->name}}</td>
                                <td>{{ $report->snumber}}</td>
                                <td>{{ $report->transaction}}</td>
                                <td>{{ $report->remarks}}</td>
                                <td>{{ $report->letter}}-{{ $report->number}}</td>
                                <td>{{ $report->created_at }}</td>

                            </tr>
                        @endforeach
                        </tbody>
                    </table>
                </div>
                <div class="card-footer py-4">
                    <nav class="d-flex justify-content-end" aria-label="...">
                        {{ $reports->links() }}
                    </nav>
                </div>
</code>```

My database table look like this:

```<code> Schema::create('reports', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('snumber');
        $table->string('name');
        $table->string('email');
        $table->string('mobile');
        $table->string('department');
        $table->string('letter');
        $table->integer('number');
        $table->string('transaction');
        $table->string('remarks')->nullable();
        $table->timestamps();
        $table->softDeletes();
    });
</code>```

Please help me. Thanks!

答:
To filter your data first you have to put your datepicker within form tag outside of your table which contains data.

If you want to use ajax call then pass that form value which contains filter date and in same index method you can check that this call is ajax call or not.

If ajax call then override variable with filtered data.

Something like this,

```<code>$reports=Report::orderBy('id', 'DESC')->paginate(10);
if($request->ajax()){
        $reports=Report::orderBy('id', 'DESC')->whereDate('created_at', today())->paginate(10);
}
return view('reports.index',['reports' => $reports]);
</code>```

if you dont want to use ajax call and want to load page, then you can pass the data and check that it exist or not, something like this,

```<code>$reports=Report::orderBy('id', 'DESC')
->when(! empty(\request('filterdate')), function($q) {
    return $q->whereDate('created_at', today());
})
->paginate(10);
return view('reports.index',['reports' => $reports]);
</code>```

It will only filter date when filterdate is not empty.

Hope this helps :)

ContentLicense: CC BY-SA 4.0

Body:
How to add a date picker for my reports data (Laravel6)
I still have no idea on where to start.

Here is my  report controller(index):

  public function index()
{
    $reports=Report::orderBy('id', 'DESC')->paginate(10);

    return view('reports.index',['reports' => $reports]);
}

Here is my index on my report.index html

                            Name
                            Student number
                            Transaction
                            Remarks
                            Queue number
                            Created at

                        @foreach ($reports as $report)

                                {{ $report->name}}
                                {{ $report->snumber}}
                                {{ $report->transaction}}
                                {{ $report->remarks}}
                                {{ $report->letter}}-{{ $report->number}}
                                {{ $report->created_at }}

                        @endforeach

                        {{ $reports->links() }}

My database table look like this:

 Schema::create('reports', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('snumber');
        $table->string('name');
        $table->string('email');
        $table->string('mobile');
        $table->string('department');
        $table->string('letter');
        $table->integer('number');
        $table->string('transaction');
        $table->string('remarks')->nullable();
        $table->timestamps();
        $table->softDeletes();
    });

Please help me. Thanks!

Body:
To filter your data first you have to put your datepicker within form tag outside of your table which contains data.

If you want to use ajax call then pass that form value which contains filter date and in same index method you can check that this call is ajax call or not.

If ajax call then override variable with filtered data.

Something like this,

$reports=Report::orderBy('id', 'DESC')->paginate(10);
if($request->ajax()){
        $reports=Report::orderBy('id', 'DESC')->whereDate('created_at', today())->paginate(10);
}
return view('reports.index',['reports' => $reports]);

if you dont want to use ajax call and want to load page, then you can pass the data and check that it exist or not, something like this,

$reports=Report::orderBy('id', 'DESC')
->when(! empty(\request('filterdate')), function($q) {
    return $q->whereDate('created_at', today());
})
->paginate(10);
return view('reports.index',['reports' => $reports]);

It will only filter date when filterdate is not empty.

Hope this helps :)


问:
URLDownloadToCacheFile failed with HRESULT '-2146697208'
I am I am having a problem installing a ClickOnce vb.net windows forms application. I have tried few solutions suggested here on this site and none have helped.

My application is built with VS2010(.NET 4.0 Framework) and is deployed to a local folder C:\inetpub\wwwroot\AppName on my dev machine but I have specified the following address as the install address https://localhost/AppName/

I am getting following error when I hit "Run" button in IE.
"Warn if changing between secure to non secure mode" is unchecked in IE.
Any help with this will be greatly appreciated. Complete error message can be seen below.

```<code>The following properties have been set:
Property: [AdminUser] = true {boolean}
Property: [InstallMode] = HomeSite {string}
Property: [ProcessorArchitecture] = AMD64 {string}
Property: [VersionNT] = 6.1.1 {version}
Running checks for package 'Microsoft .NET Framework 4 (x86 and x64)', phase BuildList
Reading value 'Version' of registry key 'HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full'
Read string value '4.5.51209'
Setting value '4.5.51209 {string}' for property 'DotNet40Full_TargetVersion'
The following properties have been set for package 'Microsoft .NET Framework 4 (x86 and x64)':
Property: [DotNet40Full_TargetVersion] = 4.5.51209 {string}
Running checks for command 'DotNetFX40\dotNetFx40_Full_x86_x64.exe'
Result of running operator 'ValueEqualTo' on property 'InstallMode' and value 'HomeSite': true
Result of checks for command 'DotNetFX40\dotNetFx40_Full_x86_x64.exe' is 'Bypass'
Running checks for command 'DotNetFX40\dotNetFx40_Full_setup.exe'
Result of running operator 'ValueNotEqualTo' on property 'InstallMode' and value 'HomeSite': false
Result of running operator 'VersionGreaterThanOrEqualTo' on property 'DotNet40Full_TargetVersion' and value '4.0.30129': true
Result of checks for command 'DotNetFX40\dotNetFx40_Full_setup.exe' is 'Bypass'
'Microsoft .NET Framework 4 (x86 and x64)' RunCheck result: No Install Needed
Running checks for package 'Microsoft .NET Framework 4 Client Profile (x86 and x64)', phase BuildList
Reading value 'Version' of registry key 'HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Client'
Read string value '4.5.51209'
Setting value '4.5.51209 {string}' for property 'DotNet40Client_TargetVersion'
The following properties have been set for package 'Microsoft .NET Framework 4 Client Profile (x86 and x64)':
Property: [DotNet40Client_TargetVersion] = 4.5.51209 {string}
Running checks for command 'DotNetFX40Client\dotNetFx40_Client_x86_x64.exe'
Result of running operator 'ValueEqualTo' on property 'InstallMode' and value 'HomeSite': true
Result of checks for command 'DotNetFX40Client\dotNetFx40_Client_x86_x64.exe' is 'Bypass'
Running checks for command 'DotNetFX40Client\dotNetFx40_Client_setup.exe'
Result of running operator 'ValueNotEqualTo' on property 'InstallMode' and value 'HomeSite': false
Result of running operator 'VersionGreaterThanOrEqualTo' on property 'DotNet40Client_TargetVersion' and value '4.0.30129': true
Result of checks for command 'DotNetFX40Client\dotNetFx40_Client_setup.exe' is 'Bypass'
'Microsoft .NET Framework 4 Client Profile (x86 and x64)' RunCheck result: No Install Needed
Launching Application.
URLDownloadToCacheFile failed with HRESULT '-2146697210'
Error: An error occurred trying to download 'http://MachineName:90/publish.htm/AssemblyName.application'
</code>```

答: This error usually occurs due to settings in Internet Explorer. Open IE > Options > Security tab. Try add URL to Trusted Sites or lower security settings for Local Intranet. </p>

ContentLicense: CC BY-SA 3.0

Body:
I am I am having a problem installing a ClickOnce vb.net windows forms application. I have tried few solutions suggested here on this site and none have helped.

My application is built with VS2010(.NET 4.0 Framework) and is deployed to a local folder C:\inetpub\wwwroot\AppName on my dev machine but I have specified the following address as the install address https://localhost/AppName/

I am getting following error when I hit "Run" button in IE.
"Warn if changing between secure to non secure mode" is unchecked in IE.
Any help with this will be greatly appreciated. Complete error message can be seen below.

The following properties have been set:
Property: [AdminUser] = true {boolean}
Property: [InstallMode] = HomeSite {string}
Property: [ProcessorArchitecture] = AMD64 {string}
Property: [VersionNT] = 6.1.1 {version}
Running checks for package 'Microsoft .NET Framework 4 (x86 and x64)', phase BuildList
Reading value 'Version' of registry key 'HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full'
Read string value '4.5.51209'
Setting value '4.5.51209 {string}' for property 'DotNet40Full_TargetVersion'
The following properties have been set for package 'Microsoft .NET Framework 4 (x86 and x64)':
Property: [DotNet40Full_TargetVersion] = 4.5.51209 {string}
Running checks for command 'DotNetFX40\dotNetFx40_Full_x86_x64.exe'
Result of running operator 'ValueEqualTo' on property 'InstallMode' and value 'HomeSite': true
Result of checks for command 'DotNetFX40\dotNetFx40_Full_x86_x64.exe' is 'Bypass'
Running checks for command 'DotNetFX40\dotNetFx40_Full_setup.exe'
Result of running operator 'ValueNotEqualTo' on property 'InstallMode' and value 'HomeSite': false
Result of running operator 'VersionGreaterThanOrEqualTo' on property 'DotNet40Full_TargetVersion' and value '4.0.30129': true
Result of checks for command 'DotNetFX40\dotNetFx40_Full_setup.exe' is 'Bypass'
'Microsoft .NET Framework 4 (x86 and x64)' RunCheck result: No Install Needed
Running checks for package 'Microsoft .NET Framework 4 Client Profile (x86 and x64)', phase BuildList
Reading value 'Version' of registry key 'HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Client'
Read string value '4.5.51209'
Setting value '4.5.51209 {string}' for property 'DotNet40Client_TargetVersion'
The following properties have been set for package 'Microsoft .NET Framework 4 Client Profile (x86 and x64)':
Property: [DotNet40Client_TargetVersion] = 4.5.51209 {string}
Running checks for command 'DotNetFX40Client\dotNetFx40_Client_x86_x64.exe'
Result of running operator 'ValueEqualTo' on property 'InstallMode' and value 'HomeSite': true
Result of checks for command 'DotNetFX40Client\dotNetFx40_Client_x86_x64.exe' is 'Bypass'
Running checks for command 'DotNetFX40Client\dotNetFx40_Client_setup.exe'
Result of running operator 'ValueNotEqualTo' on property 'InstallMode' and value 'HomeSite': false
Result of running operator 'VersionGreaterThanOrEqualTo' on property 'DotNet40Client_TargetVersion' and value '4.0.30129': true
Result of checks for command 'DotNetFX40Client\dotNetFx40_Client_setup.exe' is 'Bypass'
'Microsoft .NET Framework 4 Client Profile (x86 and x64)' RunCheck result: No Install Needed
Launching Application.
URLDownloadToCacheFile failed with HRESULT '-2146697210'
Error: An error occurred trying to download 'http://MachineName:90/publish.htm/AssemblyName.application'


答:
The script is probably designed to lure users to a site containing malware and browser exploits.

The reason that you're repeatedly being infected is because somewhere in your codebase there is a vulnerability. I suspect you've got an unprotected or broken file upload page that allows any old file to be uploaded (including scripts) and then executed. Once it's done infecting your files it probably delete's itself.

I would have a trawl through your web server log files at around the time the infection happens and look for suspicious activity for any pages that allow users to upload content.

Title: What does this script do?

Body:
Would anybody be able to tell me what the below script does? It keeps injecting itself into our site about every two weeks (always between Sundays and Mondays). We've reloaded our "clean" site dozens of times but it just keeps happening. We've installed and made every security recommendation that we've read but it just keeps getting into all of our index.html files and a few of our php files.

Anybody have any idea of what it does or where it comes from? We could really use some help!


问:
Stack jquery in expressJs
I'm looking for a way to stack jquery from the express app.js file.

Maybe this is not possible but I need to use jquery in the app.js which modifies the html file.

Example:

app.js

const express = require('express')
const app = express()
const $ = global.jQuery = require( 'jquery' );

app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname+'/index.html'));
  $("#click").click(function(e){
        console.log('click');
    })
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})
```

<p><strong>index.html</strong></p>

<pre class="lang-html prettyprint-override"><code><!doctype html>
<html>
<head>
  <title>Express - Jquery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
    <button id="click" type="button">Click</button>
</body>
</html>
</code>```

Maybe I'm using the wrong method...

If someone has already done this

答:
This code belongs client side, not server side:

```<code>$("#click").click(function(e){
    console.log('click');
})
</code>```

You'd put it in your index.html.  (Or in an external script referenced by your index.html.)  For example:

```<code><!doctype html>
<html>
<head>
  <title>Express - Jquery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
    <button id="click" type="button">Click</button>
</body>
<script type="text/javascript">
    $("#click").click(function(e){
        console.log('click');
    });
</script>
</html>
</code>```

The server-side code has no concept of the in-browser DOM.  It's just returning the page to the client as a response to the HTTP request it received.  The client-side JavaScript on that page is what interacts with the DOM in the browser.

Title: Stack jquery in expressJs

Body:
I'm looking for a way to stack jquery from the express app.js file.

Maybe this is not possible but I need to use jquery in the app.js which modifies the html file.

Example:

app.js

const express = require('express')
const app = express()
const $ = global.jQuery = require( 'jquery' );

app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname+'/index.html'));
  $("#click").click(function(e){
        console.log('click');
    })
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

index.html

<!doctype html>

  <title>Express - Jquery</title>

    <button id="click" type="button">Click</button>

Maybe I'm using the wrong method...

If someone has already done this

Body:
This code belongs client side, not server side:

$("#click").click(function(e){
    console.log('click');
})

You'd put it in your index.html.  (Or in an external script referenced by your index.html.)  For example:

<!doctype html>
<html>
<head>
  <title>Express - Jquery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
    <button id="click" type="button">Click</button>
</body>
<script type="text/javascript">
    $("#click").click(function(e){
        console.log('click');
    });
</script>
</html>

The server-side code has no concept of the in-browser DOM.  It's just returning the page to the client as a response to the HTTP request it received.  The client-side JavaScript on that page is what interacts with the DOM in the browser.


问:
CodingBat starOut, why using substring won't work correctly
I am solving coding challenge on CodingBat.com. Here is the question:

Given a string and a non-empty word string, return a version of the
  original String where all chars have been replaced by pluses ("+"),
  except for appearances of the word string which are preserved
  unchanged.

```<code>plusOut("12xy34", "xy") → "++xy++"
plusOut("12xy34", "1") → "1+++++"
plusOut("12xy34xyabcxy", "xy") → "++xy++xy+++xy"
</code>```

Here is my attempted solution:

```<code>public String plusOut(String str, String word)
{
  String ret = "";
  for (int i = 0; i < str.length() - word.length() + 1; ++i) {
    if (str.substring(i, i + word.length()).equals(word))
      ret += word;
    else
      ret += "+";
  }
  return ret;
}
</code>```

But is giving wrong outputs: giving too many plus signs. I don't understand why this shouldn't work. I suspect that the substring method is not returning enough matches, so the plus sign is appended. But I don't see why this maybe so.

答:
Do it like this :</p>

```<code>public static String plusOut(String str, String word)
{
    String ret = "";
    int i;
    for (i = 0; i < str.length() - word.length() +1 ; i++) {
        if (str.substring(i, i + word.length()).equals(word)) {
            ret += word;
            i += word.length() - 1;
        }
        else
            ret += "+";
    }
    while (i < str.length()) {
        ret += "+";
        i++;
    }

    return ret;
}
</code>```

Body:
I am solving coding challenge on CodingBat.com. Here is the question:

Given a string and a non-empty word string, return a version of the
  original String where all chars have been replaced by pluses ("+"),
  except for appearances of the word string which are preserved
  unchanged.

plusOut("12xy34", "xy") → "++xy++"
plusOut("12xy34", "1") → "1+++++"
plusOut("12xy34xyabcxy", "xy") → "++xy++xy+++xy"

Here is my attempted solution:

public String plusOut(String str, String word)
{
  String ret = "";
  for (int i = 0; i < str.length() - word.length() + 1; ++i) {
    if (str.substring(i, i + word.length()).equals(word))
      ret += word;
    else
      ret += "+";
  }
  return ret;
}

But is giving wrong outputs: giving too many plus signs. I don't understand why this shouldn't work. I suspect that the substring method is not returning enough matches, so the plus sign is appended. But I don't see why this maybe so.

Body:
Do it like this :

public static String plusOut(String str, String word)
{
    String ret = "";
    int i;
    for (i = 0; i < str.length() - word.length() +1 ; i++) {
        if (str.substring(i, i + word.length()).equals(word)) {
            ret += word;
            i += word.length() - 1;
        }
        else
            ret += "+";
    }
    while (i < str.length()) {
        ret += "+";
        i++;
    }

    return ret;
}


问:
HTML encoding issues - "Â" character showing up instead of " "
I've got a legacy app just starting to misbehave, for whatever reason I'm not sure.  It generates a bunch of HTML that gets turned into PDF reports by ActivePDF.

The process works like this:

Pull an HTML template from a DB with tokens in it to be replaced (e.g. "~CompanyName~", "~CustomerName~", etc.)

Replace the tokens with real data

Tidy the HTML with a simple regex function that property formats HTML tag attribute values (ensures quotation marks, etc, since ActivePDF's rendering engine hates anything but single quotes around attribute values)

Send off the HTML to a web service that creates the PDF.

Somewhere in that mess, the non-breaking spaces from the HTML template (the  s) are encoding as ISO-8859-1 so that they show up incorrectly as an "Â" character when viewing the document in a browser (FireFox).  ActivePDF pukes on these non-UTF8 characters.

My question: since I don't know where the problem stems from and don't have time to investigate it, is there an easy way to re-encode or find-and-replace the bad characters?  I've tried sending it through this little function I threw together, but it turns it all into gobbledegook doesn't change anything.

```<code>Private Shared Function ConvertToUTF8(ByVal html As String) As String
    Dim isoEncoding As Encoding = Encoding.GetEncoding("iso-8859-1")
    Dim source As Byte() = isoEncoding.GetBytes(html)
    Return Encoding.UTF8.GetString(Encoding.Convert(isoEncoding, Encoding.UTF8, source))
End Function
</code>```

Any ideas?

EDIT:

I'm getting by with this for now, though it hardly seems like a good solution:

```<code>Private Shared Function ReplaceNonASCIIChars(ByVal html As String) As String
    Return Regex.Replace(html, "[^\u0000-\u007F]", " ")
End Function
</code>```

答:
In my case this (a with caret) occurred in code I generated from visual studio using my own tool for generating code. It was easy to solve:

Select single spaces ( ) in the document. You should be able to see lots of single spaces that are looking different from the other single spaces, they are not selected. Select these other single spaces - they are the ones responsible for the unwanted characters in the browser. Go to Find and Replace with single space ( ). Done.

PS: It's easier to see all similar characters when you place the cursor on one or if you select it in VS2017+; I hope other IDEs may have similar features

Body:
I've got a legacy app just starting to misbehave, for whatever reason I'm not sure.  It generates a bunch of HTML that gets turned into PDF reports by ActivePDF.

The process works like this:

Pull an HTML template from a DB with tokens in it to be replaced (e.g. "~CompanyName~", "~CustomerName~", etc.)

Replace the tokens with real data

Tidy the HTML with a simple regex function that property formats HTML tag attribute values (ensures quotation marks, etc, since ActivePDF's rendering engine hates anything but single quotes around attribute values)

Send off the HTML to a web service that creates the PDF.

Somewhere in that mess, the non-breaking spaces from the HTML template (the  s) are encoding as ISO-8859-1 so that they show up incorrectly as an "Â" character when viewing the document in a browser (FireFox).  ActivePDF pukes on these non-UTF8 characters.

My question: since I don't know where the problem stems from and don't have time to investigate it, is there an easy way to re-encode or find-and-replace the bad characters?  I've tried sending it through this little function I threw together, but it turns it all into gobbledegook doesn't change anything.

Private Shared Function ConvertToUTF8(ByVal html As String) As String
    Dim isoEncoding As Encoding = Encoding.GetEncoding("iso-8859-1")
    Dim source As Byte() = isoEncoding.GetBytes(html)
    Return Encoding.UTF8.GetString(Encoding.Convert(isoEncoding, Encoding.UTF8, source))
End Function

Any ideas?

EDIT:

I'm getting by with this for now, though it hardly seems like a good solution:

Private Shared Function ReplaceNonASCIIChars(ByVal html As String) As String
    Return Regex.Replace(html, "[^\u0000-\u007F]", " ")
End Function


问:
Can not add language in ASP boilerplate (ASPNetZero)
I am trying to add Malay language in ASPNetZero framework, but its saying can not find module ./ms.js.

Following are the steps I have followed so far:

 1. Added a XML file for Malay language

 2. Added a new language in the DefaultLanguageCreator class

 3. Selected my language from the menu bar.

For detail error see below:

```<code>core.js:14597 ERROR Error: Uncaught (in promise): Error: Cannot find module './ms.js'
Error: Cannot find module './ms.js'
    at .*\.js$ namespace object:179
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:388)
    at Object.onInvoke (core.js:16156)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:387)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:138)
    at zone.js:872
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
    at Object.onInvokeTask (core.js:16147)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188)
    at resolvePromise (zone.js:814)
    at resolvePromise (zone.js:771)
    at zone.js:873
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
    at Object.onInvokeTask (core.js:16147)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188)
    at drainMicroTaskQueue (zone.js:595)
defaultErrorLogger @ core.js:14597
push../node_modules/@angular/core/fesm5/core.js.ErrorHandler.handleError @ core.js:14645
next @ core.js:16628
schedulerFn @ core.js:12609
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:196
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next @ Subscriber.js:134
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next @ Subscriber.js:77
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:54
push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @ Subject.js:47
push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js:12593
(anonymous) @ core.js:16178
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138
push../node_modules/@angular/core/fesm5/core.js.NgZone.runOutsideAngular @ core.js:16115
onHandleError @ core.js:16178
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.handleError @ zone.js:392
push../node_modules/zone.js/dist/zone.js.Zone.runGuarded @ zone.js:154
_loop_1 @ zone.js:677
api.microtaskDrainDone @ zone.js:686
drainMicroTaskQueue @ zone.js:602
Promise.then (async)
scheduleMicroTask @ zone.js:578
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:410
onScheduleTask @ zone.js:297
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:401
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:232
push../node_modules/zone.js/dist/zone.js.Zone.scheduleMicroTask @ zone.js:252
scheduleResolveOrReject @ zone.js:862
resolvePromise @ zone.js:808
(anonymous) @ zone.js:724
webpackJsonpCallback @ bootstrap:25
(anonymous) @ 892.js:1
</code>```

答:
In ASPNETZero date picker is in ngx-bootstrap, so in this lib they use moment.js,
your three steps are right but you missed some steps that explained below:

Add a XML file for Malay language (...\aspnet-core\src\YOURCOMPANY.Core\Localization\YOURCOMPANY\YOURCOMPANY.ms.xml)

Added a new language in the DefaultLanguageCreator class

First of all, in your angular project edit this file ...\angular\src\assets\appconfig.json, and add localMapping suitable conversion (to en for now), don't forget set this configuration to appconfig.production.json.

```<code>        "localeMappings": {
            "angular": [
              {
                "from": "ms",
                "to": "en"
              }
            ],
            "moment": [
              {
                "from": "ms",
                "to": "en"
              },
              ...
            ],...
</code>```

Then go this location : (...\angular\src\assets\ngx-bootstrap\ngx-bootstrap-locale-mapping.service.ts), map you culture like below:

const cultureMap = {
            'zh-Hans': 'zh-cn',
            'es-MX': 'es',
            'vi': 'en-gb',
            'ms': 'ms'
            // Add more here
        };
```

<p>
Set your module map:
</p>

```getModuleName(locale: string): string {
        const moduleNameMap = {
            'zh-Hans': 'zhCn',
            'es-MX': 'es',
            'pt-BR': 'ptBr',
            'vi': 'enGb',
            'ms': 'ms'

            // Add more here
        };
```

<p>You can map your culture like <strong>'ms': 'en'</strong>, if you do like this you will get your SPA date-picker in Georgian type, but if you want to change the moment of your date-pickers, you have to add your <strong>i18n</strong> overwrite, for doing this:</p>

<p>add this folder js file to (...\angular\src\assets\ngx-bootstrap\custom-i18n\ms.js)
you can find your moment.js culture on the net or simply edit other language to get your suitable moments.</p>

<p>finally, go to this file:
(...\angular\src\assets\ngx-bootstrap\ngx-bootstrap-datepicker-config.service.ts)
and change this function like below:</p>

<pre class="lang-js prettyprint-override"><code>static registerNgxBootstrapDatePickerLocales(): Promise<boolean> {
        if (abp.localization.currentLanguage.name === 'en') {
            return Promise.resolve(true);
        }

        let supportedLocale = new NgxBootstrapLocaleMappingService().map(abp.localization.currentLanguage.name).toLowerCase();
        let moduleLocaleName = new NgxBootstrapLocaleMappingService().getModuleName(abp.localization.currentLanguage.name);

        if (abp.localization.currentLanguage.name === 'ms') {
            return new Promise<boolean>((resolve, reject) => {
                import(`assets/ngx-bootstrap/custom-i18n/ms.js`)
                    .then(module => {
                        defineLocale(abp.localization.currentLanguage.name.toLowerCase(), module[`msLocale`]);
                        resolve(true);
                    }, reject);
            });
        }

        return new Promise<boolean>((resolve, reject) => {
            import(`ngx-bootstrap/chronos/esm5/i18n/${supportedLocale}.js`)
                .then(module => {
                    defineLocale(abp.localization.currentLanguage.name.toLowerCase(), module[`${moduleLocaleName}Locale`]);
                    resolve(true);
                }, reject);
        });
    }
</code>```

As you can see, in Promise ms.js file import function we call your ms.js module name as msLocale, this is an exported variable declared in your ms.js file.

If you can't find your moment culture js file in this link:
moment.js locales

Simply write yourself, this is a official tutorial:
moment.js customization

Body:
I am trying to add Malay language in ASPNetZero framework, but its saying can not find module ./ms.js.

Following are the steps I have followed so far:

 1. Added a XML file for Malay language

 2. Added a new language in the DefaultLanguageCreator class

 3. Selected my language from the menu bar.

For detail error see below:

core.js:14597 ERROR Error: Uncaught (in promise): Error: Cannot find module './ms.js'
Error: Cannot find module './ms.js'
    at .*\.js$ namespace object:179
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:388)
    at Object.onInvoke (core.js:16156)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:387)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:138)
    at zone.js:872
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
    at Object.onInvokeTask (core.js:16147)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188)
    at resolvePromise (zone.js:814)
    at resolvePromise (zone.js:771)
    at zone.js:873
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
    at Object.onInvokeTask (core.js:16147)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188)
    at drainMicroTaskQueue (zone.js:595)
defaultErrorLogger @ core.js:14597
push../node_modules/@angular/core/fesm5/core.js.ErrorHandler.handleError @ core.js:14645
next @ core.js:16628
schedulerFn @ core.js:12609
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:196
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next @ Subscriber.js:134
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next @ Subscriber.js:77
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:54
push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @ Subject.js:47
push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js:12593
(anonymous) @ core.js:16178
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138
push../node_modules/@angular/core/fesm5/core.js.NgZone.runOutsideAngular @ core.js:16115
onHandleError @ core.js:16178
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.handleError @ zone.js:392
push../node_modules/zone.js/dist/zone.js.Zone.runGuarded @ zone.js:154
_loop_1 @ zone.js:677
api.microtaskDrainDone @ zone.js:686
drainMicroTaskQueue @ zone.js:602
Promise.then (async)
scheduleMicroTask @ zone.js:578
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:410
onScheduleTask @ zone.js:297
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:401
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:232
push../node_modules/zone.js/dist/zone.js.Zone.scheduleMicroTask @ zone.js:252
scheduleResolveOrReject @ zone.js:862
resolvePromise @ zone.js:808
(anonymous) @ zone.js:724
webpackJsonpCallback @ bootstrap:25
(anonymous) @ 892.js:1

Body:
In ASPNETZero date picker is in ngx-bootstrap, so in this lib they use moment.js,
your three steps are right but you missed some steps that explained below:

Add a XML file for Malay language (...\aspnet-core\src\YOURCOMPANY.Core\Localization\YOURCOMPANY\YOURCOMPANY.ms.xml)

Added a new language in the DefaultLanguageCreator class

First of all, in your angular project edit this file ...\angular\src\assets\appconfig.json, and add localMapping suitable conversion (to en for now), don't forget set this configuration to appconfig.production.json.

        "localeMappings": {
            "angular": [
              {
                "from": "ms",
                "to": "en"
              }
            ],
            "moment": [
              {
                "from": "ms",
                "to": "en"
              },
              ...
            ],...

Then go this location : (...\angular\src\assets\ngx-bootstrap\ngx-bootstrap-locale-mapping.service.ts), map you culture like below:

const cultureMap = {
            'zh-Hans': 'zh-cn',
            'es-MX': 'es',
            'vi': 'en-gb',
            'ms': 'ms'
            // Add more here
        };

Set your module map:

getModuleName(locale: string): string {
        const moduleNameMap = {
            'zh-Hans': 'zhCn',
            'es-MX': 'es',
            'pt-BR': 'ptBr',
            'vi': 'enGb',
            'ms': 'ms'

            // Add more here
        };

You can map your culture like 'ms': 'en', if you do like this you will get your SPA date-picker in Georgian type, but if you want to change the moment of your date-pickers, you have to add your i18n overwrite, for doing this:

add this folder js file to (...\angular\src\assets\ngx-bootstrap\custom-i18n\ms.js)
you can find your moment.js culture on the net or simply edit other language to get your suitable moments.

finally, go to this file:
(...\angular\src\assets\ngx-bootstrap\ngx-bootstrap-datepicker-config.service.ts)
and change this function like below:

static registerNgxBootstrapDatePickerLocales(): Promise<boolean> {
        if (abp.localization.currentLanguage.name === 'en') {
            return Promise.resolve(true);
        }

        let supportedLocale = new NgxBootstrapLocaleMappingService().map(abp.localization.currentLanguage.name).toLowerCase();
        let moduleLocaleName = new NgxBootstrapLocaleMappingService().getModuleName(abp.localization.currentLanguage.name);

        if (abp.localization.currentLanguage.name === 'ms') {
            return new Promise<boolean>((resolve, reject) => {
                import(`assets/ngx-bootstrap/custom-i18n/ms.js`)
                    .then(module => {
                        defineLocale(abp.localization.currentLanguage.name.toLowerCase(), module[`msLocale`]);
                        resolve(true);
                    }, reject);
            });
        }

        return new Promise<boolean>((resolve, reject) => {
            import(`ngx-bootstrap/chronos/esm5/i18n/${supportedLocale}.js`)
                .then(module => {
                    defineLocale(abp.localization.currentLanguage.name.toLowerCase(), module[`${moduleLocaleName}Locale`]);
                    resolve(true);
                }, reject);
        });
    }

As you can see, in Promise ms.js file import function we call your ms.js module name as msLocale, this is an exported variable declared in your ms.js file.

If you can't find your moment culture js file in this link:
moment.js locales

Simply write yourself, this is a official tutorial:
moment.js customization


问:
javascript regular expression
How do you write a JS regular expression to extract the first "2" from "/?page=2&promo_id=1234". (ie page number 2)

Thanks!

答:
I wouldn't use regular expressions as such, I'd use the split method:

```<code>var str="/?page=2&promo_id=1234";

document.write(str.split("/?page=")[1][0]);
</code>```

Of course this will only work for single digit numbers.  You could modify it to work for all numbers using a proper regular expression.

http://jsfiddle.net/u8ZXc/

Title: javascript regular expression

Body:
I wouldn't use regular expressions as such, I'd use the split method:

var str="/?page=2&promo_id=1234";

document.write(str.split("/?page=")[1][0]);

Of course this will only work for single digit numbers.  You could modify it to work for all numbers using a proper regular expression.

http://jsfiddle.net/u8ZXc/


问:
How to turn Windows 10 PC as SMTP server?
I want to configure my window system as a mail server. Please let me if anybody knows how to configure windows 10 as a mail server. I have an ec2 window instance.</p>

答:
Yes, there are a plenty of videos, I hope you found this one useful, :)

https://www.youtube.com/watch?v=9Q4S_6pmPoA


答:
Here is your solution</p>

```<code>    public String plusOut(String str, String word)
{
    String ret = "";
    for (int i = 0; i < str.length();) {
        if (i + word.length()<= str.length() && str.substring(i, i + word.length()).equals(word)) {
            ret += word;
            i+=word.length();
        }
        else{
            ret += "+";
            i++;
        }
    }
    return ret;
}
</code>```

Title: CodingBat starOut, why using substring won't work correctly

Body:
Here is your solution

    public String plusOut(String str, String word)
{
    String ret = "";
    for (int i = 0; i < str.length();) {
        if (i + word.length()<= str.length() && str.substring(i, i + word.length()).equals(word)) {
            ret += word;
            i+=word.length();
        }
        else{
            ret += "+";
            i++;
        }
    }
    return ret;
}


问:
A function to check for hill or valley in a given list, without usage of Numpy or zip?

A list of numbers is identified as 'hill' if it has an ascending sequence followed by a descending sequence. Similarly, it'll be 'valley hill' if it consists of a descending sequence followed by an ascending one. Each of the sequences should be of length of at least two.

For example, a list [1,2,3,5,4] will be a hill or a list [5,4,1,2,3] will be a valley.

I'm trying to write a function, without the usage of either numpy arrays or zip function that returns a true if it identifies a hill or valley and false if it doesn't.

The code I've come up with is:

```<code>def hillovalley(n):
  if len(n)<=2:
    return False
  c = n[0]<n[1]
  x=0
  for i in range(len(n)-1):
    if c!=(n[i]<n[i+1]):
      c=n[i]<n[i+1]
      x=x+1
    if x==1:
      return True
    else:
      return False
</code>```

However, this code would fail if the input is something like [1,2,3,5,4,3,2,1] or [9,5,4,-1,-2,3,7].

Thank you for your help!

答:
```<code>    def hill(l):
        bol = 0
        count = 0
        for i in range(0,len(l)-1):
            if l[i+1] == l[i]:
                return False
            elif l[i+1] > l[i] and bol == 0:
                count = 1
            elif l[i+1] < l[i] and bol == 0:
                bol = 1
            elif l[i+1] > l[i] and bol == 1:
                return False

        if bol == 0 or count == 0:
            return False
        else:
            return True

    def valley(l):
        bol = 0
        count = 0
        for i in range(0,len(l)-1):
            if l[i+1] == l[i]:
                return False
            elif l[i+1] < l[i] and bol == 0:
                count = 1
            elif l[i+1] > l[i] and bol == 0:
                bol = 1
            elif l[i+1] < l[i] and bol == 1:
                return False
        if bol == 0 or count == 0:
            return False
        else:
            return True

    def hillvalley(l):
        if hill(l):
            print ("True")
            return True
        elif valley(l):
            print ("True")
            return True
        else:
            print("False")
            return False
</code>```

Body:
A list of numbers is identified as 'hill' if it has an ascending sequence followed by a descending sequence. Similarly, it'll be 'valley hill' if it consists of a descending sequence followed by an ascending one. Each of the sequences should be of length of at least two.

For example, a list [1,2,3,5,4] will be a hill or a list [5,4,1,2,3] will be a valley.

I'm trying to write a function, without the usage of either numpy arrays or zip function that returns a true if it identifies a hill or valley and false if it doesn't.

The code I've come up with is:

def hillovalley(n):
  if len(n)<=2:
    return False
  c = n[0]<n[1]
  x=0
  for i in range(len(n)-1):
    if c!=(n[i]<n[i+1]):
      c=n[i]<n[i+1]
      x=x+1
    if x==1:
      return True
    else:
      return False

However, this code would fail if the input is something like [1,2,3,5,4,3,2,1] or [9,5,4,-1,-2,3,7].

Thank you for your help!


答:
A straightforward application of the FLATTEN function can work here. The function creates a lateral view with exploded rows from each source row. For flat objects, all key value pairs are exploded into one row each.

Using the KEY portion of the flattened result provides the Table part of the desired output, and the VALUE portion provides Entries. Since FLATTEN produces a lateral view, you still have access to the preceding source table row values to continue retaining the Name column in the result.

An example query that performs the transformation:

SELECT
  t.name AS "Name",
  lv.key AS "Table",
  lv.value AS "Entries"
FROM
  data_table t,
  LATERAL FLATTEN(input => t.number) lv
```

Title: Snowflake lateral flatten with changing keys in json

Body:
I have a table  in Snowflake with similar structure as below,

----------------------------------------
Name | Number
----------------------------------------
Dim_1 | {'Table_1': 100}
Dim_1 | {'Table_1': 101}
Dim_2 | {'Table_2': 200, 'Table_3': 300}
Dim_2 | {'Table_2': 201, 'Table_3': 301}

and I am trying to get output as :

-----------------------
Name | Table | Entries
-----------------------
Dim_1 | Table_1 | 100
Dim_1 | Table_1 | 101
Dim_2 | Table_2 | 200
Dim_2 | Table_3 | 300
Dim_2 | Table_2 | 201
Dim_2 | Table_3 | 301

Any ideas?


答:
Try using width: 33.33% instead of margin-left: 33% and apply the class to each third of the footer. This will split the footer into 3 columns:

.footer {
  width: 100%;
  /*breite: 100%*/
  padding: 0;
  margin: 0;
  background-color: darkcyan;
  /*Hintergrundfarbe*/
  margin-bottom: 0;
  bottom: 0;
}

.footer-column {
  float: left;
  width: 33.33%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="footer">

  <div class="footer-column">
    <h3 class="company">Company</h3>
    <ul>
      <li>Text1</li>
      <li>Text2</li>
      <li>Text3</li>
    </ul>
  </div>

  <div class="footer-column">
    <h3 class="social">Social</h3>
    <ul>
      <li><a>Twitter</a></li>
      <li><a>Instagram</a></li>
      <li><a>Reddit</a></li>
    </ul>
  </div>

  <div class="footer-column">
    <h3 class="text">Text4</h3>
    <ul>
      <li><a>other1</a></li>
      <li><a>other2</a></li>
    </ul>
  </div>

</div></code>```

Title: css margin: auto issue in footer

Body:
My problem is to split the space inside my footer bar in 3 part (each with same width)

footer {
  width: 100%;
  /*breite: 100%*/
  padding: 0;
  margin: 0;
  background-color: darkcyan;
  /*Hintergrundfarbe*/
  margin-bottom: 0;
  bottom: 0;
}

.footer-items {
  width: 80%;
  margin: auto;
  display: flex;
  /*bringt alle Teile in eine Linie*/
  text-align: center;
  /*zentriert ganzen Text im footer*/
}

Company

Text1

Text2

Text3

Social

Twitter

Instagram

Reddit

Text4

other1

other2

If I try to do sth like margin-left: 33% for my 3 items in footer this is not gonna work.

thanks for your help

Body:
Try using width: 33.33% instead of margin-left: 33% and apply the class to each third of the footer. This will split the footer into 3 columns:

.footer {
  width: 100%;
  /*breite: 100%*/
  padding: 0;
  margin: 0;
  background-color: darkcyan;
  /*Hintergrundfarbe*/
  margin-bottom: 0;
  bottom: 0;
}

.footer-column {
  float: left;
  width: 33.33%;
}

<div class="footer">

  <div class="footer-column">
    <h3 class="company">Company</h3>
    <ul>
      <li><a href="text1.html">Text1</a></li>
      <li><a href="text2.html">Text2</a></li>
      <li><a href="text3.html">Text3</a></li>
    </ul>
  </div>

  <div class="footer-column">
    <h3 class="social">Social</h3>
    <ul>
      <li><a>Twitter</a></li>
      <li><a>Instagram</a></li>
      <li><a>Reddit</a></li>
    </ul>
  </div>

  <div class="footer-column">
    <h3 class="text">Text4</h3>
    <ul>
      <li><a>other1</a></li>
      <li><a>other2</a></li>
    </ul>
  </div>

</div>


问:
How do I easily prohibit access to a Github repository's commit history?
When creating course programming assignments I often work in a Github repo.  These repos usually contain commits that have the solution to the assignment.  Since I don't want to make those commits available to the class is there a way to prohibit access to the commit history?  </p>

<p>Right now I end up having to create a brand new repo and copying the code in manually so there's no commit history. Or providing a zip of the repo.  But a zip is awkward because sometimes I want to make a change to the code in the assignment. There must be a better way!  (I'd be psyched for solutions that can be done through the Github GUI if possible.  But I'll settle for command line.) </p>

答:
I'm not sure if there is a way to restrict access to specific parts of the history. It's also probably not a great idea to delete the history because you may want to refer to it later.

If your students don't need access to any of the commit history, and you are just trying to avoid copy/pasting code into a new repo, then you can copy the existing repo into a new directory, and then delete the entire .git directory to blow away the history. Then just initialize a new repo with git init, commit the entire codebase, and follow the normal steps to create a remote repository and push to it.

You'll be left with a new repo to give your students that has no history but all the same code.

Body:
When creating course programming assignments I often work in a Github repo.  These repos usually contain commits that have the solution to the assignment.  Since I don't want to make those commits available to the class is there a way to prohibit access to the commit history?

Right now I end up having to create a brand new repo and copying the code in manually so there's no commit history. Or providing a zip of the repo.  But a zip is awkward because sometimes I want to make a change to the code in the assignment. There must be a better way!  (I'd be psyched for solutions that can be done through the Github GUI if possible.  But I'll settle for command line.)


答:
I see your .footer-items is display: flex;, you could make its nearest children grow evenly.

Look into the snippet. (Aslo you could remove text-align: center;)

footer {
  width: 100%;
  /*breite: 100%*/
  padding: 0;
  margin: 0;
  background-color: darkcyan;
  /*Hintergrundfarbe*/
  margin-bottom: 0;
  bottom: 0;
}

.footer-items {
  width: 80%;
  margin: auto;
  display: flex;
  /*bringt alle Teile in eine Linie*/
  /*text-align: center;*/
  /*zentriert ganzen Text im footer*/
}

.footer-items > div {
  flex-grow: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="footer-items">

  <div class="company-items">
    <h3 class="company">Company</h3>
    <ul>
      <li>Text1</li>
      <li>Text2</li>
      <li>Text3</li>
    </ul>
  </div>

  <div class="social-items">
    <h3 class="social">Social</h3>
    <ul>
      <li><a>Twitter</a></li>
      <li><a>Instagram</a></li>
      <li><a>Reddit</a></li>
    </ul>
  </div>

  <div class="other-items">
    <h3 class="text">Text4</h3>
    <ul>
      <li><a>other1</a></li>
      <li><a>other2</a></li>
    </ul>
  </div>

</div></code>```

Title: css margin: auto issue in footer

Body:
I see your .footer-items is display: flex;, you could make its nearest children grow evenly.

Look into the snippet. (Aslo you could remove text-align: center;)

footer {
  width: 100%;
  /*breite: 100%*/
  padding: 0;
  margin: 0;
  background-color: darkcyan;
  /*Hintergrundfarbe*/
  margin-bottom: 0;
  bottom: 0;
}

.footer-items {
  width: 80%;
  margin: auto;
  display: flex;
  /*bringt alle Teile in eine Linie*/
  /*text-align: center;*/
  /*zentriert ganzen Text im footer*/
}

.footer-items > div {
  flex-grow: 1;
}

<div class="footer-items">

  <div class="company-items">
    <h3 class="company">Company</h3>
    <ul>
      <li><a href="text1.html">Text1</a></li>
      <li><a href="text2.html">Text2</a></li>
      <li><a href="text3.html">Text3</a></li>
    </ul>
  </div>

  <div class="social-items">
    <h3 class="social">Social</h3>
    <ul>
      <li><a>Twitter</a></li>
      <li><a>Instagram</a></li>
      <li><a>Reddit</a></li>
    </ul>
  </div>

  <div class="other-items">
    <h3 class="text">Text4</h3>
    <ul>
      <li><a>other1</a></li>
      <li><a>other2</a></li>
    </ul>
  </div>

</div>


问:
Fetch return blob instead of text after 0.59 RN update
I update my RN app from 0.58.3 version to 0.59.4 and instead of bodyText server return bodyBlob now

I tried to use response.json() func but it doesn't help

fetch(`http://someserver `, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Accept-Language': 'ru,en;q=0.9',
      },
       body: '{"login":"root","password":"root"}'
    })
      .then((response) => {
        console.log(response.json());
      });
```

<p>response i get is like this:</p>

<pre class="lang-js prettyprint-override"><code>{
    "type": "default",
    "status": 200,
    "ok": true,
    "headers": {
        "map": {
            "x-xss-protection": "1",
            "set-cookie": "jwt=eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyLWNvZGUiOiJyb290LXVzZXIiLCJleHAiOjE1NTU0MjY0Mjl9.UaHzsIil8t9HtgrBF8JN0c2W-eIIkDEmb6GvO9Do0-A;Expires=Tue, 16 Apr 2019 14:53:49 +0000;Path=/;HttpOnly;SameSite=Strict",
            "connection": "keep-alive",
            "content-length": "360",
            "content-type": "application/json;charset=utf-8",
            "date": "Tue, 16 Apr 2019 13:53:49 GMT",
            "server": "nginx/1.15.10"
        }
    },
    "url": "***",
    "_bodyInit": {
        "_data": {
            "size": 360,
            "offset": 0,
            "blobId": "3397402a-12dd-4dd9-8980-90924aeb416d"
        }
    },
    "_bodyBlob": {
        "_data": {
            "size": 360,
            "offset": 0,
            "blobId": "3397402a-12dd-4dd9-8980-90924aeb416d"
        }
    }
}
</code>```

instead of normal bodyText i get bodyBlob

答:
Sorry, I am late with the answer. I hope it will be helpful for others.
Be careful, response.json() returns promise.</p>

```<code>fetch(`http://someserver `, {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Accept-Language': 'ru,en;q=0.9',
    },
    body: '{"login":"root","password":"root"}'
})
.then((response) => {
    response.json().then(res => {
        console.log(res);
    })
});
</code>```

Body:
I update my RN app from 0.58.3 version to 0.59.4 and instead of bodyText server return bodyBlob now

I tried to use response.json() func but it doesn't help

fetch(`http://someserver `, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Accept-Language': 'ru,en;q=0.9',
      },
       body: '{"login":"root","password":"root"}'
    })
      .then((response) => {
        console.log(response.json());
      });

response i get is like this:

{
    "type": "default",
    "status": 200,
    "ok": true,
    "headers": {
        "map": {
            "x-xss-protection": "1",
            "set-cookie": "jwt=eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyLWNvZGUiOiJyb290LXVzZXIiLCJleHAiOjE1NTU0MjY0Mjl9.UaHzsIil8t9HtgrBF8JN0c2W-eIIkDEmb6GvO9Do0-A;Expires=Tue, 16 Apr 2019 14:53:49 +0000;Path=/;HttpOnly;SameSite=Strict",
            "connection": "keep-alive",
            "content-length": "360",
            "content-type": "application/json;charset=utf-8",
            "date": "Tue, 16 Apr 2019 13:53:49 GMT",
            "server": "nginx/1.15.10"
        }
    },
    "url": "***",
    "_bodyInit": {
        "_data": {
            "size": 360,
            "offset": 0,
            "blobId": "3397402a-12dd-4dd9-8980-90924aeb416d"
        }
    },
    "_bodyBlob": {
        "_data": {
            "size": 360,
            "offset": 0,
            "blobId": "3397402a-12dd-4dd9-8980-90924aeb416d"
        }
    }
}

instead of normal bodyText i get bodyBlob

Body:
Sorry, I am late with the answer. I hope it will be helpful for others.
Be careful, response.json() returns promise.

fetch(`http://someserver `, {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Accept-Language': 'ru,en;q=0.9',
    },
    body: '{"login":"root","password":"root"}'
})
.then((response) => {
    response.json().then(res => {
        console.log(res);
    })
});


问:
Apache Tomcat Windows stdout/stderr configuration
Like many other members before me, I have some questions surrounding configuring Apache Tomcat logging on Windows.  To be more specific, my questions surround the proper method(s) for limiting the size and number of log files that are created for stderr/stdout of the Apache Tomcat server as a whole.

My Java knowledge is pretty much limited to whatever I've been able to find on the web in searches.

What I believe I understand is this:

The Apache Tomcat service on Windows defaults to the -std(out|err).yyyy-mm-dd.log

The Apache Tomcat service uses the following options in the Java startup definition:
```  -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
  -Djava.util.logging.config.file=<tomcat_home>\conf\logging.properties```

The Apache Tomcat service defines the majority of its core logging options within the logging.properties file.

Is there a proper configuration/directive/option that can/should be added to the logging.properties file to limit the size, number, count, etc. of the std(out|err) log files?

My main confusion is with how the loggers and handlers are defined within the logging.properties file with respect to the Tomcat service itself.

If this has been answered in another thread that I didn't find before posting this, please redirect me.  I have tried to follow along with Apache's documentation for logging (https://tomcat.apache.org/tomcat-9.0-doc/logging.html) but I don't know if I can simply add options like maxDays, count, and maxCapSize (or whatever the appropriate option and value should be) directly into the <tomcat_home>\conf\logging.properties file or if I have to use a different way?

Any help or direction that gets me to a better understanding of this and how to accomplish my end goal of limiting the number and size of std(out|err) log files is and will be greatly appreciated!

Thanks!

Greg

答:
According to Apache Tomcat 9 Windows Service How-To There are only the following options:

```<code>--LogPath   %SystemRoot%\System32\LogFiles\Apache   Defines the path for logging.  Creates the directory if necessary.
--LogPrefix commons-daemon  Defines the service log filename prefix. The log file is created in the LogPath directory with .YEAR-MONTH-DAY.log suffix
--LogLevel  Info    Defines the logging level and can be either Error, Info, Warn or Debug. (Case insensitive).
--StdOutput     Redirected stdout filename. If named auto then file is created inside LogPath with the name service-stdout.YEAR-MONTH-DAY.log.
--StdError      Redirected stderr filename. If named auto then file is created inside LogPath with the name service-stderr.YEAR-MONTH-DAY.log.
</code>```

Looks like for deleting of files you would have to create a scheduled task to do so.

Body:
Like many other members before me, I have some questions surrounding configuring Apache Tomcat logging on Windows.  To be more specific, my questions surround the proper method(s) for limiting the size and number of log files that are created for stderr/stdout of the Apache Tomcat server as a whole.

My Java knowledge is pretty much limited to whatever I've been able to find on the web in searches.

What I believe I understand is this:

The Apache Tomcat service on Windows defaults to the -std(out|err).yyyy-mm-dd.log

The Apache Tomcat service uses the following options in the Java startup definition:

  -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
  -Djava.util.logging.config.file=<tomcat_home>\conf\logging.properties

The Apache Tomcat service defines the majority of its core logging options within the logging.properties file.

Is there a proper configuration/directive/option that can/should be added to the logging.properties file to limit the size, number, count, etc. of the std(out|err) log files?

My main confusion is with how the loggers and handlers are defined within the logging.properties file with respect to the Tomcat service itself.

If this has been answered in another thread that I didn't find before posting this, please redirect me.  I have tried to follow along with Apache's documentation for logging (https://tomcat.apache.org/tomcat-9.0-doc/logging.html) but I don't know if I can simply add options like maxDays, count, and maxCapSize (or whatever the appropriate option and value should be) directly into the <tomcat_home>\conf\logging.properties file or if I have to use a different way?

Any help or direction that gets me to a better understanding of this and how to accomplish my end goal of limiting the number and size of std(out|err) log files is and will be greatly appreciated!

Thanks!

Greg

Body:
According to Apache Tomcat 9 Windows Service How-To There are only the following options:

--LogPath   %SystemRoot%\System32\LogFiles\Apache   Defines the path for logging.  Creates the directory if necessary.
--LogPrefix commons-daemon  Defines the service log filename prefix. The log file is created in the LogPath directory with .YEAR-MONTH-DAY.log suffix
--LogLevel  Info    Defines the logging level and can be either Error, Info, Warn or Debug. (Case insensitive).
--StdOutput     Redirected stdout filename. If named auto then file is created inside LogPath with the name service-stdout.YEAR-MONTH-DAY.log.
--StdError      Redirected stderr filename. If named auto then file is created inside LogPath with the name service-stderr.YEAR-MONTH-DAY.log.

Looks like for deleting of files you would have to create a scheduled task to do so.


问:
MATLAB/Octave plot markers above the line rather than on the line
I want to visualize the peaks of a function, and I want to have markers for it appear above the line they are associated with.

I fabricated a minimum example where I already have the peaks, the question is just how to visualize the markers correctly:

```<code>y = [0.1 0.3 10.0 1.0 0.5 0.1 24.0 0.6 0.1 0.2]
x = (1:length(y))
plot(x,y);

hold on;

peaks = [3 7];
plot(x(peaks), y(peaks), 'v', 'MarkerSize', 24);

print('-dpng', 'example.png', '-S640,480');
</code>```

So, as a result, the markers appear centered on the line like this:

The result that I want could be achieved by carefully tuning a parameter OFFSET like this:

```<code>plot(x(peaks), y(peaks)+OFFSET, 'v', 'MarkerSize', 24);
</code>```

As shown in the following figure, for this exact example OFFSET=2.56 works for the exported png, but with the interactive plot and exporting vector graphics, it's wrong again.

Can anyone recommend a way to get this result without having to manually doing trial/error?

Currently I am using Octave with gnuplot to export to latex+tikz, and it would be good if the solution would work there.

In my actual (more complicated) use case I am plotting multiple lines after each other into the same figure, and the y limits change, so the offsets can not just be calculated easily, as the markersize doesn't change with the y limits.

Edit: Additionally I am using a semilogx plot, so drawing lines inside the diagram in the x/y-Axis scales would look distorted.

答:
One way to do this is with annotations, but there are some drawbacks (see below).

Annotations enable you to place various graphic objects into your figure. One very annoying thing about them is that they work in so-called normalized coordinates,
which span the whole figure window (not just the plot area) and go from [0,0] to [1,1], forcing you to convert to these coordinates first. I wrote a simple function to do this, provided your plot scale is linear (if you want logarithmic, you will have to modify this function):

```<code>## Convert from data coordinates to normalized figure coordinates.
function [xf yf] = figcoords(xa, ya)
    axp = get(gca, "position");
    lf = axp(1);
    bf = axp(2);
    rf = lf + axp(3);
    tf = bf + axp(4);

    xl = xlim();
    yl = ylim();
    la = xl(1);
    ra = xl(2);
    ba = yl(1);
    ta = yl(2);

    xf = lf + (xa-la).*(rf-lf)./(ra-la);
    yf = bf + (ya-ba).*(tf-bf)./(ta-ba);
endfunction
</code>```

With this out of your way, you can proceed to annotating the plot using the annotation function:

```<code>y = [0.1 0.3 10.0 1.0 0.5 0.1 24.0 0.6 0.1 0.2];
x = (1:length(y));
peaks = [3 7];

## Plot the data as you would normally
plot(x,y);

## Plot peak markers (no `hold on` needed)
[xp yp] = figcoords(peaks, y(peaks));    # Transform to figure coordinates
for coords = [xp; yp]
    xpi = coords(1);
    ypi = coords(2);
    annotation("arrow", [xpi xpi], [ypi+eps ypi]);
endfor
</code>```

Plot with annotated peaks

Here, we actually draw little arrows pointing from top onto the peaks.
As their height is very small, we only see the arrowheads.
The arguments to the annotation function are the x and y coordinates
of the endpoints of the arrow. Note that we added a small number (eps)
to the y-value of the starting point to make the arrow point downward.

If you want, you can tweak the appearance of the markers to make them more visually appealing:

```<code>y = [0.1 0.3 10.0 1.0 0.5 0.1 24.0 0.6 0.1 0.2];
x = (1:length(y));
peaks = [3 7];

coloridx = get(gca, "ColorOrderIndex")
peakcolor = get(gca, "ColorOrder")(coloridx,:);    # Save current plot colour

plot(x,y);

## Plot peak markers
[xp yp] = figcoords(peaks, y(peaks));
for coords = [xp; yp]
    xpi = coords(1);
    ypi = coords(2);
    annotation("arrow", [xpi xpi], [ypi+eps ypi], "headstyle", "plain",...
        "color", peakcolor);
endfor
</code>```

Plot with annotated peaks in the same color

Drawbacks

While this approach works fine regardless of the size of the markers or your plot, there are some drawbacks:

First, the annotations are fixed relative to the figure window, not the plot.
This is fine when you display the plot for the first time, but once you zoom
or pan, the alignment is lost: The markes stay in place while the plot moves.
If you don't need an interactive plot (eg, you just want to export it to image),
just be sure to set the plot limits before adding the annotations and you should
be fine.

Second, this method is very slow compared to plotting the points using the
plot function. On my computer, for example, when drawing a simple example with
seven annotated peaks, it takes about a second before the markers appear.
Plotting a signal with thousands of peaks is near impossible.

Body:
I want to visualize the peaks of a function, and I want to have markers for it appear above the line they are associated with.

I fabricated a minimum example where I already have the peaks, the question is just how to visualize the markers correctly:

y = [0.1 0.3 10.0 1.0 0.5 0.1 24.0 0.6 0.1 0.2]
x = (1:length(y))
plot(x,y);

hold on;

peaks = [3 7];
plot(x(peaks), y(peaks), 'v', 'MarkerSize', 24);

print('-dpng', 'example.png', '-S640,480');

So, as a result, the markers appear centered on the line like this:

The result that I want could be achieved by carefully tuning a parameter OFFSET like this:

plot(x(peaks), y(peaks)+OFFSET, 'v', 'MarkerSize', 24);

As shown in the following figure, for this exact example OFFSET=2.56 works for the exported png, but with the interactive plot and exporting vector graphics, it's wrong again.

Can anyone recommend a way to get this result without having to manually doing trial/error?

Currently I am using Octave with gnuplot to export to latex+tikz, and it would be good if the solution would work there.

In my actual (more complicated) use case I am plotting multiple lines after each other into the same figure, and the y limits change, so the offsets can not just be calculated easily, as the markersize doesn't change with the y limits.

Edit: Additionally I am using a semilogx plot, so drawing lines inside the diagram in the x/y-Axis scales would look distorted.

Body:
One way to do this is with annotations, but there are some drawbacks (see below).

Annotations enable you to place various graphic objects into your figure. One very annoying thing about them is that they work in so-called normalized coordinates,
which span the whole figure window (not just the plot area) and go from [0,0] to [1,1], forcing you to convert to these coordinates first. I wrote a simple function to do this, provided your plot scale is linear (if you want logarithmic, you will have to modify this function):

## Convert from data coordinates to normalized figure coordinates.
function [xf yf] = figcoords(xa, ya)
    axp = get(gca, "position");
    lf = axp(1);
    bf = axp(2);
    rf = lf + axp(3);
    tf = bf + axp(4);

    xl = xlim();
    yl = ylim();
    la = xl(1);
    ra = xl(2);
    ba = yl(1);
    ta = yl(2);

    xf = lf + (xa-la).*(rf-lf)./(ra-la);
    yf = bf + (ya-ba).*(tf-bf)./(ta-ba);
endfunction

With this out of your way, you can proceed to annotating the plot using the annotation function:

y = [0.1 0.3 10.0 1.0 0.5 0.1 24.0 0.6 0.1 0.2];
x = (1:length(y));
peaks = [3 7];

## Plot the data as you would normally
plot(x,y);

## Plot peak markers (no `hold on` needed)
[xp yp] = figcoords(peaks, y(peaks));    # Transform to figure coordinates
for coords = [xp; yp]
    xpi = coords(1);
    ypi = coords(2);
    annotation("arrow", [xpi xpi], [ypi+eps ypi]);
endfor

Plot with annotated peaks

Here, we actually draw little arrows pointing from top onto the peaks.
As their height is very small, we only see the arrowheads.
The arguments to the annotation function are the x and y coordinates
of the endpoints of the arrow. Note that we added a small number (eps)
to the y-value of the starting point to make the arrow point downward.

If you want, you can tweak the appearance of the markers to make them more visually appealing:

y = [0.1 0.3 10.0 1.0 0.5 0.1 24.0 0.6 0.1 0.2];
x = (1:length(y));
peaks = [3 7];

coloridx = get(gca, "ColorOrderIndex")
peakcolor = get(gca, "ColorOrder")(coloridx,:);    # Save current plot colour

plot(x,y);

## Plot peak markers
[xp yp] = figcoords(peaks, y(peaks));
for coords = [xp; yp]
    xpi = coords(1);
    ypi = coords(2);
    annotation("arrow", [xpi xpi], [ypi+eps ypi], "headstyle", "plain",...
        "color", peakcolor);
endfor

Plot with annotated peaks in the same color

Drawbacks

While this approach works fine regardless of the size of the markers or your plot, there are some drawbacks:

First, the annotations are fixed relative to the figure window, not the plot.
This is fine when you display the plot for the first time, but once you zoom
or pan, the alignment is lost: The markes stay in place while the plot moves.
If you don't need an interactive plot (eg, you just want to export it to image),
just be sure to set the plot limits before adding the annotations and you should
be fine.

Second, this method is very slow compared to plotting the points using the
plot function. On my computer, for example, when drawing a simple example with
seven annotated peaks, it takes about a second before the markers appear.
Plotting a signal with thousands of peaks is near impossible.


问:
I'm a bit confused about how to solve this warning and error
I have to make a code where a random number is generated between 1 and 100, and a user has to input numbers until they figure it out. At the end, it has to tell them how many guesses it took them to figure it out. I have one error and one warning, neither of which I know how to handle. I tried looking them up but I couldn't really find something to help me:

```<code>main.c: In function ‘main’:
main.c:18:26: warning: implicit declaration of function ‘time’ [-Wimplicit-function-declaration]
         srand((unsigned) time(&t));
                          ^~~~
main.c:43:1: error: expected ‘while’ before ‘}’ token
 }
 ^
main.c:43:1: error: expected declaration or statement at end of input
</code>```

Here's the code I'm working with for reference:

```<code>#include <stdio.h>
#include <stdlib.h>

int main() {
    char name[1024];
    int i, n;
    time_t t;
    int randNum;
    int userTries;
    int inpUser;

    printf("Please enter your name: \n");
    scanf("%s", name);
    printf("Hello %s\n, we're going to play a game where you guess a secret number. I will tell you if you're too high or too low, and I will also tell you at the end how many guesses you took.\n", name);

    //initializes the random number generator
    srand((unsigned) time(&t));

    //calculates a random number between 100 and 1*/
    randNum = rand() % 100 + 1;

    do {
        printf("Guess a random number, but I bet you'll get it wrong:\n");
        scanf("%d", inpUser);
        if (inpUser == randNum) {
            printf("That's the number! Maybe I underestimated you.\n");
        }
        else if (inpUser > randNum) {
            printf("You're a little high there, bud.\n");
        }
        else if (inpUser < randNum) {
            printf("Maybe go a little higher next time?\n");

            userTries++;
        }

        while (randNum != inpUser);
        printf("Congratulations, you actually did it! That's the number! It took you %d tries, but you did it!", userTries);

        return 0;
    }
}
</code>```

答: In your while loop, you should enclose the print statement inside curly braces{}. Using a semicolon ends the while statement. Also, you declared time_t, but you are then using simply time. No variable time was declared. </p>

Body:
I have to make a code where a random number is generated between 1 and 100, and a user has to input numbers until they figure it out. At the end, it has to tell them how many guesses it took them to figure it out. I have one error and one warning, neither of which I know how to handle. I tried looking them up but I couldn't really find something to help me:

main.c: In function ‘main’:
main.c:18:26: warning: implicit declaration of function ‘time’ [-Wimplicit-function-declaration]
         srand((unsigned) time(&t));
                          ^~~~
main.c:43:1: error: expected ‘while’ before ‘}’ token
 }
 ^
main.c:43:1: error: expected declaration or statement at end of input

Here's the code I'm working with for reference:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char name[1024];
    int i, n;
    time_t t;
    int randNum;
    int userTries;
    int inpUser;

    printf("Please enter your name: \n");
    scanf("%s", name);
    printf("Hello %s\n, we're going to play a game where you guess a secret number. I will tell you if you're too high or too low, and I will also tell you at the end how many guesses you took.\n", name);

    //initializes the random number generator
    srand((unsigned) time(&t));

    //calculates a random number between 100 and 1*/
    randNum = rand() % 100 + 1;

    do {
        printf("Guess a random number, but I bet you'll get it wrong:\n");
        scanf("%d", inpUser);
        if (inpUser == randNum) {
            printf("That's the number! Maybe I underestimated you.\n");
        }
        else if (inpUser > randNum) {
            printf("You're a little high there, bud.\n");
        }
        else if (inpUser < randNum) {
            printf("Maybe go a little higher next time?\n");

            userTries++;
        }

        while (randNum != inpUser);
        printf("Congratulations, you actually did it! That's the number! It took you %d tries, but you did it!", userTries);

        return 0;
    }
}


问:
Where can I learn jQuery? Is it worth it?
I've had a lot of good experiences learning about web development on w3schools.com. It's hit or miss, I know, but the PHP and CSS sections specifically have proven very useful for reference.

Anyway, I was wondering if there was a similar site for jQuery. I'm interested in learning, but I need it to be online/searchable, so I can refer back to it easily when I need the information in the future.

Also, as a brief aside, is jQuery worth learning? Or should I look at different JavaScript libraries? I know Jeff uses jQuery on Stack Overflow and it seems to be working well.

Thanks!

Edit: jQuery's website has a pretty big list of tutorials, and a seemingly comprehensive documentation page. I haven't had time to go through it all yet, has anyone else had experience with it?

Edit 2: It seems Google is now hosting the jQuery libraries. That should give jQuery a pretty big advantage in terms of publicity.

Also, if everyone uses a single unified aQuery library hosted at the same place, it should get cached for most Internet users early on and therefore not impact the download footprint of your site should you decide to use it.

2 Months Later...

Edit 3: I started using jQuery on a project at work recently and it is great to work with! Just wanted to let everyone know that I have concluded it is ABSOLUTELY worth it to learn and use jQuery.

Also, I learned almost entirely from the Official jQuery documentation and tutorials. It's very straightforward.

10 Months Later...

jQuery is a part of just about every web app I've made since I initially wrote this post. It makes progressive enhancement a breeze, and helps make the code maintainable.

Also, all the jQuery plug-ins are an invaluable resource!

3 Years Later...

Still using jQuery just about every day. I now author jQuery plug-ins and consult full time. I'm primarily a Djangonaut but I've done several javascript only contracts with jQuery. It's a life saver.

From one jQuery user to another... You should look at templating with jQuery (or underscore -- see below).

Other things I've found valuable in addition to jQuery (with estimated portion of projects I use it on):

jQuery Form Plugin (95%)

jQuery Form Example Plugin (75%)

jQuery UI (70%)

Underscore.js (80%)

CoffeeScript (30%)

Backbone.js (10%)

答:
Jquery.com is well organized and has many great examples. You don't need to buy a book. I found it easy to pickup on the fly by just referencing website's documentation. If you're someone who learns best by doing, I'd suggest this approach.

And yes, it's absolutely worth learning. It'll save you a lot of time and you'll actually look forward to doing JavaScript work!

OwnerDisplayName: Jim Robert

LastEditorDisplayName: Jim Robert

OwnerDisplayName: Cory House

ContentLicense: CC BY-SA 2.5


问:
Jquery show/hide not working until refresh
I have a checkout page that has three fieldsets:
fieldset id="1", fieldset id="2", fieldset id="3".  When the page loads, I need it to hide fieldsets 2 and 3 and only show fieldset 1.  This is what my jquery looks like:  </p>

```<code>$(document).ready(function(){
  $("#1").show();
  $("#2").hide();
  $("#3").hide();
  $("#4").hide();
});
</code>```

<p>When I load the page I can see fieldset 1 and fieldset 2.  If I refresh the page, it looks perfect, but upon first load, it's weird.  Any suggestions? </p>

答:
First thing you need to do is properly name your ID's.  ID's can't start with a number.

If you change the name to set_1 you can do the initial hide with CSS.

```<code>#set_2, #set_3, #set_4 { display:none; }
</code>```

No JS needed.

Body:
I have a checkout page that has three fieldsets:
fieldset id="1", fieldset id="2", fieldset id="3".  When the page loads, I need it to hide fieldsets 2 and 3 and only show fieldset 1.  This is what my jquery looks like:

$(document).ready(function(){
  $("#1").show();
  $("#2").hide();
  $("#3").hide();
  $("#4").hide();
});

When I load the page I can see fieldset 1 and fieldset 2.  If I refresh the page, it looks perfect, but upon first load, it's weird.  Any suggestions?

Body:
First thing you need to do is properly name your ID's.  ID's can't start with a number.

If you change the name to set_1 you can do the initial hide with CSS.

#set_2, #set_3, #set_4 { display:none; }

No JS needed.


问:
Elixir/Phoenix date from weekday + weeknumber
Is it possible to get date (day, month, year) by providing week number and weekday? Basically I need query for this week's monday.

I've checked Erlang, there is :erlang.date |> :calendar.day_of_the_week which returns the weekday. However, is there a way to reverse this function? Provide weekday, week number and year to get the exact date?

Thank you

答:
Is it possible to get date (day, month, year) by providing week number and weekday?

Maybe something like this would work:

```<code>@doc """
iex>get_date(1, 1, 2018)
{:ok, ~D[2018-01-01]}
"""
def get_date(weekday, _week_number, _year)
    when weekday < 1 or weekday > 7,
    do: {:error, "invalid weekday: #{inspect(weekday)}"}

def get_date(_weekday, week_number, _year)
    when week_number < 0 or week_number > 51,
    do: {:error, "invalid week_number: #{inspect(week_number)}"}

def get_date(weekday, week_number, year) do
  case Date.new(year, 1, 1) do
    {:ok, first_day_of_year} ->
      Date.add(first_day_of_year, week_number * 7 + weekday - 1)

    {:error, error} ->
      {:error, error}
  end
end
</code>```

Body:
Is it possible to get date (day, month, year) by providing week number and weekday?

Maybe something like this would work:

@doc """
iex>get_date(1, 1, 2018)
{:ok, ~D[2018-01-01]}
"""
def get_date(weekday, _week_number, _year)
    when weekday < 1 or weekday > 7,
    do: {:error, "invalid weekday: #{inspect(weekday)}"}

def get_date(_weekday, week_number, _year)
    when week_number < 0 or week_number > 51,
    do: {:error, "invalid week_number: #{inspect(week_number)}"}

def get_date(weekday, week_number, year) do
  case Date.new(year, 1, 1) do
    {:ok, first_day_of_year} ->
      Date.add(first_day_of_year, week_number * 7 + weekday - 1)

    {:error, error} ->
      {:error, error}
  end
end


问:
Count lines with integers in them using bash and wc -l
A utility on my Linux machine outputs a log to 'stdout'.
In each line, there is either a String or an Integer, it looks like the following:

```<code>[ERROR] resource busy, retrying
0989282882
[DEBUG] starting process with pid 4028
7918361566
1037491392
[DEBUG] starting process with pid 4056
2873187983
7853738301
1290312037
[DEBUG] done with init
1872989829
[DEBUG] cleaning up
8917982882
</code>```

(In reality it is way longer)

I want to count the lines that have integers in them.

I already used: program | grep DEBUG | wc -l to get the debug count (same for ERROR)

But how can I count the integers? They don't have anything static like the strings, that I could grep...

答: I would do this program  | grep -E "^[0-9]+" | wc -l. This will match lines which start with 1 or more digits. Seems like enough for your use case.

Body:
A utility on my Linux machine outputs a log to 'stdout'.
In each line, there is either a String or an Integer, it looks like the following:

[ERROR] resource busy, retrying
0989282882
[DEBUG] starting process with pid 4028
7918361566
1037491392
[DEBUG] starting process with pid 4056
2873187983
7853738301
1290312037
[DEBUG] done with init
1872989829
[DEBUG] cleaning up
8917982882

(In reality it is way longer)

I want to count the lines that have integers in them.

I already used: program | grep DEBUG | wc -l to get the debug count (same for ERROR)

But how can I count the integers? They don't have anything static like the strings, that I could grep...


问:
HTTP Live streaming is not readable and not work in AVPlayer Swift
I am just trying to play network stream in AVPlayer. I can't share the link but this is some informations about :

And the code :

```<code>let asset = AVAsset(url: inUrl)
let playerItem = AVPlayerItem(asset: asset)
let playern = AVPlayer(playerItem: playerItem)

print("playable = \(asset.isReadable)") // => false

playern.allowsExternalPlayback = true
playern.play()
</code>```

Is there something that I'm missing ?

答:
The step I’m missing was to fragment my mpeg-ts to HLS because AVPlayer can't read my stream.

I finally chose to use MobileVLCKit (https://code.videolan.org/videolan/VLCKit) which provide VLCMediaPlayer natively play my network stream.

Body:
I am just trying to play network stream in AVPlayer. I can't share the link but this is some informations about :

And the code :

let asset = AVAsset(url: inUrl)
let playerItem = AVPlayerItem(asset: asset)
let playern = AVPlayer(playerItem: playerItem)

print("playable = \(asset.isReadable)") // => false

playern.allowsExternalPlayback = true
playern.play()

Is there something that I'm missing ?


Title: Count lines with integers in them using bash and wc -l

Body: program | grep '^[0-9].*$' | wc -l


问:
Uncaught TypeError: Cannot set property 'value' of undefined for input fields
I have this code:

```<code>var username = 'xyz';
var password = 'xyz';
var input = document.getElementsByClassName('_2hvTZ pexuQ zyHYP');
var button = document.getElementsByClassName('sqdOP L3NKy y3zKF');
input[0].value = username;
input[1].value = password;
button.click();
</code>```

Every time I get this error, but in the console, the two input fields are found in the dom.

Uncaught TypeError: Cannot set property 'value' of undefined

I'm able to get the HTML collection array of the two elements.

This is the outerHTML of them:

```<code><input aria-label="Password" aria-required="true" autocapitalize="off" autocorrect="off" name="password" type="password" class="_2hvTZ pexuQ zyHYP" value="">

<input aria-label="Numero di telefono, nome utente o e-mail" aria-required="true" autocapitalize="off" autocorrect="off" maxlength="75" name="username" type="text" class="_2hvTZ pexuQ zyHYP" value="">"
</code>```

Here is a screen of the consolle

Any solution?

答:
A class name cannot contain spaces. If you are looking for elements with each of those space-separated classes, use querySelectorAll instead of getElementsByClassName:

```<code>const input = document.querySelectorAll('._2hvTZ.pexuQ.zyHYP');
const button = document.querySelectorAll('.sqdOP.L3NKy.y3zKF');
</code>```

As mentioned before, since button will be an array-like NodeList, which has no click() method.

Here's an example with the HTML you added in the comments:

const input = document.querySelectorAll('._2hvTZ.pexuQ.zyHYP');

console.log(input.length); // let's see how many there are
input[0].value = "I'm here";
input[1].value = "and here";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input aria-label="Password" aria-required="true" autocapitalize="off" autocorrect="off" name="password" type="password" class="_2hvTZ pexuQ zyHYP" value="">
<input aria-label="Numero di telefono, nome utente o e-mail" aria-required="true" autocapitalize="off" autocorrect="off" maxlength="75" name="username" type="text" class="_2hvTZ pexuQ zyHYP" value=""></code>```

Body:
I have this code:

var username = 'xyz';
var password = 'xyz';
var input = document.getElementsByClassName('_2hvTZ pexuQ zyHYP');
var button = document.getElementsByClassName('sqdOP L3NKy y3zKF');
input[0].value = username;
input[1].value = password;
button.click();

Every time I get this error, but in the console, the two input fields are found in the dom.

Uncaught TypeError: Cannot set property 'value' of undefined

I'm able to get the HTML collection array of the two elements.

This is the outerHTML of them:

<input aria-label="Password" aria-required="true" autocapitalize="off" autocorrect="off" name="password" type="password" class="_2hvTZ pexuQ zyHYP" value="">

<input aria-label="Numero di telefono, nome utente o e-mail" aria-required="true" autocapitalize="off" autocorrect="off" maxlength="75" name="username" type="text" class="_2hvTZ pexuQ zyHYP" value="">"

Here is a screen of the consolle

Any solution?

Body:
A class name cannot contain spaces. If you are looking for elements with each of those space-separated classes, use querySelectorAll instead of getElementsByClassName:

const input = document.querySelectorAll('._2hvTZ.pexuQ.zyHYP');
const button = document.querySelectorAll('.sqdOP.L3NKy.y3zKF');

As mentioned before, since button will be an array-like NodeList, which has no click() method.

Here's an example with the HTML you added in the comments:

const input = document.querySelectorAll('._2hvTZ.pexuQ.zyHYP');

console.log(input.length); // let's see how many there are
input[0].value = "I'm here";
input[1].value = "and here";

<input aria-label="Password" aria-required="true" autocapitalize="off" autocorrect="off" name="password" type="password" class="_2hvTZ pexuQ zyHYP" value="">
<input aria-label="Numero di telefono, nome utente o e-mail" aria-required="true" autocapitalize="off" autocorrect="off" maxlength="75" name="username" type="text" class="_2hvTZ pexuQ zyHYP" value="">