问:
Unable to gather error info from halting Powershell script
I'm writing a script that will watch a directory for any new mp4 files, then convert the file using HandBrake's CLI tool.  The logic that watches the directory for changes works by itself, but if I drop a large video into the "watched" directory the conversion fails since it kicks off as soon as it sees a new file, before the file has time to finish copying.

I'm using a do until loop to check if the file is locked/downloading and then continues once the file is unlocked/writable.  The loop works as a stand-alone script, but when used inside the filesystem watcher the script it will halt without any errors on this line:

[System.IO.FileStream] $fs = $convertingFile.OpenWrite();

This occurs regardless if $ErrorActionPreference = "SilentlyContinue" is commented out.  I've been unable to gather any log output to see why the script is halting using Start-Transcript or Out-File.

How should I best gather error info about why the script halts once it hits this line?

Bonus:  Why might this script not provide error information?

```<code>    $ErrorActionPreference = "SilentlyContinue"

    function Start-FileSystemWatcher {

      [CmdletBinding()]
      param(
        [Parameter()]
        [string]$Path,
        [Parameter()]
        [ValidateSet('Changed','Created','Deleted','Renamed')]
        [string[]]$EventName,
        [Parameter()]
        [string]$Filter,
        [Parameter()]
        [System.IO.NotifyFilters]$NotifyFilter,
        [Parameter()]
        [switch]$Recurse,
        [Parameter()]
        [scriptblock]$Action
      )

      #region Build  FileSystemWatcher

      $FileSystemWatcher = New-Object System.IO.FileSystemWatcher
      if (-not $PSBoundParameters.ContainsKey('Path')) {
        $Path = $PWD
      }
      $FileSystemWatcher.Path = $Path
      if ($PSBoundParameters.ContainsKey('Filter')) {
        $FileSystemWatcher.Filter = $Filter
      }

      if ($PSBoundParameters.ContainsKey('NotifyFilter')) {
        $FileSystemWatcher.NotifyFilter = $NotifyFilter
      }

      if ($PSBoundParameters.ContainsKey('Recurse')) {
        $FileSystemWatcher.IncludeSubdirectories = $True
      }

      if (-not $PSBoundParameters.ContainsKey('EventName')) {
        $EventName = 'Changed','Created','Deleted','Renamed'
      }

      if (-not $PSBoundParameters.ContainsKey('Action')) {
        $Action = {
          switch ($Event.SourceEventArgs.ChangeType) {
            'Renamed' {
              $Object = "{0} was  {1} to {2} at {3}" -f $Event.SourceArgs[-1].OldFullPath,
              $Event.SourceEventArgs.ChangeType,
              $Event.SourceArgs[-1].FullPath,
              $Event.TimeGenerated
            }

            Default {
              $Object = "{0} was  {1} at {2}" -f $Event.SourceEventArgs.FullPath,
              $Event.SourceEventArgs.ChangeType,
              $Event.TimeGenerated
            }
          }

          $WriteHostParams = @{
            ForegroundColor = 'Green'
            BackgroundColor = 'Black'
            Object = $Object
          }

          Write-Host @WriteHostParams
        }

      }

      $ObjectEventParams = @{
        InputObject = $FileSystemWatcher
        Action = $Action

      }

      foreach ($Item in $EventName) {
        $ObjectEventParams.EventName = $Item
        $ObjectEventParams.SourceIdentifier = "File.$($Item)"
        Write-Verbose "Starting watcher for Event: $($Item)"
        $Null = Register-ObjectEvent @ObjectEventParams
      }

    }

    $FileSystemWatcherParams = @{
      Path = 'X:\share\scripts\ps\converter\input'
      Recurse = $True
      NotifyFilter = 'FileName'
      Verbose = $True
      Action = {
        $Item = Get-Item $Event.SourceEventArgs.FullPath
        $WriteHostParams = @{
          ForegroundColor = 'Green'
          BackgroundColor = 'Black'
        }

        $inputFile = "${PWD}\input\$($Item.Name)".trim()
        $outputFile = "${PWD}\output\$($Item.Name)".trim()
        $logFile = "${PWD}\log\$($Item.Name).txt"
        $testLogFile = "${PWD}\log\$($Item.Name)(t).txt"

        function mp4-Func {
          Start-Transcript -path $logFile
          Write-Host "New mp4 file detected..."
          $convertingFile = New-Object -TypeName System.IO.FileInfo -ArgumentList $inputFile
          $locked = 1
          do {
            [System.IO.FileStream] $fs = $convertingFile.OpenWrite();
            if (!$?) {
                Write-Host "Can't convert yet, file appears to be loading..."
                sleep 2
            }
            else {
                $fs.Dispose()
                $locked = 0
            }
          } until ($locked -eq 0)

          Write-Host "File unlocked and ready for conversion."
          HandBrake
          Stop-Transcript
          $WriteHostParams.Object = "Finished converting: $($Item.Name)"
        }

        function HandBrake {
          .\HandBrakeCLI.exe --input "$inputFile" `
                             --output "$outputFile" `
                             --format av_mp4 `
                             --encoder x264 `
                             --vb 1700 `
                             --two-pass `
                             --aencoder copy:aac `
                             --ab 320 `
                             --arate 48 `
                             --mixdown stereo
        }

        switch -regex ($Item.Extension) {
          '\.mp4' { mp4-Func }
        }

        Write-Host @WriteHostParams
      }

    }
    @( 'Created') | ForEach-Object {
      $FileSystemWatcherParams.EventName = $_
      Start-FileSystemWatcher @FileSystemWatcherParams
    }
</code>```

答: I think you'll find that  $ErrorActionPreference only impact errors at the level of cmdlets, while you hitting a problem in non-cmdlet code.    For that, you'll probably need a try/catch construct.

Body:
I'm writing a script that will watch a directory for any new mp4 files, then convert the file using HandBrake's CLI tool.  The logic that watches the directory for changes works by itself, but if I drop a large video into the "watched" directory the conversion fails since it kicks off as soon as it sees a new file, before the file has time to finish copying.

I'm using a do until loop to check if the file is locked/downloading and then continues once the file is unlocked/writable.  The loop works as a stand-alone script, but when used inside the filesystem watcher the script it will halt without any errors on this line:

[System.IO.FileStream] $fs = $convertingFile.OpenWrite();

This occurs regardless if $ErrorActionPreference = "SilentlyContinue" is commented out.  I've been unable to gather any log output to see why the script is halting using Start-Transcript or Out-File.

How should I best gather error info about why the script halts once it hits this line?

Bonus:  Why might this script not provide error information?

    $ErrorActionPreference = "SilentlyContinue"

    function Start-FileSystemWatcher {

      [CmdletBinding()]
      param(
        [Parameter()]
        [string]$Path,
        [Parameter()]
        [ValidateSet('Changed','Created','Deleted','Renamed')]
        [string[]]$EventName,
        [Parameter()]
        [string]$Filter,
        [Parameter()]
        [System.IO.NotifyFilters]$NotifyFilter,
        [Parameter()]
        [switch]$Recurse,
        [Parameter()]
        [scriptblock]$Action
      )

      #region Build  FileSystemWatcher

      $FileSystemWatcher = New-Object System.IO.FileSystemWatcher
      if (-not $PSBoundParameters.ContainsKey('Path')) {
        $Path = $PWD
      }
      $FileSystemWatcher.Path = $Path
      if ($PSBoundParameters.ContainsKey('Filter')) {
        $FileSystemWatcher.Filter = $Filter
      }

      if ($PSBoundParameters.ContainsKey('NotifyFilter')) {
        $FileSystemWatcher.NotifyFilter = $NotifyFilter
      }

      if ($PSBoundParameters.ContainsKey('Recurse')) {
        $FileSystemWatcher.IncludeSubdirectories = $True
      }

      if (-not $PSBoundParameters.ContainsKey('EventName')) {
        $EventName = 'Changed','Created','Deleted','Renamed'
      }

      if (-not $PSBoundParameters.ContainsKey('Action')) {
        $Action = {
          switch ($Event.SourceEventArgs.ChangeType) {
            'Renamed' {
              $Object = "{0} was  {1} to {2} at {3}" -f $Event.SourceArgs[-1].OldFullPath,
              $Event.SourceEventArgs.ChangeType,
              $Event.SourceArgs[-1].FullPath,
              $Event.TimeGenerated
            }

            Default {
              $Object = "{0} was  {1} at {2}" -f $Event.SourceEventArgs.FullPath,
              $Event.SourceEventArgs.ChangeType,
              $Event.TimeGenerated
            }
          }

          $WriteHostParams = @{
            ForegroundColor = 'Green'
            BackgroundColor = 'Black'
            Object = $Object
          }

          Write-Host @WriteHostParams
        }

      }

      $ObjectEventParams = @{
        InputObject = $FileSystemWatcher
        Action = $Action

      }

      foreach ($Item in $EventName) {
        $ObjectEventParams.EventName = $Item
        $ObjectEventParams.SourceIdentifier = "File.$($Item)"
        Write-Verbose "Starting watcher for Event: $($Item)"
        $Null = Register-ObjectEvent @ObjectEventParams
      }

    }

    $FileSystemWatcherParams = @{
      Path = 'X:\share\scripts\ps\converter\input'
      Recurse = $True
      NotifyFilter = 'FileName'
      Verbose = $True
      Action = {
        $Item = Get-Item $Event.SourceEventArgs.FullPath
        $WriteHostParams = @{
          ForegroundColor = 'Green'
          BackgroundColor = 'Black'
        }

        $inputFile = "${PWD}\input\$($Item.Name)".trim()
        $outputFile = "${PWD}\output\$($Item.Name)".trim()
        $logFile = "${PWD}\log\$($Item.Name).txt"
        $testLogFile = "${PWD}\log\$($Item.Name)(t).txt"

        function mp4-Func {
          Start-Transcript -path $logFile
          Write-Host "New mp4 file detected..."
          $convertingFile = New-Object -TypeName System.IO.FileInfo -ArgumentList $inputFile
          $locked = 1
          do {
            [System.IO.FileStream] $fs = $convertingFile.OpenWrite();
            if (!$?) {
                Write-Host "Can't convert yet, file appears to be loading..."
                sleep 2
            }
            else {
                $fs.Dispose()
                $locked = 0
            }
          } until ($locked -eq 0)

          Write-Host "File unlocked and ready for conversion."
          HandBrake
          Stop-Transcript
          $WriteHostParams.Object = "Finished converting: $($Item.Name)"
        }

        function HandBrake {
          .\HandBrakeCLI.exe --input "$inputFile" `
                             --output "$outputFile" `
                             --format av_mp4 `
                             --encoder x264 `
                             --vb 1700 `
                             --two-pass `
                             --aencoder copy:aac `
                             --ab 320 `
                             --arate 48 `
                             --mixdown stereo
        }

        switch -regex ($Item.Extension) {
          '\.mp4' { mp4-Func }
        }

        Write-Host @WriteHostParams
      }

    }
    @( 'Created') | ForEach-Object {
      $FileSystemWatcherParams.EventName = $_
      Start-FileSystemWatcher @FileSystemWatcherParams
    }


来源: stackexchange

问:
Send HTTP Request and properly ignore the Response in Javascript
Examples abound of methods to initiate a web (HTTP) request in Javascript. But, when I initiate a web request and the server return a blank response, Firefox at least throws an error:

XML Parsing Error: no root element found Location: http://example.com/service Line Number 1, Column 1: 1 service:1:1

I am using a function similar to:

```<code>function RequestGET(url) {
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.send();
}
</code>```

In this particular case, the server has nothing to return and I expect that. So, how do I structure my client-side script to handle this response without throwing this error? Or, more generally, how can I handle a non-XML response properly?

答:
For probably a defensible reason, Firefox sets the default MIME type to XML (not sure if it's text/xml or application/xml). Thankfully, the XMLHttpRequest object has an overrideMimeType method, which I can use to set the MIME type to text/plain.

The following function works to ignore responses, blank or otherwise:

```<code>function RequestGET(url, callback) {
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    if (req.overrideMimeType)
        req.overrideMimeType("text/plain");
    req.send(null);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Examples abound of methods to initiate a web (HTTP) request in Javascript. But, when I initiate a web request and the server return a blank response, Firefox at least throws an error:

XML Parsing Error: no root element found Location: http://example.com/service Line Number 1, Column 1: 1 service:1:1

I am using a function similar to:

function RequestGET(url) {
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.send();
}

In this particular case, the server has nothing to return and I expect that. So, how do I structure my client-side script to handle this response without throwing this error? Or, more generally, how can I handle a non-XML response properly?

Body:
For probably a defensible reason, Firefox sets the default MIME type to XML (not sure if it's text/xml or application/xml). Thankfully, the XMLHttpRequest object has an overrideMimeType method, which I can use to set the MIME type to text/plain.

The following function works to ignore responses, blank or otherwise:

function RequestGET(url, callback) {
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    if (req.overrideMimeType)
        req.overrideMimeType("text/plain");
    req.send(null);
}


问:
How come with JQuery Masonry, when I click "back" on the browser, it shoots the user back to the top?
Why can't it hold the position where the user left off? Is this normal for Masonry?
When the user clicks back, the browser goes to where the user left off, but weirdly, Masonry makes it SHOOT back up to the top!

By the way, refresh works fine. It moves the scroll to where the user left off. But back doesn't work.

Edit: when I click "back", it's up at the top. But then I scroll down just a tiny bit (2 pixels). And then the browser will jump back to the position of the left off place.

ures.

Edit: If I disable this line, it will work:

```<code>$('#grid').masonry({ columnWidth:250, itemSelector:".awallpost", animate:false, resizeable:false });
</code>```

答:
Are you sure this is an issue caused by Masonry? Has the site worked with back button previously? As per BalusC's comment, the issue seems to vary from browser to browser and as confirmed by mr. Chavan, the site sends Cache-Control: no-store so I'm leaning towards server software or configuration causing it rather than Masonry.

It is a documented behaviour for various browsers to go to top of page on back when the HTTP response has certain Cache-Control: headers. (In short: FF goes to top on no-store - or no-cache if using HTTPS, IE doesn't honour Cache-Control on back.)

You can set cache headers either in HTTP server (Apache, lighttpd, etc.) or in code. Every web-targeted language have their metheds of setting HTTP headers, the correct solution to fix the problem depends on the environment you have.

This SO post offers some solutions, including some esoteric methods to store the page scroll position with JS and cookies.

ContentLicense: CC BY-SA 2.5

Body:
Why can't it hold the position where the user left off? Is this normal for Masonry?
When the user clicks back, the browser goes to where the user left off, but weirdly, Masonry makes it SHOOT back up to the top!

By the way, refresh works fine. It moves the scroll to where the user left off. But back doesn't work.

Edit: when I click "back", it's up at the top. But then I scroll down just a tiny bit (2 pixels). And then the browser will jump back to the position of the left off place.

ures.

Edit: If I disable this line, it will work:

$('#grid').masonry({ columnWidth:250, itemSelector:".awallpost", animate:false, resizeable:false });


问:
How to check more than one year in 'leap year'
Just recently started learning C# and did in class the 'leap year'. We came up with this solution. But it only allows to check one year at a time. Is there a nice way to check more at once? Let's say I need to check 10 different years if they are leap or not. All I could think of is copying the block and giving new variable. </p>

```<code>int a = int.Parse(Console.ReadLine());

bool div1 = a % 4 == 0;
bool div2 = a % 100 != 0;
bool div3 = a % 400 == 0;

if ((div1 && div2) || div3)
{
    Console.WriteLine($"{a} is a leap year");
}
else
{
    Console.WriteLine($"{a} is not a leap year");
}
</code>```

答: You can read a string of years (e.g.: 1991,1992,2001,2004), then split the string to array with string.split(','). Loop through the array to check for leap year.

Body:
Just recently started learning C# and did in class the 'leap year'. We came up with this solution. But it only allows to check one year at a time. Is there a nice way to check more at once? Let's say I need to check 10 different years if they are leap or not. All I could think of is copying the block and giving new variable.

int a = int.Parse(Console.ReadLine());

bool div1 = a % 4 == 0;
bool div2 = a % 100 != 0;
bool div3 = a % 400 == 0;

if ((div1 && div2) || div3)
{
    Console.WriteLine($"{a} is a leap year");
}
else
{
    Console.WriteLine($"{a} is not a leap year");
}


问:
What alternatives are there for Docker on Solaris 11.3?
I'm trying to set up something similar to Docker for deploying a spring application in Solaris. I thought of Solaris zones but it doesn't seem to be that simple or I'm having a difficult time wrapping my head around it.

I welcome helpful suggestions, thanks.

答:
I would suggest two options:

1) Create a zone with 'minimal-server' pack installed. Install your application and all dependencies. Create a Unified Archive from that zone. Create a profile for the new zone (with user/password, IP, hostname, etc. -- to avoid doing that at the first boot). Install the zone from that unified archive using the profile you've just created. It's pretty fast--with 'minimal-server' it took me 2-2.5 minutes in VirtualBox. Will be even faster on bare metal.

2) Create an IPS package from your app, publish it on the local repository. Create a manifest where you list 'minimal-server', dependencies and your application package. Install the zone with that manifest and profile (like in the first method).

First method is faster and easier, but it's not very flexible. If you want to change your app, you have to re-create your archive. Second method is more flexible (when you update your app, you just repackage it and publish it one the repository), but it could take longer to install (because individual packages take longer to install than a single archive stream).
Please let me know if you need more detailed instructions and links to the docs.


问:
Programmatically change a Google apps script's timezone
I've been having a very hard time trying to properly set up the timezones of calendar event dates because the Javascript's Date object is taking the project's timezone:

.

Is there a way to programmatically change that property?

答: No. The project time zone can not be changed with code. You can get the script time zone Session.getScriptTimeZone() with code, but you can not set it with code. You shouldn't be changing the script time zone in code anyway. I'm assuming that you have users who are in different time zones? If there are multiple users of the script in different time zones, then I set the Time Zone in the script to +GMT 00:00 no daylight savings. And leave it at that.</p>

ContentLicense: CC BY-SA 4.0


问:
How to log source file name and line number in Python
Is it possible to decorate/extend the python standard logging system, so that when a logging method is invoked it also logs the file and the line number where it was invoked or maybe the method that invoked it?</p>

答:
On top of Seb's very useful answer, here is a handy code snippet that demonstrates the logger usage with a reasonable format:

```<code>#!/usr/bin/env python
import logging

logging.basicConfig(format='%(asctime)s,%(msecs)03d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
    datefmt='%Y-%m-%d:%H:%M:%S',
    level=logging.DEBUG)

logger = logging.getLogger(__name__)
logger.debug("This is a debug log")
logger.info("This is an info log")
logger.critical("This is critical")
logger.error("An error occurred")
</code>```

Generates this output:

```<code>2017-06-06:17:07:02,158 DEBUG    [log.py:11] This is a debug log
2017-06-06:17:07:02,158 INFO     [log.py:12] This is an info log
2017-06-06:17:07:02,158 CRITICAL [log.py:13] This is critical
2017-06-06:17:07:02,158 ERROR    [log.py:14] An error occurred
</code>```

OwnerDisplayName: digy

Body:
On top of Seb's very useful answer, here is a handy code snippet that demonstrates the logger usage with a reasonable format:

#!/usr/bin/env python
import logging

logging.basicConfig(format='%(asctime)s,%(msecs)03d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
    datefmt='%Y-%m-%d:%H:%M:%S',
    level=logging.DEBUG)

logger = logging.getLogger(__name__)
logger.debug("This is a debug log")
logger.info("This is an info log")
logger.critical("This is critical")
logger.error("An error occurred")

Generates this output:

2017-06-06:17:07:02,158 DEBUG    [log.py:11] This is a debug log
2017-06-06:17:07:02,158 INFO     [log.py:12] This is an info log
2017-06-06:17:07:02,158 CRITICAL [log.py:13] This is critical
2017-06-06:17:07:02,158 ERROR    [log.py:14] An error occurred


问:
How do I implement this external merge sorting algorithm in C?
I need to simulate an external sorting algorithm considering the machine has only 96 bytes of memory available. I'm using 32 bytes structs that look like this:

```<code>typedef struct {
    char usedmemory[31];
    char key;
}Register32;
</code>```

I'm already do the point of splitting a big tobesorted.txt file in a number of 3 Register32 binaries. For instance:

```<code> I N T E R C A L A C A O B A L A N C E A D A
</code>```

is split into 8 files, which are internally sorted, ranging from file0.bin to file7.bin, containing 31 bytes of trash and 1 byte being the key which is used to sort the registers at all times.

```<code>file0.bin containing INT
file1.bin containing CER
file2.bin containing AAL
file3.bin containing ACO
file4.bin containing ABL
file5.bin containing ACN
file6.bin containing ADE
file7.bin containing A
</code>```

My assignment is to "merge" 2, 3 or 4 of these files into an exit file at any given time and keep merging them until I have the initial word all sorted out. Example: merging file0 with file1 would output C E I N R T
in the exit file. Of course the merging function should be generalized as to read each sorting key at a time and merge into an exit file regardless of file input size. My Merge function receives an array of files that can contain 2, 3 or 4 files (not known by function), the lowest index of mentioned array, the higher index and the exit file. It looks like this:

```<code>void MergeFunction(TypeFile* entry, int lowerindex,int higherindex, TypeFile exitfile){
       int i, j, count = 0;
}
</code>```

TypeFile being only a typedef FILE* TypeFile;.

I know that I should compare each register's key at a time and then write the lowest to exitfile if I need to simulate the memory constrait, but I can't bring myself to think of a way to do it. The loop constraints and the cases in which inputs are 6 or more key characters long are melting my brain. In the end i just want o have that initial tobesorted.txt completely sorted, merging 2, 3 or 4 files at a time into a bigger one and proceeding to the next. This is already implemented, I just need to implement the Merge function.
Sorry if I made myself too difficult to understand, english is not my mother tongue. Appreciate any hep you guys can give.

答:
If you already have splitted and sorted original "chunk" files, what you need is something like this:

```<code>void mergeFiles(FILE* fIn1, FILE* fIn2, FILE* fOut)
{
    int ch1;
    int ch2;
    ch1 = fgetc(fIn1);
    ch2 = fgetc(fIn2);
    // merge files
    while ((ch1 != EOF) && (ch2 != EOF))
    {
        if (ch1 < ch2)
        {
            fputc(ch1, fOut);
            ch1 = fgetc(fIn1);
        }
        else
        {
            fputc(ch2, fOut);
            ch2 = fgetc(fIn2);
        }
    }

    // write the rest of one of the files
    if (ch2 == EOF)
    {
        while (ch1 != EOF)
        {
            fputc(ch1, fOut);
            ch1 = fgetc(fIn1);
        }
    }
    else
    {
        while (ch2 != EOF)
        {
            fputc(ch2, fOut);
            ch2 = fgetc(fIn2);
        }
    }
    fflush(fOut);
}
</code>```

The idea is that the merge stage of the merge sort algorithme requires you only to get first elements of each of the two sub-arrays being merged. Thus a stream input (such as file) fits this requirements as well (i.e. you don't have to read whole files into your RAM!). All you have to do is just to read two sorted files char-by-char, compare those chars, and output to the target file whichever is less. Then you merge these new combined files again until you get one big sorted file.

Body:
I need to simulate an external sorting algorithm considering the machine has only 96 bytes of memory available. I'm using 32 bytes structs that look like this:

typedef struct {
    char usedmemory[31];
    char key;
}Register32;

I'm already do the point of splitting a big tobesorted.txt file in a number of 3 Register32 binaries. For instance:

 I N T E R C A L A C A O B A L A N C E A D A

is split into 8 files, which are internally sorted, ranging from file0.bin to file7.bin, containing 31 bytes of trash and 1 byte being the key which is used to sort the registers at all times.

file0.bin containing INT
file1.bin containing CER
file2.bin containing AAL
file3.bin containing ACO
file4.bin containing ABL
file5.bin containing ACN
file6.bin containing ADE
file7.bin containing A

My assignment is to "merge" 2, 3 or 4 of these files into an exit file at any given time and keep merging them until I have the initial word all sorted out. Example: merging file0 with file1 would output C E I N R T
in the exit file. Of course the merging function should be generalized as to read each sorting key at a time and merge into an exit file regardless of file input size. My Merge function receives an array of files that can contain 2, 3 or 4 files (not known by function), the lowest index of mentioned array, the higher index and the exit file. It looks like this:

void MergeFunction(TypeFile* entry, int lowerindex,int higherindex, TypeFile exitfile){
       int i, j, count = 0;
}

TypeFile being only a typedef FILE* TypeFile;.

I know that I should compare each register's key at a time and then write the lowest to exitfile if I need to simulate the memory constrait, but I can't bring myself to think of a way to do it. The loop constraints and the cases in which inputs are 6 or more key characters long are melting my brain. In the end i just want o have that initial tobesorted.txt completely sorted, merging 2, 3 or 4 files at a time into a bigger one and proceeding to the next. This is already implemented, I just need to implement the Merge function.
Sorry if I made myself too difficult to understand, english is not my mother tongue. Appreciate any hep you guys can give.

Body:
If you already have splitted and sorted original "chunk" files, what you need is something like this:

void mergeFiles(FILE* fIn1, FILE* fIn2, FILE* fOut)
{
    int ch1;
    int ch2;
    ch1 = fgetc(fIn1);
    ch2 = fgetc(fIn2);
    // merge files
    while ((ch1 != EOF) && (ch2 != EOF))
    {
        if (ch1 < ch2)
        {
            fputc(ch1, fOut);
            ch1 = fgetc(fIn1);
        }
        else
        {
            fputc(ch2, fOut);
            ch2 = fgetc(fIn2);
        }
    }

    // write the rest of one of the files
    if (ch2 == EOF)
    {
        while (ch1 != EOF)
        {
            fputc(ch1, fOut);
            ch1 = fgetc(fIn1);
        }
    }
    else
    {
        while (ch2 != EOF)
        {
            fputc(ch2, fOut);
            ch2 = fgetc(fIn2);
        }
    }
    fflush(fOut);
}

The idea is that the merge stage of the merge sort algorithme requires you only to get first elements of each of the two sub-arrays being merged. Thus a stream input (such as file) fits this requirements as well (i.e. you don't have to read whole files into your RAM!). All you have to do is just to read two sorted files char-by-char, compare those chars, and output to the target file whichever is less. Then you merge these new combined files again until you get one big sorted file.


问:
Permanently storing key-value pairs efficiently
I'm working on an application which requires read/write access to key-value pairs (strings) currently saved in a CSV file. At the moment I'm creating hash maps from the file and overwriting when adding new entries but this is leading to a plethora of problems down the line. What's the best way to store and update this data?

Only need to store string pairs

Relatively few entries (<100)

Must be able to update data

答:
If you have so few entries, I suggest properties files, which are basicly handled as HashMaps.

An example for loading and saving of properties files can be found here:
https://www.mkyong.com/java/java-properties-file-examples/

Happy Coding!


问:
bookshelf orderBy ignore case
I am trying to order my collection fetch results by a column which is working so far, but I want the sorting to be case insensitive.  I've gone through the bookshelf docs and searched around here and other forums to no avail.  Is something that requires some raw Knex insertion?  Any help is much appreciated.

Here is my code:

```<code>new Recipes().query('orderBy', 'name', 'asc').fetch({
  withRelated: [
    { instructions: (query) => { query.orderBy('step_number'); }},
    'tags',
    'ingredients',
    'ingredients.alternatives',
    'ingredients.tags'
  ]
});
</code>```

I'd like to do something like:

```<code>new Recipes().query('orderByIgnoreCase', 'name', 'asc').fetch({
  withRelated: [
    { instructions: (query) => { query.orderBy('step_number'); }},
    'tags',
    'ingredients',
    'ingredients.alternatives',
    'ingredients.tags'
  ]
});
</code>```

OR:

```<code>new Recipes().query('orderBy', LOWER('name'), 'asc').fetch({
  withRelated: [
    { instructions: (query) => { query.orderBy('step_number'); }},
    'tags',
    'ingredients',
    'ingredients.alternatives',
    'ingredients.tags'
  ]
});
</code>```

答:
Please try it as below

```<code>Recipes.query(function (qb) {
  qb.orderByRaw('LOWER(name) asc');
})
.fetchAll({
  withRelated: [{
    'instructions': (query) => query.orderBy('step_number'),
    'tags',
    'ingredients',
    'ingredients.alternatives',
    'ingredients.tags'
  }]
})
</code>```

It is also worth noting that postgresql sorting depends the OS

Title: bookshelf orderBy ignore case

Body:
I am trying to order my collection fetch results by a column which is working so far, but I want the sorting to be case insensitive.  I've gone through the bookshelf docs and searched around here and other forums to no avail.  Is something that requires some raw Knex insertion?  Any help is much appreciated.

Here is my code:

new Recipes().query('orderBy', 'name', 'asc').fetch({
  withRelated: [
    { instructions: (query) => { query.orderBy('step_number'); }},
    'tags',
    'ingredients',
    'ingredients.alternatives',
    'ingredients.tags'
  ]
});

I'd like to do something like:

new Recipes().query('orderByIgnoreCase', 'name', 'asc').fetch({
  withRelated: [
    { instructions: (query) => { query.orderBy('step_number'); }},
    'tags',
    'ingredients',
    'ingredients.alternatives',
    'ingredients.tags'
  ]
});

OR:

new Recipes().query('orderBy', LOWER('name'), 'asc').fetch({
  withRelated: [
    { instructions: (query) => { query.orderBy('step_number'); }},
    'tags',
    'ingredients',
    'ingredients.alternatives',
    'ingredients.tags'
  ]
});

Body:
Please try it as below

Recipes.query(function (qb) {
  qb.orderByRaw('LOWER(name) asc');
})
.fetchAll({
  withRelated: [{
    'instructions': (query) => query.orderBy('step_number'),
    'tags',
    'ingredients',
    'ingredients.alternatives',
    'ingredients.tags'
  }]
})

It is also worth noting that postgresql sorting depends the OS


问:
jquery this attr href is undefined
I'm having a weird problem, I've got some links with the class "scrollto" on my page, if you click on it, essentially it just goes to that section on the page. The top links seem to work fine (although they alert undefined when clicked on). The side floating navigation also returns undefined when clicked on, but does nothing.

It works perfectly fine in chrome, but I'm having issues with Firefox and IE (not sure about Mac browsers).

Here's my code:

```<code>$('.scrollto').click(function(e){
    e.preventDefault();
    alert( $(this).attr('href') );
    var aid     = $(this).attr('href').replace('#','');
    var aTag    = $('body').find('.section[name="'+aid+'"]').first();
    var offset  = aTag.offset().top - 90;
    $('html,body').stop().animate({scrollTop:offset},1500);
  });
</code>```

Here's the top links (that work).

```<code><ul>
    <li><span class="number">01</span> <span class="angle">/</span> <a href="#item-01" class="scrollto">Yoga</a></li>
    <li><span class="number">02</span> <span class="angle">/</span> <a href="#item-02" class="scrollto">American Tribal Style Belly Dancing</a></li>
    <li><span class="number">03</span> <span class="angle">/</span> <a href="#item-03" class="scrollto">Tai Chi - Beginner</a></li>
    <li><span class="number">04</span> <span class="angle">/</span> <a href="#item-04" class="scrollto">Tai Chi - Advanced</a></li>
    <li><span class="number">05</span> <span class="angle">/</span> <a href="#item-05" class="scrollto">Chat + Stitch</a></li>
    <li><span class="number">06</span> <span class="angle">/</span> <a href="#item-06" class="scrollto">Bubba Fun</a></li>
    <li><span class="number">07</span> <span class="angle">/</span> <a href="#item-07" class="scrollto">Moving Bodies Gymnastics</a></li>
    <li><span class="number">08</span> <span class="angle">/</span> <a href="#item-08" class="scrollto">Prams in the Park</a></li>
    <li><span class="number">09</span> <span class="angle">/</span> <a href="#item-09" class="scrollto">Storytime</a></li>
    <li><span class="number">10</span> <span class="angle">/</span> <a href="#item-10" class="scrollto">Kimblebees Playgroup</a></li>
    <li><span class="number">11</span> <span class="angle">/</span> <a href="#item-11" class="scrollto">Kindy Gym</a></li>
    <li><span class="number">12</span> <span class="angle">/</span> <a href="#item-12" class="scrollto">Mums Who Make Market</a></li>
    <li><span class="number">13</span> <span class="angle">/</span> <a href="#item-13" class="scrollto">Wow! It's Italian</a></li>
    <li><span class="number">14</span> <span class="angle">/</span> <a href="#item-14" class="scrollto">Cards Club</a></li>
    <li><span class="number">15</span> <span class="angle">/</span> <a href="#item-15" class="scrollto">Walk + Chat</a></li>
    <li><span class="number">16</span> <span class="angle">/</span> <a href="#item-16" class="scrollto">Dream Catcher Adult Workshop</a></li>
    <li><span class="number">17</span> <span class="angle">/</span> <a href="#item-17" class="scrollto">Senior Citizens Club</a></li>
    <li><span class="number">18</span> <span class="angle">/</span> <a href="#item-18" class="scrollto">Rensei Karate</a></li>
    <li><span class="number">19</span> <span class="angle">/</span> <a href="#item-19" class="scrollto">Super Parents Multi Birth Club</a></li>
    <li><span class="number">20</span> <span class="angle">/</span> <a href="#item-20" class="scrollto">Photography - Beginner</a></li>
    <li><span class="number">21</span> <span class="angle">/</span> <a href="#item-21" class="scrollto">Mental Health First Aid for Youth</a></li>
</ul>
</code>```

Here's the side links (which don't work on this particular page, but work on the homepage)

```<code><div class="section-pagination vertical-align">
    <div>
        <div class="previous"><a href="#item-01" class="scrollto"><i class="fa fa-angle-up"></i></a></div>
        <div class="numbers">
            <p><span class="active">1</span></p>
            <p> / </p>
            <p>21</p>
        </div>
        <div class="next"><a href="#item-01" class="scrollto"><i class="fa fa-angle-down"></i></a></div>
    </div>
</div>
</code>```

Here's an example of one of the sections it's supposed to scroll to:

```<code><section id="3" name="item-03" class="section">
    <div class="container large">
        <div class="row">
            <div class="col-md-12">
                <div class="item">
                    <svg class="ie-only" width="600px" height="400px" xmlns="http://www.w3.org/2000/svg"><polygon points="0 400,600 400,600 0,200 0" /></svg>
                    <div class="information">
                        <div class="text">
                            <h2><a href="http://kimberly.customcaraudio.com.au/activities-and-events/programs-and-courses/article/3/tai-chi-beginner.html">Tai Chi - Beginner</a></h2>
                            <h3 class="new">New!</h3>
                            <p>Ever wanted to try Tai Chi, but not sure what it's all about? This...</p>
                            <div class="buttons">
                                <a href="http://kimberly.customcaraudio.com.au/activities-and-events/programs-and-courses/article/3/tai-chi-beginner.html" class="button-next"><i class="fa fa-angle-right"></i></a>
                            </div>
                        </div>
                    </div>
                    <div class="image">
                        <a href="http://kimberly.customcaraudio.com.au/activities-and-events/programs-and-courses/article/3/tai-chi-beginner.html"><img src="/images/thumbnail/image__OODzynSjIndmeWWiXIZg.jpg" alt="Tai Chi - Beginner" width="1170" height="670" /></a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <svg class="clip-svg"><defs><clipPath id="information-path-left" clipPathUnits="objectBoundingBox"><polygon points="0 0,1 0,0.66 1,0 1" /></clipPath></defs></svg>
    <svg class="clip-svg"><defs><clipPath id="information-path-right" clipPathUnits="objectBoundingBox"><polygon points="0.345 0,1 0,1 1,0 1" /></clipPath></defs></svg>
</section>
</code>```

Here's the page:

http://kimberly.customcaraudio.com.au/activities-and-events/programs-and-courses.html

Any help would be great :)

答:
Try changing your javascript to this way</p>

```<code>$('.scrollto').click(function(e){
  e.preventDefault();
  var aid     = $(this).attr('href').replace('#','');
  alert( $(this).attr('href') );
  var aTag    = $('body').find('.section[name="'+aid+'"]').first();
  var offset  = aTag.offset().top - 90;
  $('html,body').stop().animate({scrollTop:offset},1500);
});
</code>```

Title: jquery this attr href is undefined

Body:
I'm having a weird problem, I've got some links with the class "scrollto" on my page, if you click on it, essentially it just goes to that section on the page. The top links seem to work fine (although they alert undefined when clicked on). The side floating navigation also returns undefined when clicked on, but does nothing.

It works perfectly fine in chrome, but I'm having issues with Firefox and IE (not sure about Mac browsers).

Here's my code:

$('.scrollto').click(function(e){
    e.preventDefault();
    alert( $(this).attr('href') );
    var aid     = $(this).attr('href').replace('#','');
    var aTag    = $('body').find('.section[name="'+aid+'"]').first();
    var offset  = aTag.offset().top - 90;
    $('html,body').stop().animate({scrollTop:offset},1500);
  });

Here's the top links (that work).

01 / Yoga

02 / American Tribal Style Belly Dancing

03 / Tai Chi - Beginner

04 / Tai Chi - Advanced

05 / Chat + Stitch

06 / Bubba Fun

07 / Moving Bodies Gymnastics

08 / Prams in the Park

09 / Storytime

10 / Kimblebees Playgroup

11 / Kindy Gym

12 / Mums Who Make Market

13 / Wow! It's Italian

14 / Cards Club

15 / Walk + Chat

16 / Dream Catcher Adult Workshop

17 / Senior Citizens Club

18 / Rensei Karate

19 / Super Parents Multi Birth Club

20 / Photography - Beginner

21 / Mental Health First Aid for Youth

Here's the side links (which don't work on this particular page, but work on the homepage)

1

 /

21

Here's an example of one of the sections it's supposed to scroll to:

                    <svg class="ie-only" width="600px" height="400px" xmlns="http://www.w3.org/2000/svg"><polygon points="0 400,600 400,600 0,200 0" /></svg>

Tai Chi - Beginner

New!

Ever wanted to try Tai Chi, but not sure what it's all about? This...

    <svg class="clip-svg"><defs><clipPath id="information-path-left" clipPathUnits="objectBoundingBox"><polygon points="0 0,1 0,0.66 1,0 1" /></clipPath></defs></svg>
    <svg class="clip-svg"><defs><clipPath id="information-path-right" clipPathUnits="objectBoundingBox"><polygon points="0.345 0,1 0,1 1,0 1" /></clipPath></defs></svg>

Here's the page:

http://kimberly.customcaraudio.com.au/activities-and-events/programs-and-courses.html

Any help would be great :)

Body:
Try changing your javascript to this way

$('.scrollto').click(function(e){
  e.preventDefault();
  var aid     = $(this).attr('href').replace('#','');
  alert( $(this).attr('href') );
  var aTag    = $('body').find('.section[name="'+aid+'"]').first();
  var offset  = aTag.offset().top - 90;
  $('html,body').stop().animate({scrollTop:offset},1500);
});


问:
Using jQuery I need to replace spaces inside href with hyphens
I have a list of links that direct to a page which corresponds to each of the 50 states in the US.

I am looping through each states in an array and adding it the href for each but for states that contain two words I need to replaces the space (' ') between them with a hyphen('-').

example: New York must be replaced with New-York.

href="http://www.projectknow.com/find/New York/" class="spaces">

MUST BE REPLACED WITH

href="http://www.projectknow.com/find/New-York/" class="spaces">

This is what I got so far but it does NOT work. Still new to jQuery and any help would be greatly appreciated.

```<code>var option = '';
for (var i = 0; i < states.length;i++){
    option += '<li><a href="http://www.states.com/find/'+ states[i] +'/"
    class="spaces">'+ states[i] +'</a></li>';
}

$('.menu').append(option);

$("a.spaces").each(function (){
    $(this).attr('href', $(this).attr("href").replace("","-"));
});
</code>```

答:
You're so close!

Problem:

$(this).attr('href', $(this).attr("href").replace("","-"));

because "" != " "

Answer:

$(this).attr('href', $(this).attr("href").replace(" ","-"));

but replace only replaces the first occurrence. We could suggest regex, but as you stated you're still trying to figure things out; regex would just confuse you at this time

```<code>function replaceAll(str, find, replace) {
  str = str.replace(find, replace);
  if(str.indexOf(find) > -1) {
    return replaceAll(str, find, replace);
  }
  return str;
}
</code>```

and then $(this).attr('href', replaceAll($(this).attr('href'), ' ', '+'));

Body:
I have a list of links that direct to a page which corresponds to each of the 50 states in the US.

I am looping through each states in an array and adding it the href for each but for states that contain two words I need to replaces the space (' ') between them with a hyphen('-').

example: New York must be replaced with New-York.

MUST BE REPLACED WITH

This is what I got so far but it does NOT work. Still new to jQuery and any help would be greatly appreciated.

var option = '';
for (var i = 0; i < states.length;i++){
    option += '
'+ states[i] +'
';
}

$('.menu').append(option);

$("a.spaces").each(function (){
    $(this).attr('href', $(this).attr("href").replace("","-"));
});

Body:
You're so close!

Problem:

$(this).attr('href', $(this).attr("href").replace("","-"));

because "" != " "

Answer:

$(this).attr('href', $(this).attr("href").replace(" ","-"));

but replace only replaces the first occurrence. We could suggest regex, but as you stated you're still trying to figure things out; regex would just confuse you at this time

function replaceAll(str, find, replace) {
  str = str.replace(find, replace);
  if(str.indexOf(find) > -1) {
    return replaceAll(str, find, replace);
  }
  return str;
}

and then $(this).attr('href', replaceAll($(this).attr('href'), ' ', '+'));


问:
Does the full header of the email taken from gmail inbox always contain a <return path> tag?
When an email is sent from one gmail account to another gmail account and upon extracting the full headers of the same email received by the recipient in his inbox, here are my two critical questions.

Do the header tags of email taken from the recipients inbox always
contain a Return Path tag?

What other tags need to be definitely present to ascertain the email to be genuine and not tampered?

What does it mean when the content within the  tag is different from the content on the actual subject line?

Example: Subject tag indicates  but the actual subject on the gmail message indicates Hello!

Any response from the google team is most appreciated in this regard.

答:
Yes, the Return-path header field is mandatory. Is is set by the last SMTP server to handle the message. See RFC 5321 for the full, gory detail. This site also has a pretty good plainer English explanation.

An important caveat, as noted in the RFC:

It is possible for the mailbox in the return path to be different

  from the actual sender's mailbox, for example, if error responses are
  to be delivered to a special error handling mailbox rather than to

  the message sender.  When mailing lists are involved, this

  arrangement is common and useful as a means of directing errors to

  the list maintainer rather than the message originator.

So the Return-path header on isn't the best option for verifying email authenticity. If you're looking for methods of verifying authenticity & detecting tampering, look into SPF, DKIM & DMARC. In short:

SPF provides verification that the email originates from a server authorised to send email on behalf of a given domain

DKIM uses message signing to detect message tampering & verify that the email was indeed sent from the domain it claims

DMARC leverages both SPF & DKIM & additionally verifies that the domains involved in all of these processes & in the SMPT chain are all in alignment


问:
How to prevent server blocking php
I'm currently developing a php daemon for connecting and retreiving data from social networks like facebook and twitter. This script allready works but I have some concerns about it.

It's possible to create an infinite amount of accounts that the script has to process and (right now) it runs every 5 minutes to create a 'near' realtime experience. So my concern is that, when, let's say 5000 accounts, have been created and have to be monitored. The script slows down and maybe wil run longer than the 5 minute interval. Is there any way to work around this problem? And better, is there any good way (with php, possible with javascript) to create a better 'near' realtime experience?

Any advice will be great!

Thanks in advance

答:
One option would be to spawn multiple daemons and share duties between them. Perhaps have single central job queue and have the daemons consume that. It's really a server-side issue and Javascript has very little to do with such tasks, as long it's not server-side JS.

If the number of monitored subjects is going into thousands, PHP is not really a viable choice since it's neither inherently multi-threaded nor does it have synchronization features. In mass monitoring scenarios, a dedicated server running a J2EE, .NET or a custom multithreaded application is pretty much a must.

Title: How to prevent server blocking php


问:
How to record the screen in iphone
hi am doing an app in iphone with camera integration.i am using an iphone 3gS for testing.
My client wants to see the app so he has asked me to send a video showing the complete workflow. Since the app uses camera i cant run the app on stimulator.
Is there any app for iphone which captures its screen.
i dont want to jailbreak my iphone</p>

答: iOS 11 will finally allow screen recording.</p>

Title: How to record the screen in iphone


问:
Cannot Change InnerHTML of span class?
I'm new to JavaScript and I cannot understand why my html isn't changing?

I have an Iframe and I'm trying to change the .innerHTML of the span class that the Iframe has created in the DOM.

In the DOM structure, the class is called China

I'm just trying to access this by changing it's innerHTML to Taiwan instead.

here is my code:

```<code><html>
<head>
<title>test</title>
</head>
<body onload="myFunction()">

<iframe class="weather" width="100%" height="600px" frameBorder="0"
src="(this is my iframe src code)></iframe>

<script type="text/javascript">
   function myFunction() {
      document.getElementsByClassName("weather-location")[0].innerHTML = "Taiwan";
   }
</script>
</body>
</html>
</code>```

When I test it in the console log, it brings up that weather-location as [] but whats also bizarre is when I use the selector tool to hover on that weather-location class and go back and re-type in the code it in the console, it changes the class how I wanted?

Also, I don't know if this helps but when it shows up as [] in chrome a little i box pops up saying "value below was evaluated just now".

答:
You can't change the innerHTML of iframes if it's on another domain.

https://developer.mozilla.org/en/docs/Web/HTML/Element/iframe

This kind of iframe is like a window into another webpage you have no control over.

If it is on the same domain you can use something like

```<code>var ifr = document.getElementById( yourIframeId );
var ifrDoc = ifr.contentDocument || ifr.contentWindow.document;
var theForm = ifrDoc.getElementById( yourFormId );
</code>```

SO Question: accessing a form that is in an iframe

Credit to : @le_m

Title: Cannot Change InnerHTML of span class?

Body:
I'm new to JavaScript and I cannot understand why my html isn't changing?

I have an Iframe and I'm trying to change the .innerHTML of the span class that the Iframe has created in the DOM.

In the DOM structure, the class is called China

I'm just trying to access this by changing it's innerHTML to Taiwan instead.

here is my code:

<title>test</title>

When I test it in the console log, it brings up that weather-location as [] but whats also bizarre is when I use the selector tool to hover on that weather-location class and go back and re-type in the code it in the console, it changes the class how I wanted?

Also, I don't know if this helps but when it shows up as [] in chrome a little i box pops up saying "value below was evaluated just now".

Body:
You can't change the innerHTML of iframes if it's on another domain.

https://developer.mozilla.org/en/docs/Web/HTML/Element/iframe

This kind of iframe is like a window into another webpage you have no control over.

If it is on the same domain you can use something like

var ifr = document.getElementById( yourIframeId );
var ifrDoc = ifr.contentDocument || ifr.contentWindow.document;
var theForm = ifrDoc.getElementById( yourFormId );

SO Question: accessing a form that is in an iframe

Credit to : @le_m


问:
Is there any way I could improve this batch script? In terms of formatting, syntax, etc
SO keeps telling me "Please add some context to explain the code sections (or check that you have no incorrectly formatted all of your questions as code). Why does it keep telling me this? I do have comments within the code which explain what each section does. After adding this paragraph, it seems to have allowed me to post.</p>

```<code>REM Runs scva.exe if it is not running; kills process after dosbox.exe is terminated

tasklist /FI "IMAGENAME eq scva.exe" 2>NUL | find /I /N "scva.exe">NUL
if "%ERRORLEVEL%"=="0" (
    goto LoopStart
) else (
    cd "%~dp0../"
    start /min "" "scva.exe"
    goto FirstCheck
)

:FirstCheck
REM Waits until dosbox.exe is started before continuing, so the script doesn't terminate prematurely

tasklist /FI "IMAGENAME eq dosbox.exe" 2>NUL | find /I /N "dosbox.exe">NUL
if "%ERRORLEVEL%"=="0" (
    goto LoopStart
) else (
    goto FirstCheck
)

:LoopStart
REM Exits script if scva.exe is manually terminated, otherwise, goes to CheckDOSBox

tasklist /FI "IMAGENAME eq scva.exe" 2>NUL | find /I /N "scva.exe">NUL
if "%ERRORLEVEL%"=="0" (
    goto CheckDOSBox
) else (
    exit
)

:CheckDOSBox
REM Goes to LoopStart while dosbox.exe is running, otherwise, goes to Kill

tasklist /FI "IMAGENAME eq dosbox.exe" 2>NUL | find /I /N "dosbox.exe">NUL
if "%ERRORLEVEL%"=="0" (
    goto LoopStart
) else (
    goto Kill
)

:Kill
REM Sends command to terminate scva.exe while scva.exe is running, otherwise, exits script

tasklist /FI "IMAGENAME eq scva.exe" 2>NUL | find /I /N "scva.exe">NUL
if "%ERRORLEVEL%"=="0" (
    taskkill /IM scva.exe
    goto Kill
)
exit
</code>```

答:
Using conditionall execution on fail || or success && you can avoid all the if's.

if the label you want to jump to is the next statement, it can be omitted - program flow will reach it nevertheless.

I'd insert some timeout /t 1 or ping -n 1 localhost to have a 1 second delay.

```<code>REM Runs scva.exe if it is not running; kills process after dosbox.exe is terminated

tasklist /FI "IMAGENAME eq scva.exe" 2>NUL | find /I /N "scva.exe">NUL && goto LoopStart
cd "%~dp0../"
start /min "" "scva.exe"

:FirstCheck
REM Waits until dosbox.exe is started before continuing, so the script doesn't terminate prematurely

tasklist /FI "IMAGENAME eq dosbox.exe" 2>NUL | find /I /N "dosbox.exe">NUL || goto FirstCheck

:LoopStart
REM Exits script if scva.exe is manually terminated, otherwise, goes to CheckDOSBox

tasklist /FI "IMAGENAME eq scva.exe" 2>NUL | find /I /N "scva.exe">NUL || exit

:CheckDOSBox
REM Goes to LoopStart while dosbox.exe is running, otherwise, goes to Kill

tasklist /FI "IMAGENAME eq dosbox.exe" 2>NUL | find /I /N "dosbox.exe">NUL && goto LoopStart

:Kill
REM Sends command to terminate scva.exe while scva.exe is running, otherwise, exits script

tasklist /FI "IMAGENAME eq scva.exe" 2>NUL | find /I /N "scva.exe">NUL || exit
taskkill /IM scva.exe
goto Kill
</code>```

Body:
SO keeps telling me "Please add some context to explain the code sections (or check that you have no incorrectly formatted all of your questions as code). Why does it keep telling me this? I do have comments within the code which explain what each section does. After adding this paragraph, it seems to have allowed me to post.

REM Runs scva.exe if it is not running; kills process after dosbox.exe is terminated

tasklist /FI "IMAGENAME eq scva.exe" 2>NUL | find /I /N "scva.exe">NUL
if "%ERRORLEVEL%"=="0" (
    goto LoopStart
) else (
    cd "%~dp0../"
    start /min "" "scva.exe"
    goto FirstCheck
)

:FirstCheck
REM Waits until dosbox.exe is started before continuing, so the script doesn't terminate prematurely

tasklist /FI "IMAGENAME eq dosbox.exe" 2>NUL | find /I /N "dosbox.exe">NUL
if "%ERRORLEVEL%"=="0" (
    goto LoopStart
) else (
    goto FirstCheck
)

:LoopStart
REM Exits script if scva.exe is manually terminated, otherwise, goes to CheckDOSBox

tasklist /FI "IMAGENAME eq scva.exe" 2>NUL | find /I /N "scva.exe">NUL
if "%ERRORLEVEL%"=="0" (
    goto CheckDOSBox
) else (
    exit
)

:CheckDOSBox
REM Goes to LoopStart while dosbox.exe is running, otherwise, goes to Kill

tasklist /FI "IMAGENAME eq dosbox.exe" 2>NUL | find /I /N "dosbox.exe">NUL
if "%ERRORLEVEL%"=="0" (
    goto LoopStart
) else (
    goto Kill
)

:Kill
REM Sends command to terminate scva.exe while scva.exe is running, otherwise, exits script

tasklist /FI "IMAGENAME eq scva.exe" 2>NUL | find /I /N "scva.exe">NUL
if "%ERRORLEVEL%"=="0" (
    taskkill /IM scva.exe
    goto Kill
)
exit

Body:
Using conditionall execution on fail || or success && you can avoid all the if's.

if the label you want to jump to is the next statement, it can be omitted - program flow will reach it nevertheless.

I'd insert some timeout /t 1 or ping -n 1 localhost to have a 1 second delay.

REM Runs scva.exe if it is not running; kills process after dosbox.exe is terminated

tasklist /FI "IMAGENAME eq scva.exe" 2>NUL | find /I /N "scva.exe">NUL && goto LoopStart
cd "%~dp0../"
start /min "" "scva.exe"

:FirstCheck
REM Waits until dosbox.exe is started before continuing, so the script doesn't terminate prematurely

tasklist /FI "IMAGENAME eq dosbox.exe" 2>NUL | find /I /N "dosbox.exe">NUL || goto FirstCheck

:LoopStart
REM Exits script if scva.exe is manually terminated, otherwise, goes to CheckDOSBox

tasklist /FI "IMAGENAME eq scva.exe" 2>NUL | find /I /N "scva.exe">NUL || exit

:CheckDOSBox
REM Goes to LoopStart while dosbox.exe is running, otherwise, goes to Kill

tasklist /FI "IMAGENAME eq dosbox.exe" 2>NUL | find /I /N "dosbox.exe">NUL && goto LoopStart

:Kill
REM Sends command to terminate scva.exe while scva.exe is running, otherwise, exits script

tasklist /FI "IMAGENAME eq scva.exe" 2>NUL | find /I /N "scva.exe">NUL || exit
taskkill /IM scva.exe
goto Kill


问:
How identify a user session ? Rails
i have this routes:

```<code>Rails.application.routes.draw do

  root 'login#new'
  get '/home/inicio', to: 'home#index'

  scope '/login' do
    get '/acesso', to:'login#new'
    post '/acessorecebendo', to:'login#create', as:'user'
    get '/sair', to:'login#destroy'
  end

  resources :login
  resources :home
  resources :produtos
  resources :fornecedors
end
</code>```

the Login controller:

```<code>class LoginController < ApplicationController
  protect_from_forgery

  def new
    if session[:user]
      @user = User.find(session[:user])
    end
  end

  def destroy
    reset_session
    redirect_to "/login/acesso", notice: "Você foi deslogado"
  end

  def create
    user = User.validate(login_params[:email], login_params[:senha])

    if user
      session[:user] = user.id
      redirect_to "/home/inicio", notice: "login feito com sucesso"
    else
      redirect_to "/login/acesso", notice: "Dados incorretos"
    end
  end

  private
  def login_params
    params.require(:login).permit(:email, :senha)
  end
end
</code>```

The home controller:

```<code>    class HomeController < ApplicationController   protect_from_forgery with: :exception

  def new
    @user = User.find_by(id: session[:user])   end

  def index
    @produtos = Produto.all
    render 'inicio'   end

  def show
    if session[:user]
      @user = User.find(session[:user])
    end   end end
</code>```

I'm getting an error on the Home view (new.html.erb):

```<code><header>
  <h2><a href="#">Bem-vindo <%= @user.nome %></a></h2>
  <nav>
</code>```

undefined method `nome' for nil:NilClass

Why i have some problems with the session? I can do the login and i wanna see the user informations of this session on the redirected page, like if i can pass the @user variable assigned on the login action to the home controller to use it.

答:
This is happening because your @user is being set only in index and show, but you are trying to reference it from the new action.

Consider moving this logic to a before_action

```<code>class HomeController < ApplicationController
  before_action if: ->{ session[:user] } do
    @user = User.find_by(id: session[:user])
  end
end
</code>```

If this controller needs to assume that @user is present, you should also have a before_action that handles the case of a missing user account. I usually put this behavior into a AuthenticatedController class and inherit from it where needed.

User.find is not optimal here, because it will throw an exception if no record is found.

Title: How identify a user session ? Rails

Body:
i have this routes:

Rails.application.routes.draw do

  root 'login#new'
  get '/home/inicio', to: 'home#index'

  scope '/login' do
    get '/acesso', to:'login#new'
    post '/acessorecebendo', to:'login#create', as:'user'
    get '/sair', to:'login#destroy'
  end

  resources :login
  resources :home
  resources :produtos
  resources :fornecedors
end

the Login controller:

class LoginController < ApplicationController
  protect_from_forgery

  def new
    if session[:user]
      @user = User.find(session[:user])
    end
  end

  def destroy
    reset_session
    redirect_to "/login/acesso", notice: "Você foi deslogado"
  end

  def create
    user = User.validate(login_params[:email], login_params[:senha])

    if user
      session[:user] = user.id
      redirect_to "/home/inicio", notice: "login feito com sucesso"
    else
      redirect_to "/login/acesso", notice: "Dados incorretos"
    end
  end

  private
  def login_params
    params.require(:login).permit(:email, :senha)
  end
end

The home controller:

    class HomeController < ApplicationController   protect_from_forgery with: :exception

  def new
    @user = User.find_by(id: session[:user])   end

  def index
    @produtos = Produto.all
    render 'inicio'   end

  def show
    if session[:user]
      @user = User.find(session[:user])
    end   end end

I'm getting an error on the Home view (new.html.erb):

Bem-vindo <%= @user.nome %>

undefined method `nome' for nil:NilClass

Why i have some problems with the session? I can do the login and i wanna see the user informations of this session on the redirected page, like if i can pass the @user variable assigned on the login action to the home controller to use it.

Body:
This is happening because your @user is being set only in index and show, but you are trying to reference it from the new action.

Consider moving this logic to a before_action

class HomeController < ApplicationController
  before_action if: ->{ session[:user] } do
    @user = User.find_by(id: session[:user])
  end
end

If this controller needs to assume that @user is present, you should also have a before_action that handles the case of a missing user account. I usually put this behavior into a AuthenticatedController class and inherit from it where needed.

User.find is not optimal here, because it will throw an exception if no record is found.


问:
Manage namespace library (C#)
I am trying to organize a library. My issue is that it would quickly gets very large.

This is what i have so far:

```<code>namespace MyLibrary {

    namespace Math {

        namespace Geometry {

            public class BezierCurve {

                //...
            };
        }

        namespace Combinatorics {

        }
    }

    namespace Collections {

    }

    //...
}
</code>```

Its not many lines of code now, but since BezierCurve alone is around 200 lines, creating all of the classes in the above document is not going to be the way to go.

Is it possible to somehow specify the content of BezierCurve in another document and include / refer to it in the namespace Geometry?

答:
It's recommended to have one type per file (well, with some exceptions). Thus you will have a single namespace without all this nested structure:

```<code>namespace MyLibrary.Math.Geometry
{
    public class BezierCurve
    {
       // ...
    }
}
</code>```

If you want to refer BezierCurve in another file, just add a using directive with appropriate namespace:

```<code>using MyLibrary.Math.Geometry;

namespace MyLibrary.Math.Combinatorics
{
    public class SomeClassFromCombinatoricsWhichUsesBezierCurve
    {
         // ...
    }
}
</code>```

Title: Manage namespace library (C#)

Body:
I am trying to organize a library. My issue is that it would quickly gets very large.

This is what i have so far:

namespace MyLibrary {

    namespace Math {

        namespace Geometry {

            public class BezierCurve {

                //...
            };
        }

        namespace Combinatorics {

        }
    }

    namespace Collections {

    }

    //...
}

Its not many lines of code now, but since BezierCurve alone is around 200 lines, creating all of the classes in the above document is not going to be the way to go.

Is it possible to somehow specify the content of BezierCurve in another document and include / refer to it in the namespace Geometry?

Body:
It's recommended to have one type per file (well, with some exceptions). Thus you will have a single namespace without all this nested structure:

namespace MyLibrary.Math.Geometry
{
    public class BezierCurve
    {
       // ...
    }
}

If you want to refer BezierCurve in another file, just add a using directive with appropriate namespace:

using MyLibrary.Math.Geometry;

namespace MyLibrary.Math.Combinatorics
{
    public class SomeClassFromCombinatoricsWhichUsesBezierCurve
    {
         // ...
    }
}


问:
Restoring database failed in SQL Server 2005 enterprise edition
I have tried to restore a database in SQL Server 2005 enterprise edition on Windows Server 2003. It shows the following error.

```<code>    Restored failed for Server 'MYS'. (Microsoft.SqlServer.Express.Smo)
    Additional information:
    System.Data.SqlClient.SqlError: The database was backed up on a server running version
 9.00.4053. That version is incompatible with this server, which is running version
9.00.1187. Either restore the database on a server that supports the backup, or use a
backup that is compatible with this server.  (Microsoft.SqlServer.Express.Smo)
</code>```

What should I do?

答:
Uninstall the CTP

Install RTM

Install SP3

Restore backup

Hire DBA

Body:
I have tried to restore a database in SQL Server 2005 enterprise edition on Windows Server 2003. It shows the following error.

    Restored failed for Server 'MYS'. (Microsoft.SqlServer.Express.Smo)
    Additional information:
    System.Data.SqlClient.SqlError: The database was backed up on a server running version
 9.00.4053. That version is incompatible with this server, which is running version
9.00.1187. Either restore the database on a server that supports the backup, or use a
backup that is compatible with this server.  (Microsoft.SqlServer.Express.Smo)

What should I do?


问:
Expanding a parent
 to the height of its children
I have a page structure similar to this:

```<code><body>
  <div id="parent">
    <div id="childRightCol">
      /*Content*/
    </div>
    <div id="childLeftCol">
      /*Content*/
    </div>
  </div>
</body>
</code>```

I would like for the parent div to expand in height when the inner div's height increases.

Edit:

One problem is that if the width of the child content expands past the width of the browser window, my current CSS puts a horizontal scrollbar on the parent div.  I would like the scrollbar to be at the page level. Currently my parent div is set to overflow: auto;

Can you please help me with the CSS for this?

答:
This is functioning as described by the spec - several answers here are valid, and consistent with the following:

If it has block-level children, the height is the distance between the top border-edge of the topmost block-level child box that doesn't have margins collapsed through it and the bottom border-edge of the bottommost block-level child box that doesn't have margins collapsed through it. However, if the element has a nonzero top padding and/or top border, or is the root element, then the content starts at the top margin edge of the topmost child. (The first case expresses the fact that the top and bottom margins of the element collapse with those of the topmost and bottommost children, while in the second case the presence of the padding/border prevents the top margins from collapsing.) Similarly, if the element has a nonzero bottom padding and/or bottom border, then the content ends at the bottom margin edge of the bottommost child.

from here: https://www.w3.org/TR/css3-box/#blockwidth

OwnerDisplayName: Steve Horn

Title: Expanding a parent <div> to the height of its children

Body:
I have a page structure similar to this:

      /*Content*/

      /*Content*/

I would like for the parent div to expand in height when the inner div's height increases.

Edit:

One problem is that if the width of the child content expands past the width of the browser window, my current CSS puts a horizontal scrollbar on the parent div.  I would like the scrollbar to be at the page level. Currently my parent div is set to overflow: auto;

Can you please help me with the CSS for this?

LastEditorDisplayName: Steve Horn


问:
WebRTC mouse pointer
Let's say we have a connection from A to B with webRTC. B sees also his own webcam in a window.
Is it possible to view the A mouse arrow on the B window where his own webcam is shown?

(so if Alice is connected with Bob, Alice can use his pointer to indicate to Bob where is the spoon in Bob's kitchen).

答:
Use a data channel to send mouse pointer coordinates from A to B:

var pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();

pc1.onicecandidate = e => pc2.addIceCandidate(e.candidate);
pc2.onicecandidate = e => pc1.addIceCandidate(e.candidate);
pc1.onnegotiationneeded = e =>
  pc1.createOffer().then(d => pc1.setLocalDescription(d))
  .then(() => pc2.setRemoteDescription(pc1.localDescription))
  .then(() => pc2.createAnswer()).then(d => pc2.setLocalDescription(d))
  .then(() => pc1.setRemoteDescription(pc2.localDescription))
  .catch(e => console.log(e));

var dc = pc1.createDataChannel("mouse position");
document.onmousemove = e => dc.send(e.x + ", " + e.y);

pc2.ondatachannel = ({channel}) => channel.onmessage = e => console.log(e.data);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="div"></div>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script></code>```

Then render it in JavaScript on the other end. Low latency is important in peer interactions.

Title: WebRTC mouse pointer

Body:
Use a data channel to send mouse pointer coordinates from A to B:

var pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();

pc1.onicecandidate = e => pc2.addIceCandidate(e.candidate);
pc2.onicecandidate = e => pc1.addIceCandidate(e.candidate);
pc1.onnegotiationneeded = e =>
  pc1.createOffer().then(d => pc1.setLocalDescription(d))
  .then(() => pc2.setRemoteDescription(pc1.localDescription))
  .then(() => pc2.createAnswer()).then(d => pc2.setLocalDescription(d))
  .then(() => pc1.setRemoteDescription(pc2.localDescription))
  .catch(e => console.log(e));

var dc = pc1.createDataChannel("mouse position");
document.onmousemove = e => dc.send(e.x + ", " + e.y);

pc2.ondatachannel = ({channel}) => channel.onmessage = e => console.log(e.data);

<div id="div"></div>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>

Then render it in JavaScript on the other end. Low latency is important in peer interactions.


问:
How to get current item check/uncheked in slick grid event onSelectedRowsChanged
Is there any way to get the current row while selecting the row in a slick grid?
also how to identify that the checkbox state using this?

I am using checkbox selection plugin of a slick grid. and binding a subscribe event of row selection like

```<code>grid.onSelectedRowsChanged.subscribe(function (e, args) {
                        // args.rows : Return the selected rows
                        // Code here
                    });
</code>```

答:
You can use var rtn = getActiveCell(); to give rtn.row, rtn.cell and rtn.grid.
grid.getSelectedRows() will tell you the row selections as an array of row indexes. If the active row is in that array, then the checkbox is ticked.

Body:
Is there any way to get the current row while selecting the row in a slick grid?
also how to identify that the checkbox state using this?

I am using checkbox selection plugin of a slick grid. and binding a subscribe event of row selection like

grid.onSelectedRowsChanged.subscribe(function (e, args) {
                        // args.rows : Return the selected rows
                        // Code here
                    });


问:
How do I set a checkbox to unchecked based on php var - previous posts don't fix my issue
I have a php var ($testx) set to 0.

Html code looks like this:

```<code><input type='checkbox' name='test_cb' id='test_cb' checked=<?= $testx == true ? 'checked' : '0' ?>></input>
</code>```

The checkbox is always checked even though the php var being checked is false.  I must be missing something obvious.

答:
You're close :)...</p>

```<code><input type='checkbox' name='test_cb' id='test_cb' <?= $testx == true ? 'checked' : '' ?>></input>
</code>```

Body:
I have a php var ($testx) set to 0.

Html code looks like this:

<input type='checkbox' name='test_cb' id='test_cb' checked=<?= $testx == true ? 'checked' : '0' ?>></input>

The checkbox is always checked even though the php var being checked is false.  I must be missing something obvious.

Body:
You're close :)...

<input type='checkbox' name='test_cb' id='test_cb' <?= $testx == true ? 'checked' : '' ?>></input>


问:
Yii2-admin and Yii2-user compatibility
I am trying to use yii2-user and yii2-admin for my yii2 project.

If I use this configuration in my composer

```<code>    "dektrium/yii2-user": "0.9.*@dev",
    "mdmsoft/yii2-admin": "~2.0",
</code>```

I get errors in admin module. They are simply not compatible. One error was that yii2 user does not have the status column in the user table. It used to work with this configuration.

```<code>    "dektrium/yii2-user": "0.9.*@dev",
    "mdmsoft/yii2-admin": "*",
</code>```

However I found that from recently the composer updates for this setting results in a memory error. Even if it does succeed it takes a little less than forever to complete. Can someone tell me if there are stable compatible versions for both these packages? Can you also suggest other modules which we can use for user and rights configuration? thanks

答:
It appears to me your mixing extensions.

Try dektrium/yii2-rbac instead of mdmsoft/yii2-admin,

Per the dektrium/yii2-rbac docs:

Integrated with Yii2-user - flexible user management module

https://github.com/dektrium/yii2-rbac

https://github.com/dektrium/yii2-user

Title: Yii2-admin and Yii2-user compatibility

Body:
I am trying to use yii2-user and yii2-admin for my yii2 project.

If I use this configuration in my composer

    "dektrium/yii2-user": "0.9.*@dev",
    "mdmsoft/yii2-admin": "~2.0",

I get errors in admin module. They are simply not compatible. One error was that yii2 user does not have the status column in the user table. It used to work with this configuration.

    "dektrium/yii2-user": "0.9.*@dev",
    "mdmsoft/yii2-admin": "*",

However I found that from recently the composer updates for this setting results in a memory error. Even if it does succeed it takes a little less than forever to complete. Can someone tell me if there are stable compatible versions for both these packages? Can you also suggest other modules which we can use for user and rights configuration? thanks


问:
How to Make Header Menu Vertically Aligned & Icon aligned to the left
I'm trying to make a header for a webpage that has a horizontal menu tab (composed of links to other html files), but I find it hard to align the icon on the same horizontal row as the menu tab while keeping the icon and tabs aligned differently (icon to the left, tabs to the right). When I move the icon out of the same group as the links and use css to make them aligned differently, the result is the two (icon and tabs) being in separate rows. I even tried using the align attribute directly to the image tag but it made everything align to the left as well.

So here is my code so far, using a random logo image.

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
    <title>[Website-Name] | Home</title>
</head>
<style type="text/css">
    img {
        text-align: left;
    }
    ul {
        text-align: right;
        padding: 0px;
        margin: 0px
    }
    a{
        color: white;
        text-decoration: none; /* remove link underline*/
        font-size: 20px;
    }
    div/*MENU CSS*/ {
        background: black;
    }

    a:hover /* Change color mouse hover */,
    a:active {
        color: orange;
    }

    li { /*Space between tabs */
        display: inline;
        padding: 0px 25px 0px 25px; /* distance between menu tabs*/
            vertical-align: middle;
    }

</style>
<body>
    <nav>
    <div>
    <img src="icon.jpg">
        <ul>
            <li><a href="index.html">Home</a></li>
            <li><a href="drawing.html">Drawing</a></li>
            <li><a href="music.html">Music</a></li>
            <li><a href="handcrafted.html">Handcrafted</a></li>
            <li><a href="literature.html">Literature</a></li>
            <li><a href="search.html">Search</a></li>
        </ul>
    </div>
    </nav>
</body>
</html>
</code>```

So here is an image comparing what I would like the code to do and what the code (above) is actually doing:
https://i.stack.imgur.com/hTGob.jpg

And here is the icon.jpg used in the code above:
https://i.stack.imgur.com/qW4UU.jpg

Thanks in advance, and please ask if there is something you would like me to clarify on!

答:
You can use flexbox with the following settings for your DIV which is inside nav:

(note: i reduced the padding so all menu items would fit into the snippet widow next to each other)

```<code>nav>div {
  height: 100px;
  display: flex;
  align-items: center;
}
</code>```

nav>div {
  height: 100px;
  display: flex;
  align-items: center;
}

img {
  text-align: left;
}

ul {
  text-align: right;
  padding: 0px;
  margin: 0px
}

a {
  color: white;
  text-decoration: none;
  /* remove link underline*/
  font-size: 20px;
}

div
/*MENU CSS*/

{
  background: black;
}

a:hover
/* Change color mouse hover */

,
a:active {
  color: orange;
}

li {
  /*Space between tabs */
  display: inline;
  padding: 0px 10px 0px 10px;
  /* distance between menu tabs*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <div>
    <img src="http://placehold.it/50x40/fa0">
    <ul>
      <li>Home</li>
      <li>Drawing</li>
      <li>Music</li>
      <li>Handcrafted</li>
      <li>Literature</li>
      <li>Search</li>
    </ul>
  </div>
</nav></code>```

Body:
I'm trying to make a header for a webpage that has a horizontal menu tab (composed of links to other html files), but I find it hard to align the icon on the same horizontal row as the menu tab while keeping the icon and tabs aligned differently (icon to the left, tabs to the right). When I move the icon out of the same group as the links and use css to make them aligned differently, the result is the two (icon and tabs) being in separate rows. I even tried using the align attribute directly to the image tag but it made everything align to the left as well.

So here is my code so far, using a random logo image.

<!DOCTYPE html>

<meta charset="UTF-8"/>
    <title>[Website-Name] | Home</title>

Home

Drawing

Music

Handcrafted

Literature

Search

So here is an image comparing what I would like the code to do and what the code (above) is actually doing:
https://i.stack.imgur.com/hTGob.jpg

And here is the icon.jpg used in the code above:
https://i.stack.imgur.com/qW4UU.jpg

Thanks in advance, and please ask if there is something you would like me to clarify on!

Body:
You can use flexbox with the following settings for your DIV which is inside nav:

(note: i reduced the padding so all menu items would fit into the snippet widow next to each other)

nav>div {
  height: 100px;
  display: flex;
  align-items: center;
}

nav>div {
  height: 100px;
  display: flex;
  align-items: center;
}

img {
  text-align: left;
}

ul {
  text-align: right;
  padding: 0px;
  margin: 0px
}

a {
  color: white;
  text-decoration: none;
  /* remove link underline*/
  font-size: 20px;
}

div
/*MENU CSS*/

{
  background: black;
}

a:hover
/* Change color mouse hover */

,
a:active {
  color: orange;
}

li {
  /*Space between tabs */
  display: inline;
  padding: 0px 10px 0px 10px;
  /* distance between menu tabs*/
}

<nav>
  <div>
    <img src="http://placehold.it/50x40/fa0">
    <ul>
      <li><a href="index.html">Home</a></li>
      <li><a href="drawing.html">Drawing</a></li>
      <li><a href="music.html">Music</a></li>
      <li><a href="handcrafted.html">Handcrafted</a></li>
      <li><a href="literature.html">Literature</a></li>
      <li><a href="search.html">Search</a></li>
    </ul>
  </div>
</nav>


问:
Reference list object by a variable is different than for (some) other objects?
In defining variable of a list object, for example:

```<code>x = [1,2,0.2,3,4]
y = x
x.sort()
</code>```

I would expect that y is still equal to [1, 2, 0.2, 3, 4], but it does not. The value of y changed as x changed. To counter this, I found that using y = x.copy() can preserve the value in the first line.

On the other hand, another example :

```<code>x = 5
y = x
x = 4
</code>```

from this the value of y is still 5, it does not change as x change.

My question : is this due to the design in list's class, or there is another explanation? I found the dynamic change also happen when using x.append(value). Any insight is appreciated. Regards, Arief

答:
The problem is, y and x are just references to the class list.

When you do something like:

```<code>y=x
</code>```

You are coping the reference of the class and not creating another one.

When using copy you are doing a shallow copy that are creating a new class, copying all elements again to this new object.

Python manual presents a explanation and others operators used to actually copy a full class.

Body:
In defining variable of a list object, for example:

x = [1,2,0.2,3,4]
y = x
x.sort()

I would expect that y is still equal to [1, 2, 0.2, 3, 4], but it does not. The value of y changed as x changed. To counter this, I found that using y = x.copy() can preserve the value in the first line.

On the other hand, another example :

x = 5
y = x
x = 4

from this the value of y is still 5, it does not change as x change.

My question : is this due to the design in list's class, or there is another explanation? I found the dynamic change also happen when using x.append(value). Any insight is appreciated. Regards, Arief

Body:
The problem is, y and x are just references to the class list.

When you do something like:

y=x

You are coping the reference of the class and not creating another one.

When using copy you are doing a shallow copy that are creating a new class, copying all elements again to this new object.

Python manual presents a explanation and others operators used to actually copy a full class.


问:
Undefined reference to std::bad_cast::bad_cast()
I am using cmake with clang++ on linux. I have run into a bit of linker trouble:

```<code>Linking CXX executable "/run/media/toi/Storage E/Dropbox/Programmering/Flictus/bin/main"
CMakeFiles/main.dir/GraphicsEngine/Shader.cpp.o:/run/media/toi/Storage E/Dropbox/Programmering/Flictus/src/GraphicsEngine/Shader.cpp:function std::__1::basic_filebuf<char, std::__1::char_traits<char> >::seekoff(long long, std::__1::ios_base::seekdir, unsigned int): error: undefined reference to 'std::bad_cast::bad_cast()'
CMakeFiles/main.dir/GraphicsEngine/Shader.cpp.o:/run/media/toi/Storage E/Dropbox/Programmering/Flictus/src/GraphicsEngine/Shader.cpp:function std::__1::basic_filebuf<char, std::__1::char_traits<char> >::sync(): error: undefined reference to 'std::bad_cast::bad_cast()'
CMakeFiles/main.dir/GraphicsEngine/Shader.cpp.o:/run/media/toi/Storage E/Dropbox/Programmering/Flictus/src/GraphicsEngine/Shader.cpp:function std::__1::basic_filebuf<char, std::__1::char_traits<char> >::underflow(): error: undefined reference to 'std::bad_cast::bad_cast()'
CMakeFiles/main.dir/GraphicsEngine/Shader.cpp.o:/run/media/toi/Storage E/Dropbox/Programmering/Flictus/src/GraphicsEngine/Shader.cpp:function std::__1::basic_filebuf<char, std::__1::char_traits<char> >::overflow(int): error: undefined reference to 'std::bad_cast::bad_cast()'
</code>```

I'm assuming it is indeed a linker problem since it occurs after linking begins and the relevant headers are included.

I don't get undefined references on std::cout and such.

The code generating the linker error:

```<code>std::ifstream file(shaderFile, std::ios::in | std::ios::binary);
if (file) {
    file.seekg(0, std::ios::end);
    shaderString.resize(file.tellg());
    file.seekg(0, std::ios::beg);
    file.read(&shaderString[0], shaderString.size());
    file.close();
}
</code>```

The project ran fine until above code was added. It runs in Visual Studio 2013 with no problems.

Relevant parts of the cmake files:

```<code>add_compile_options(-stdlib=libc++)
add_compile_options(-std=c++1y)
set(CMAKE_LINKER /usr/bin/clang++) # didn't help when added
set(CMAKE_EXE_LINKER_FLAGS "-lc++ -Wall -fexceptions")
set(CMAKE_CXX_COMPILER /usr/bin/clang++)
set(CMAKE_C_COMPILER /usr/bin/clang)
</code>```

So is there something more i should link with or is it a limitation in clang++?

EDIT: Linker invocation:

```<code>"/usr/bin/ld.gold" -export-dynamic --eh-frame-hdr -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 -o
/run/media/toi/Storage E/Dropbox/Programmering/Flictus/bin/main /usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/../../../../lib64/crt1.o /usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/../../../../lib64/crti.o
/usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/crtbegin.o -L/usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2 -L/usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/../../.. -L/lib
 -L/usr/lib CMakeFiles/main.dir/main.cpp.o CMakeFiles/main.dir/GraphicsEngine/GraphicsEngine.cpp.o CMakeFiles/main.dir/GraphicsEngine/Shader.cpp.o
CMakeFiles/main.dir/GraphicsEngine/TextureLoader.cpp.o CMakeFiles/main.dir/Input/Gamepad.cpp.o CMakeFiles/main.dir/Input/Input.cpp.o CMakeFiles/main.dir/GUI/Font.cpp.o CMakeFiles/main.dir/GUI/GUIEngine.cpp.o
CMakeFiles/main.dir/GUI/GUIRect.cpp.o CMakeFiles/main.dir/GUI/GUISprite.cpp.o CMakeFiles/main.dir/GUI/Objects/Components/GUIText.cpp.o CMakeFiles/main.dir/GUI/Objects/GUIButton.cpp.o
CMakeFiles/main.dir/GUI/Objects/GUIImage.cpp.o CMakeFiles/main.dir/GUI/Objects/GUILabel.cpp.o CMakeFiles/main.dir/GUI/Objects/GUIListBox.cpp.o
CMakeFiles/main.dir/GUI/Objects/GUIObject.cpp.o -lSDL2 -lpthread -lGLEW -lGL -lSOIL -lc++ -lfreetype -lstdc++ -lm -lgcc_s -lgcc -lc -lgcc_s -lgcc /usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/crtend.o /usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/../../../../lib64/crtn.o
</code>```

答:
If you haven't done so already try compiling your code with the prefix g++ instead of gcc EX:

```<code>g++ (file name) :  gcc (file name)
</code>```

The first one is correct.

The reason for this is because using the g++ prefix allows a different library of code to run.

Body:
I am using cmake with clang++ on linux. I have run into a bit of linker trouble:

Linking CXX executable "/run/media/toi/Storage E/Dropbox/Programmering/Flictus/bin/main"
CMakeFiles/main.dir/GraphicsEngine/Shader.cpp.o:/run/media/toi/Storage E/Dropbox/Programmering/Flictus/src/GraphicsEngine/Shader.cpp:function std::__1::basic_filebuf<char, std::__1::char_traits<char> >::seekoff(long long, std::__1::ios_base::seekdir, unsigned int): error: undefined reference to 'std::bad_cast::bad_cast()'
CMakeFiles/main.dir/GraphicsEngine/Shader.cpp.o:/run/media/toi/Storage E/Dropbox/Programmering/Flictus/src/GraphicsEngine/Shader.cpp:function std::__1::basic_filebuf<char, std::__1::char_traits<char> >::sync(): error: undefined reference to 'std::bad_cast::bad_cast()'
CMakeFiles/main.dir/GraphicsEngine/Shader.cpp.o:/run/media/toi/Storage E/Dropbox/Programmering/Flictus/src/GraphicsEngine/Shader.cpp:function std::__1::basic_filebuf<char, std::__1::char_traits<char> >::underflow(): error: undefined reference to 'std::bad_cast::bad_cast()'
CMakeFiles/main.dir/GraphicsEngine/Shader.cpp.o:/run/media/toi/Storage E/Dropbox/Programmering/Flictus/src/GraphicsEngine/Shader.cpp:function std::__1::basic_filebuf<char, std::__1::char_traits<char> >::overflow(int): error: undefined reference to 'std::bad_cast::bad_cast()'

I'm assuming it is indeed a linker problem since it occurs after linking begins and the relevant headers are included.

I don't get undefined references on std::cout and such.

The code generating the linker error:

std::ifstream file(shaderFile, std::ios::in | std::ios::binary);
if (file) {
    file.seekg(0, std::ios::end);
    shaderString.resize(file.tellg());
    file.seekg(0, std::ios::beg);
    file.read(&shaderString[0], shaderString.size());
    file.close();
}

The project ran fine until above code was added. It runs in Visual Studio 2013 with no problems.

Relevant parts of the cmake files:

add_compile_options(-stdlib=libc++)
add_compile_options(-std=c++1y)
set(CMAKE_LINKER /usr/bin/clang++) # didn't help when added
set(CMAKE_EXE_LINKER_FLAGS "-lc++ -Wall -fexceptions")
set(CMAKE_CXX_COMPILER /usr/bin/clang++)
set(CMAKE_C_COMPILER /usr/bin/clang)

So is there something more i should link with or is it a limitation in clang++?

EDIT: Linker invocation:

"/usr/bin/ld.gold" -export-dynamic --eh-frame-hdr -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 -o
/run/media/toi/Storage E/Dropbox/Programmering/Flictus/bin/main /usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/../../../../lib64/crt1.o /usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/../../../../lib64/crti.o
/usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/crtbegin.o -L/usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2 -L/usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/../../.. -L/lib
 -L/usr/lib CMakeFiles/main.dir/main.cpp.o CMakeFiles/main.dir/GraphicsEngine/GraphicsEngine.cpp.o CMakeFiles/main.dir/GraphicsEngine/Shader.cpp.o
CMakeFiles/main.dir/GraphicsEngine/TextureLoader.cpp.o CMakeFiles/main.dir/Input/Gamepad.cpp.o CMakeFiles/main.dir/Input/Input.cpp.o CMakeFiles/main.dir/GUI/Font.cpp.o CMakeFiles/main.dir/GUI/GUIEngine.cpp.o
CMakeFiles/main.dir/GUI/GUIRect.cpp.o CMakeFiles/main.dir/GUI/GUISprite.cpp.o CMakeFiles/main.dir/GUI/Objects/Components/GUIText.cpp.o CMakeFiles/main.dir/GUI/Objects/GUIButton.cpp.o
CMakeFiles/main.dir/GUI/Objects/GUIImage.cpp.o CMakeFiles/main.dir/GUI/Objects/GUILabel.cpp.o CMakeFiles/main.dir/GUI/Objects/GUIListBox.cpp.o
CMakeFiles/main.dir/GUI/Objects/GUIObject.cpp.o -lSDL2 -lpthread -lGLEW -lGL -lSOIL -lc++ -lfreetype -lstdc++ -lm -lgcc_s -lgcc -lc -lgcc_s -lgcc /usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/crtend.o /usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/../../../../lib64/crtn.o

Body:
If you haven't done so already try compiling your code with the prefix g++ instead of gcc EX:

g++ (file name) :  gcc (file name)

The first one is correct.

The reason for this is because using the g++ prefix allows a different library of code to run.


问:
Mapping between Oracle Packages and Java Packages
In my database interfacing library jOOQ, I would like to add support for Oracle (or DB2, etc) packages. I have already implemented stored procedure/function support where every stored object is modelled as a generated Java class. For example, this stored function

```<code>CREATE FUNCTION f_author_exists (author_name VARCHAR2) RETURNS NUMBER;
</code>```

will generate a class that can be used like this (note, there are also lots of convenience methods, this example just shows the general design):

```<code>// A new "function call instance". The function needs to be instanciated
// once per call
FAuthorExists f = new FAuthorExists();

// Set the function parameters on the call instance and call it
f.setAuthorName("Paulo");
f.execute(connection);

// Fetch the result from the function call instance
BigDecimal result = f.getReturnValue();
</code>```

The reason I chose a mapping SQL function -> Java Class is because stored procedures allow complex return values (several OUT, or IN OUT parameters) that I want to be able to fetch one by one after calling the procedure:

```<code>p.getOutParam1();
p.getOutParam2();
</code>```

Now this design works fine with stored functions / procedures, where overloading is not possible. Within Oracle's (or DB2's) packages, however, I can have several functions with the same name, like

```<code>CREATE PACKAGE my_package IS
  FUNCTION f_author_exists (name VARCHAR2) RETURNS NUMBER;
  FUNCTION f_author_exists (name VARCHAR2, country VARCHAR2) RETURNS NUMBER;
END my_package;
</code>```

When I generate a class per function (or procedure), I will have naming clashes with several FAuthorExists Java classes. A lame solution is to add an index to the class name, such as FAuthorExists2, FAuthorExists3. Another lame solution is to generate some sort of hash value (or the value itself) from the parameter names/types directly into the classname, such as FAuthorExistsVARCHAR2, FAuthorExistsVARCHAR2VARCHAR2. Neither solution is desirable for obvious reasons.

Does anyone have a simple solution to this problem? Or maybe an Idea of a better overall design which would not produce such function name overloading issues?

Any feedback appreciated!

答: Your getReturnValue function could determine at call time which overloaded function to call depending on how many input parameters have been set - but I think it will end up being simpler if you stick to something like setParam1 rather than setName

Body:
In my database interfacing library jOOQ, I would like to add support for Oracle (or DB2, etc) packages. I have already implemented stored procedure/function support where every stored object is modelled as a generated Java class. For example, this stored function

CREATE FUNCTION f_author_exists (author_name VARCHAR2) RETURNS NUMBER;

will generate a class that can be used like this (note, there are also lots of convenience methods, this example just shows the general design):

// A new "function call instance". The function needs to be instanciated
// once per call
FAuthorExists f = new FAuthorExists();

// Set the function parameters on the call instance and call it
f.setAuthorName("Paulo");
f.execute(connection);

// Fetch the result from the function call instance
BigDecimal result = f.getReturnValue();

The reason I chose a mapping SQL function -> Java Class is because stored procedures allow complex return values (several OUT, or IN OUT parameters) that I want to be able to fetch one by one after calling the procedure:

p.getOutParam1();
p.getOutParam2();

Now this design works fine with stored functions / procedures, where overloading is not possible. Within Oracle's (or DB2's) packages, however, I can have several functions with the same name, like

CREATE PACKAGE my_package IS
  FUNCTION f_author_exists (name VARCHAR2) RETURNS NUMBER;
  FUNCTION f_author_exists (name VARCHAR2, country VARCHAR2) RETURNS NUMBER;
END my_package;

When I generate a class per function (or procedure), I will have naming clashes with several FAuthorExists Java classes. A lame solution is to add an index to the class name, such as FAuthorExists2, FAuthorExists3. Another lame solution is to generate some sort of hash value (or the value itself) from the parameter names/types directly into the classname, such as FAuthorExistsVARCHAR2, FAuthorExistsVARCHAR2VARCHAR2. Neither solution is desirable for obvious reasons.

Does anyone have a simple solution to this problem? Or maybe an Idea of a better overall design which would not produce such function name overloading issues?

Any feedback appreciated!