text:
Q: Performance analysis of CPUs for parallel executions Recently, I did a "parallel speedup" comparison between two computers with different specifications
1- Single AMD Ryzen 7 1800x running at 3.6GHz. This cpu has 8 physical cores and 16 logical cores (here).
2- Dual Xeon 2695 v3 (Haswell) running at 2.3GHz on one motherboard. Each cpu has 14 physical cores. So, total physical cores are 28 and total logical cores are 56 (here).
I ran one program with different number of threads on both systems. I know that this may not be a fair comparison since the program also uses about 4GB of memory and I didn't tell about memory specs, but the speedup chart is shown below. Note that for each processor,
speedup = (time of one thread on that CPU) / (time of N threads on that CPU)

Therefore, for 1 thread, both Ryzen and Xeon are scaled to 1.

If someone looks at the chart, he may say that the speedup of Xeon is better than Ryzen. For example, with 8 cores, Ryzen has 3.4 speedup while Xeon has 4.69 speedup.
However, if we check the time data, we will see that for 8 threads they have the same execution time. Moreover, Ryzen performs better that Xeon. It is obvious that
S_ryzen = 900/263        <        S_xeon = 1188/253

So, looking at only speedup data, sound misguiding. On the other hand, I do expect that 8 thread ryzen should have less execution time than Xeon, e.g. 200 seconds since it has better single core performance.
What can be concluded about the performance comparison of these two processors? I know the xeon provides more cores, but taking 8 cores (which both have), which processor has higher performance?

A: Let S(U, N) denotes the speedup obtained on system U where the baseline program (the numerator in the speedup formula) uses 1 thread and the improved program uses N threads. That is:
S(U, N) = TimeU(1) / TimeU(N)
Hence:
S(Xeon, 8) > S(Ryzen, 8)
This implies that:
TimeXeon(1) / TimeXeon(8) > TimeRyzen(1) / TimeRyzen(8)
But we cannot conclude anything about how any two execution times are related. We can only say that Xeon has scaled better (i.e., the program was able to make more effective use of the additional resources on Xeon than on Ryzen), but that doesn't mean that it has performed better in terms of execution time. It's just a mathematically invalid conclusion. For example, we can't conclude that TimeXeon(8) > TimeRyzen(8).
However, we can observe that:
S(Xeon, 8) > S(Xeon, 4)
That is:
TimeXeon(1) / TimeXeon(8) > TimeXeon(1) / TimeXeon(4)
The two TimeXeon(1) terms cancel each other and we get:
TimeXeon(4) > TimeXeon(8)
Now here comes the critical observation. Why were we able to deduce from two given speedups how two execution times are related on the same CPU but on on two different CPUs? Because on the same CPU, the baseline is the same in both speedups, which enabled us to cancel them with each other.
So how can we make the same deduction on two different CPUs? By using a shared baseline or reference system. Typically, some old system is chosen as the baseline. For example, you can choose here Willamette, which is a Pentium 4 processor released in 2000. Of course, you need to choose a system that you can run experiments on to measure the baseline execution time. So the speedup can then be calculated as follows:
Sref(U, N) = TimeWillamette(1) / TimeU(N)
Essentially, TimeWillamette(1) becomes the shared term. This formula is much more useful than the previous one. For example, you can easily calculate S(U, N) given only Sref(U, N) as follows:
S(U, N) = Sref(U, N) / Sref(U, 1)
So if Sref(Xeon, 8) > Sref(Xeon, 4), then it's mathematically valid to deduce that TimeXeon(8) < TimeXeon(4). Also if Sref(Xeon, 8) > Sref(Ryzen, 8), then it's mathematically valid to deduce that TimeXeon(8) < TimeRyzen(8). A given relation between two Sref(U, N) speedups on the same or different CPUs contains more information compared to using S(U, N).
The SPEC CPU benchmark suite uses this method to normalize performance metrics. The SPEC CPU 2006 suite uses a machine from 1997:

SPEC uses a historical Sun system, the "Ultra Enterprise 2" which was
  introduced in 1997, as the reference machine. The reference machine
  uses a 296 MHz UltraSPARC II processor, as did the reference machine
  for CPU2000. But the reference machines for the two suites are not
  identical: the CPU2006 reference machine has substantially better
  caches, and the CPU2000 reference machine could not have held enough
  memory to run CPU2006.

The SPEC CPU 2017 uses a more modern machine from 2006:

The reference machine is a historical Sun Microsystems server, the Sun
  Fire V490 with 2100 MHz UltraSPARC-IV+ chips. The UltraSPARC-IV+ was
  introduced in 2006, and is newer than the chip used in the CPU2000 and
  CPU2006 reference machines (the 300 MHz 1997 UltraSPARC II).

The normalized numbers can be compared against each other whether they are from the same system or different systems.
So the reference system should be the most modern system that is older (in particular, slower) than all the systems of interest (i.e., those that may be compared against each other).


text:
Q: How to check if this grammar is ambiguous or not? I´m having trouble to see if this grammar it´s ambiguous or not. How can I check if it is ambiguous?
G = ({S,A,B}, {0,1}, P, S}
P:
S → 0B | 1A
A → 0 | 0S | 1AA
B → 1 | 1S | 0BB

A: What you'd like is an algorithm that, for a given context-free grammar, tells you whether it's ambiguous or not. However, it's been proven that no such algorithm can exist.
One approach is to apply a parser-construction technique that's known to only work for a subset of unambiguous grammars.

*

*If the construction succeeds, then you know for sure that the grammar is unambiguous.

*If the construction fails, then you still don't know: the grammar might be ambiguous, or it might be unambiguous but outside the subset that the technique can handle. However, the way in which the construction fails may give you insight into the problem.

For instance, if you construct the LR(0) automaton for your grammar, you get 2 states with conflicts, so that's inconclusive. But you know that if it is ambiguous, then any sentence that demonstrates the ambiguity would have to involve at least one of those states. (Any sentence that avoids those states could be parsed deterministically.) So you can concentrate on that area of the grammar.
Another approach is to use heuristics. E.g. the production B -> 0BB looks like it might cause ambiguity. (Having the two Bs right next to each other is kind of suspicious.) So you'd concentrate on the BB and ask if there's some way that that can derive a form XYZ where the two Bs 'fight' over the Y. I.e. if there's one derivation where
B -> X   and B -> YZ

and another where
B -> XY  and B -> Z

(and Y is non-empty, of course) then you can use that to demonstrate ambiguity.

A: A grammar is said to be ambiguous if there exists more than one leftmost derivation or more than one rightmost derivation or more than one parse tree for the given input string. If the grammar is not ambiguous, then it is called unambiguous.
Thus, let's try to reproduce 0011 from the above grammar.
Example for 0011:
S->OB->00BB->001B->0011
Example for 1100:
S->1A->11AA->110A->1100
It seems that only one leftmost derivation or rightmost derivation is produced, if parsing this input string. So the grammar is unambigous.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java: automatic repeating print statement I have this piece of code:
import java.io.IOException;

public class Sample {

public static void main(String[] args) throws IOException {
    int b = 3;
    int c = 5;
    char mov;
    while(b != c) {
        System.out.println("Your next move?");
        mov = (char)System.in.read();
        System.out.println(mov);
    }
}
}

and the output:
Your next move?
b
b
Your next move?

Your next move?

Your next move?

why Your next move? is printed 3 times in a row without other codes in while loop be executed?


text:
Q: how to add a new sheet and use it to paste tables in vba i want a macro to add a new sheet and use it to paste some tables, but i when i run the macro again i wanna use the same newly created sheet and not to add a new sheet everytime i run the macro. Can u help me?
I am using the code that folows:
Sub cria_relatorio()

Dim newS As Worksheet, currentS As Worksheet
Dim aba_anterior As Worksheet

lugarAnterior = Selection.Address

Set pos = ActiveSheet
Set currentWB = ThisWorkbook
Set currentS = currentWB.Sheets("fim")
currentS.Range("PRODUTOS").Select 'table that i wanna copy and paste(it changes the values)

Selection.Copy

Sheets("tabelas_por_produto").Activate

   ActiveCell.End(xlUp).Offset(1, 0).Select
       Range("A1").Activate

        If ActiveCell.Value = "" Then

ElseIf Range("a1000").End(xlUp).Offset(2, 0) = "" Then
   Range("a1000").End(xlUp).Offset(2, 0).Select

Else
    Selection.End(xlDown).Select
    ActiveCell.Offset(2, 0).Select
End If

ActiveCell.PasteSpecial _
    Paste:=xlPasteValues, _
    Operation:=xlNone, _
    SkipBlanks:=False, _
    Transpose:=False

ActiveCell.PasteSpecial _
    Paste:=xlPasteFormats, _
    Operation:=xlNone, _
    SkipBlanks:=False, _
    Transpose:=False

ActiveCell.PasteSpecial _
    Paste:=xlPasteColumnWidths, _
    Operation:=xlNone, _
    SkipBlanks:=False, _
    Transpose:=False

     Rows("1:200").AutoFit

End Sub

A: Copy Versions of a Range One Below the Other

*

*Copy the code into a standard module (e.g. Module1).

*Carefully adjust the constants and the workbook if necessary.

*It is assumed that PRODUTO is a defined
name of
a range, with workbook scope.

The Code
Option Explicit

Sub cria_relatorio()

    ' Define constants.
    Const srcName As String = "fim"
    Const tgtName As String = "tabelas_por_produto"
    Const rngName As String = "PRODUTOS"
    Const tgtFirst As String = "A1"
    Const tgtOffset As Long = 2
    Dim wb As Workbook: Set wb = ThisWorkbook

    ' Define Source Range.
    Dim src As Range: Set src = wb.Names(rngName).RefersToRange

    ' Define Target worksheet.
    Dim ws As Worksheet
    On Error Resume Next
    Set ws = wb.Worksheets(tgtName): GoSub NoWorksheet
    On Error GoTo 0

    ' Define Target Cell.
    Dim tgt As Range
    Set tgt = ws.Columns(ws.Range(tgtFirst).Column) _
                .Find("*", , xlValues, , , xlPrevious)
    If tgt Is Nothing Then Set tgt = ws.Range(tgtFirst)
    If tgt.Row < ws.Range(tgtFirst).Row Then Set tgt = ws.Range(tgtFirst)
    Set tgt = tgt.Offset(tgtOffset)

    ' Do copy/paste.
    src.Copy
    With tgt.Resize(src.Rows.Count, src.Columns.Count)
        .PasteSpecial xlPasteValues
        .PasteSpecial xlPasteFormats
        .PasteSpecial xlPasteColumnWidths
        .Rows.AutoFit
    End With

    Exit Sub

NoWorksheet:
    If Err.Number <> 0 Then
        wb.Worksheets.Add
        Set ws = ActiveSheet: ws.Name = tgtName
    End If
    Return

End Sub


text:
Q: How do I mark a radio button as "checked" within my Blazor app, while creating the radio buttons inside of a foreach loop? I am populating a group of radio buttons in my Blazor app with a foreach loop:
Dictionary<string,string> my_radio_options = new Dictionary<string,string>(){
    {"optionone","Option One"}
    {"optiontwo","Option Two"}
    {"optionthree","Option Three"}
    {"optionfour","Option Four"}
    {"optionfive","Option Five"}
}

@foreach (KeyValuePair<String, String> entry in my_radio_options) {
    <input type="radio" name="my_selected_option" id="my_selected_option-@entry.Value" @onclick="() => my_selection = entry.Key">
}

@code {
    private string my_selection;

    private void do_something() {
        // Use "my_selection" here ...
    }
}

I tried this:
<input type="radio" name="my_selected_option" id="my_selected_option-@entry.Value" @onclick="() => my_selection = entry.Key" checked="@(entry.Key.Equals(my_radio_options.ElementAt(1).Key) ? "checked" : "")">

And this:
@{bool first = true;}
@foreach (KeyValuePair<String, String> entry in my_radio_options) {
    <input type="radio" name="my_selected_option" id="my_selected_option-@entry.Value" @onclick="() => my_selection = entry.Key" checked="@(first ? "checked" : "")">
    @(first = false)
}

However, neither one of those works.
How can I do this?

A: There's more than one way to do this, but here's a working version of your code.

*

*my_selection can be either the key or the value, it depends on which you want.

*C# code is not mixed up with the Razor markup - makes it easy to read.

*IsChecked returns true/false.

*Uses onchange event rather that onclicked which is more appropriate for buttons.

@page "/Check"
@foreach (KeyValuePair<String, String> entry in my_radio_options)
{

        <input type="radio" name="my_selected_option" id="my_selected_option-@entry.Value" checked="@this.IsChecked(entry.Key)" @onchange="() => Update(entry.Key)">
        @entry.Value

}

Selected item: @my_selection

@code {
    private string my_selection = "optionthree";

    private void do_something()
    {
        // Use "my_selection" here ...
    }
    Dictionary<string, string> my_radio_options = new Dictionary<string, string> {
        {"optionone","Option One"},
        {"optiontwo","Option Two"},
        {"optionthree","Option Three"},
        {"optionfour","Option Four"},
        {"optionfive","Option Five"},
    };

    private void Update(string value)
    {
        my_selection = value;
    }

    private bool IsChecked(string value)
        => value.Equals(my_selection);
}


text:
Q: Grunt task to compile Bootstrap 4 custom scss I have followed B4 docs and created a _custom.scss file to get a customized css file. I have run a grunt task by executing Gruntfile.js that comes with B4 download. I see that in css folder all files got overwritten because of a new modified date. But comparing a content of new bootstrap.css with the original doesn't show any difference. What am I doing wrong?
Thanks
Update. I have imported _custom.scss. But seems like I am having errors:
D:\bootstrap-4.0.0-alpha.6>grunt
>> Local Npm module "grunt-sass" not found. Is it installed?

Running "clean:dist" (clean) task
>> 1 path cleaned.

Running "exec:sass" (exec) task

> bootstrap@4.0.0-alpha.6 sass D:\bootstrap-4.0.0-alpha.6
> node-sass --output-style expanded --source-map true --precision 6 scss/bootstrap.scss dist/css/bootstrap.css && node-sass --output-style expanded --source-map true --precision 6 scss/bootstrap-grid.scss dist/css/bootstrap-grid.css && node-sass --output-style expanded --source-map true --precision 6 scss/bootstrap-reboot.scss dist/css/bootstrap-reboot.css

>> Rendering Complete, saving .css file...
>> Wrote Source Map to D:\bootstrap-4.0.0-alpha.6\dist\css\bootstrap.css.map
>> Wrote CSS to D:\bootstrap-4.0.0-alpha.6\dist\css\bootstrap.css
>> Rendering Complete, saving .css file...
>> Wrote CSS to D:\bootstrap-4.0.0-alpha.6\dist\css\bootstrap-grid.css
>> Wrote Source Map to D:\bootstrap-4.0.0-alpha.6\dist\css\bootstrap-grid.css.map
>> Rendering Complete, saving .css file...
>> Wrote CSS to D:\bootstrap-4.0.0-alpha.6\dist\css\bootstrap-reboot.css
>> Wrote Source Map to D:\bootstrap-4.0.0-alpha.6\dist\css\bootstrap-reboot.css.map

Running "exec:sass-docs" (exec) task

> bootstrap@4.0.0-alpha.6 sass-docs D:\bootstrap-4.0.0-alpha.6
> node-sass --output-style expanded --source-map true --precision 6 docs/assets/scss/docs.scss docs/assets/css/docs.min.css

>> Rendering Complete, saving .css file...
>> Wrote CSS to D:\bootstrap-4.0.0-alpha.6\docs\assets\css\docs.min.css
>> Wrote Source Map to D:\bootstrap-4.0.0-alpha.6\docs\assets\css\docs.min.css.map

Running "exec:postcss" (exec) task

> bootstrap@4.0.0-alpha.6 postcss D:\bootstrap-4.0.0-alpha.6
> postcss --config grunt/postcss.js --replace dist/css/*.css

Running "exec:clean-css" (exec) task

> bootstrap@4.0.0-alpha.6 clean-css D:\bootstrap-4.0.0-alpha.6
> cleancss --skip-advanced --source-map --output dist/css/bootstrap.min.css dist/css/bootstrap.css && cleancss --skip-advanced --source-map --output dist/css/bootstrap-grid.min.css dist/css/bootstrap-grid.css && cleancss --skip-advanced --source-map --output dist/css/bootstrap-reboot.min.css dist/css/bootstrap-reboot.css

Running "exec:clean-css-docs" (exec) task

> bootstrap@4.0.0-alpha.6 clean-css-docs D:\bootstrap-4.0.0-alpha.6
> cleancss --skip-advanced --source-map --output docs/assets/css/docs.min.css docs/assets/css/docs.min.css

Running "babel:dev" (babel) task
Warning: D:\bootstrap-4.0.0-alpha.6\node_modules\babel-plugin-transform-es2015-modules-strip\lib\index.js:4
      ModuleDeclaration(path) {
                       ^
Unexpected token ( Use --force to continue.

Aborted due to warnings.

Execution Time (2017-03-11 07:32:29 UTC-6)
exec:sass             1.6s  ███████████████████████ 28%
exec:sass-docs       735ms  ███████████ 13%
exec:postcss          1.4s  ████████████████████ 24%
exec:clean-css        1.3s  ███████████████████ 23%
exec:clean-css-docs  687ms  ██████████ 12%
Total 5.7s

Any idea what that might be?
Update 2.
I ran npm install --save-dev grunt-sass and I am not getting:

Local Npm module "grunt-sass" not found. Is it installed?

But:
 Running "babel:dev" (babel) task
    Warning: D:\bootstrap-4.0.0-alpha.6\node_modules\babel-plugin-transform-es2015-modules-strip\lib\index.js:4
          ModuleDeclaration(path) {
                           ^
    Unexpected token ( Use --force to continue.
Aborted due to warnings.

Is still happening.
Update 3. Used -- force to comlete. Dont
Thanks


text:
Q: Coordinate scale different (much smaller) than map I've set up a new project with the CRS set to WGS84 (EPSG:4326). Then I added a google map and a CVS with my Lat/Lon coordinates in degrees. there is nothing else in the CSV other than the header. At a zoomed out view, my points all show up as a single point around the west coast of Africa near (0,0). Please see the first map. When I zoom way in, they are revealed to have the right configuration. Please see the second map. I've included a screenshot from when I add the delimited text layer (numbers after decimal have been crossed out in red for privacy).
How do I fix this?? I know this is something simple..

A: Your screenshots show a map rendered in EPSG:4326 (bottom right), which is geographic coordinates (latitude, longitude). The coordinates of the cursor are also read in the status bar, with numbers in the order of 4 million and 2 million.
So, based on your screenshots, the base layer is being rendered on a world that is at least 4 million degrees wide, so it follows that the system for that layer (base map) is not correct (must be EPSG:3857, but seems to be EPSG:4326).
In my opinion the points are well placed. I sense that you could have changed the system of the base layer. So the solution will be to change it back to the system that corresponds to it.
The project or map can be rendered on any system.


text:
Q: Compromised DigitalOcean droplet routing strange traffic I have a DigitalOcean Ubuntu 16.04 droplet with pre-installed Wordpress. It has SSH login
enabled with root and password login disabled. UFW is enabled.
Not a security expert and only a novice webdev but it seems it has been compromised.
I think this occured because I disabled 'strict SQL mode' as per this tutorial:
https://serverpilot.io/community/articles/how-to-disable-strict-mode-in-mysql-5-7.html
I had a second Wordpress install to install on the server and could only do it with
strict mode disabled. I didn't re-enable it once I completed the install.
Here is an excerpt from the Apache2 error.log file:
[Mon Dec 05 10:32:51.819437 2016] [:error] [pid 15466] [client 172.68.10.110:26708] PHP Warning:  mysqli_query(): MySQL server has gone away in /var/www/html/wp-includes/wp-db.php on line 1868
[Mon Dec 05 10:32:51.821173 2016] [:error] [pid 15466] [client 172.68.10.110:26708] PHP Warning:  mysqli_query(): Error reading result set's header in /var/www/html/wp$
[Mon Dec 05 10:32:51.819142 2016] [:error] [pid 4570] [client 66.249.79.102:64614] PHP Warning:  mysqli_query(): MySQL server has gone away in /var/www/html/wp-include$
[Mon Dec 05 10:32:51.821877 2016] [:error] [pid 4570] [client 66.249.79.102:64614] PHP Warning:  mysqli_query(): Error reading result set's header in /var/www/html/wp-$
[Mon Dec 05 10:32:51.819998 2016] [:error] [pid 3981] [client 173.245.55.78:35305] PHP Warning:  mysqli_query(): MySQL server has gone away in /var/www/html/wp-include$
[Mon Dec 05 10:32:51.822283 2016] [:error] [pid 3981] [client 173.245.55.78:35305] PHP Warning:  mysqli_query(): Error reading result set's header in /var/www/html/wp-$
[Mon Dec 05 15:12:58.198942 2016] [core:error] [pid 17194] (36)File name too long: [client 66.249.79.104:58168] AH00036: access to /read-online-psychedelic-research-in$
[Mon Dec 05 23:02:30.550613 2016] [core:error] [pid 20194] (36)File name too long: [client 66.249.79.98:51473] AH00036: access to /read-online-peoples-temple-including$
[Tue Dec 06 04:15:03.795417 2016] [core:error] [pid 21882] (36)File name too long: [client 66.249.79.98:53902] AH00036: access to /novels-by-tad-williams-including-the$
[Tue Dec 06 07:47:20.068192 2016] [mpm_prefork:notice] [pid 1475] AH00169: caught SIGTERM, shutting down
[Tue Dec 06 07:47:21.097262 2016] [mpm_prefork:notice] [pid 23589] AH00163: Apache/2.4.18 (Ubuntu) configured -- resuming normal operations
[Tue Dec 06 07:47:21.097393 2016] [core:notice] [pid 23589] AH00094: Command line: '/usr/sbin/apache2'
[Tue Dec 06 07:54:16.190667 2016] [mpm_prefork:notice] [pid 23589] AH00169: caught SIGTERM, shutting down
[Tue Dec 06 07:54:32.918723 2016] [mpm_prefork:notice] [pid 1525] AH00163: Apache/2.4.18 (Ubuntu) configured -- resuming normal operations
[Tue Dec 06 07:54:32.934492 2016] [core:notice] [pid 1525] AH00094: Command line: '/usr/sbin/apache2'
[Tue Dec 06 07:55:51.504685 2016] [mpm_prefork:notice] [pid 1525] AH00169: caught SIGTERM, shutting down
[Tue Dec 06 07:55:52.592154 2016] [mpm_prefork:notice] [pid 1906] AH00163: Apache/2.4.18 (Ubuntu) configured -- resuming normal operations
[Tue Dec 06 07:55:52.592279 2016] [core:notice] [pid 1906] AH00094: Command line: '/usr/sbin/apache2'
[Tue Dec 06 08:45:58.655029 2016] [core:error] [pid 2052] (36)File name too long: [client 66.249.79.79:42704] AH00036: access to /read-online-encyclopedia-of-christmas$

And here is an excerpt from the Apache2 access.log file:
130.193.51.38 - - [05/Dec/2016:08:21:55 +0000] "GET /file-archive-1692.xml HTTP/1.1" 404 517 "-" "Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)"
66.249.79.98 - - [05/Dec/2016:08:21:55 +0000] "GET /file-archive-1575.xml HTTP/1.1" 404 516 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.htm$
172.68.11.121 - - [05/Dec/2016:08:21:56 +0000] "GET /steps-for-astaire-by-nigel-roberts.pdf HTTP/1.1" 404 537 "-" "Mozilla/5.0 (compatible; YandexBot/3.0; +http://yand$
66.249.79.98 - - [05/Dec/2016:08:21:56 +0000] "GET /christian-prayer-liturgy-of-the-hours-black-leather.pdf HTTP/1.1" 404 550 "-" "Mozilla/5.0 (compatible; Googlebot/2$
66.249.79.122 - - [05/Dec/2016:08:21:56 +0000] "GET /colonel-roosevelt.pdf HTTP/1.1" 404 514 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.ht$
66.249.79.98 - - [05/Dec/2016:08:21:57 +0000] "GET /definitive-bob-dylan-songbook-music-sales-america.pdf HTTP/1.1" 404 548 "-" "Mozilla/5.0 (compatible; Googlebot/2.1$
172.68.11.131 - - [05/Dec/2016:08:21:57 +0000] "GET /doris-force-at-locked-gates-gytcjx.pdf HTTP/1.1" 404 537 "-" "Mozilla/5.0 (compatible; YandexBot/3.0; +http://yand$
66.249.79.79 - - [05/Dec/2016:08:21:57 +0000] "GET /read-online-le-belv-d-re-du-diable-by-rosemary-carter.pdf HTTP/1.1" 404 548 "-" "Mozilla/5.0 (compatible; Googlebot$
66.249.79.98 - - [05/Dec/2016:08:21:58 +0000] "GET /read-online-furball-and-feathers-by-sean-sweeney.pdf HTTP/1.1" 404 547 "-" "Mozilla/5.0 (compatible; Googlebot/2.1;$
172.68.11.121 - - [05/Dec/2016:08:21:58 +0000] "GET /until-it-breaks-by-suggestivescribe.pdf HTTP/1.1" 404 538 "-" "Mozilla/5.0 (compatible; YandexBot/3.0; +http://yan$
66.249.79.98 - - [05/Dec/2016:08:21:58 +0000] "GET /the-knights-templars-the-key-of-solomon-the-king.pdf HTTP/1.1" 404 547 "-" "Mozilla/5.0 (compatible; Googlebot/2.1;$
66.249.79.81 - - [05/Dec/2016:08:21:59 +0000] "GET /file-archive-845.xml HTTP/1.1" 404 527 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html$
66.249.79.98 - - [05/Dec/2016:08:21:59 +0000] "GET /guide-to-old-radios-pointers-pictures-and-prices.pdf HTTP/1.1" 404 547 "-" "Mozilla/5.0 (compatible; Googlebot/2.1;$
172.68.11.134 - - [05/Dec/2016:08:21:59 +0000] "GET /the-puppet-boy-of-warsaw-eva-weaver.pdf HTTP/1.1" 404 538 "-" "Mozilla/5.0 (compatible; YandexBot/3.0; +http://yan$
66.249.79.98 - - [05/Dec/2016:08:21:59 +0000] "GET /bon-voyage-level-2-student-edition-glencoe-french.pdf HTTP/1.1" 404 548 "-" "Mozilla/5.0 (compatible; Googlebot/2.1$
66.249.79.102 - - [05/Dec/2016:08:22:00 +0000] "GET /read-online-the-seal-s-surprise-baby-by-amy-j-fetzer.pdf HTTP/1.1" 404 552 "-" "Mozilla/5.0 (compatible; Googlebot$
162.158.91.152 - - [05/Dec/2016:08:22:00 +0000] "GET /my-philosophy-for-successful-living.pdf HTTP/1.1" 404 538 "-" "Mozilla/5.0 (compatible; YandexBot/3.0; +http://ya$
66.249.79.106 - - [05/Dec/2016:08:22:00 +0000] "GET /read-online-time-enough-for-drums-by-ann-rinaldi.pdf HTTP/1.1" 404 548 "-" "Mozilla/5.0 (compatible; Googlebot/2.1$

I was using nano to grab these so they got partially cutoff.
As you can see my server is making all these strange GET requests, it looks like torrent traffic or something.
172.68.10.110 and 172.68.11.121 are Russian IPs.
Is this just a consequence of disabling SQL's strict mode? Any advice?

A: This is normal server behavior and nothing of particular concern.
The reason that you are seeing requests for some odd URLs may be that the IP address you were assigned from DigitalOcean was previously used to host another website -- its something that is very common and is nothing to worry about.


text:
Q: jquery tabs not working with multiple fullcalendar I assume I am missing something trivial, but I cannot get jQuery tabs to work with multiple fullCalendar implementations.  ALL calendars are rendered instantly and show one above the next.
Here is the most simplified JSFiddle I could come up with to show the issue:
JSFiddle
I saw a similar question posted, but the solution to add $("..").fullCalendar("render") to the .tabs({show: ...}) seems based on an earlier version of fullCalendar and in any case did not work.
Anyone know what I am doing wrong?

A: This works:   http://jsfiddle.net/L4kqC/30/
Move the calendar elements inside the element on which you are calling tabs() (as per the jQuery UI doc: http://jqueryui.com/tabs/ )
And call tabs() after fullcalendar()  (probably because fullcalendar doesn't like to be instantiated on hidden elements).


text:
Q: Update a SpreadSheet with the google API I'm trying to update a given spreadsheet cell, using node.js googleapis v4 and authorizing with a JWT client.
Reading works fine, but I cannot understand how to write:
    new Promise((resolve, reject) => {

            sheets.spreadsheets.values.update({
                auth: this._auth,
                spreadsheetId: this._metaData.spreadSheetId,
                range: range,
                valueInputOption: 'USER_ENTERED'
            },(err, resp) => {

                if (err) {
                    console.log('Data Error :', err)
                    reject(err);
                }

                resolve(resp);

            });

        });

How do I specify the data, and how do I pass it to the call?
I understand I should use a ValueRange object, but how?

A: After better reviewing the (poor) documentation, I inferred that you had to pass a request object in the call:
return new Promise((resolve, reject) => {
  sheets.spreadsheets.values.update(
    {
      auth: this._auth,
      spreadsheetId: this._metaData.spreadSheetId,
      range: "Sheet1!A1",
      valueInputOption: "USER_ENTERED",
      resource: { range: "Sheet1!A1", majorDimension: "ROWS", values: [["b"]] },
    },
    (err, resp) => {
      if (err) {
        console.log("Data Error :", err);
        reject(err);
      }
      resolve(resp);
    }
  );
});


text:
Q: Twilio gather Is it possible only support some keys in gather I have 4 long messages, when playing the message,
I want to support '#' that end the message, '*' back to choose other message.
So I do like this:
function gather() {
      const gatherNode = twiml.gather({
         numDigits: 1,
         timeout: 5,
         finishOnKey: ''
      });

      gatherNode.play('longmessage_1.mp3');
}

if(request.body.Digits == '*') { ...
}
else if (request.body.Digits == '#') { ...
}
else {
  gather()
}

The question is when user press other key like 1, 2, 3, will cause a break and restart playing message from begining.  So I want to know is it method that ask gather method only support when user click '#' and '*'.

A: Twilio developer evangelist here.
You cannot limit the digits that a user can press with <Gather>.
As a workaround, I could suggest a couple of things.

*

*You could keep the behaviour the same, but as part of your instructions, say "or press any other key to replay the message"

*Or, you could have users press * to go back or any other key to end the message.


text:
Q: How does Javascript's number precision affect large values? So I have a project where I am dealing with both really small numbers and really large numbers.  Essentially I have a counter that is counting up from 10^-9 or so.  Eventually, it reaches 1 and continues counting upwards by a really small factor, but very quickly.
This counter represents a "currency" in my project.  So when the user presses a button, if the "cost" associated with that button is lower than the currency, the cost is subtracted from the user's currency and they are given that item.  Here's what I mean:
if (currency >= itemCost) {
        items++
        currency = currency - itemCost
        itemCost = itemCost * 2

So for example, at the beginning of the game, an example value of currency and itemCost would be 0.000000003020 or so.  When a cost is subtracted at this level, the program works as intended.  However, when I pass 1, it ~SOMETIMES~, stops working and sometimes it doesn't.  Although it will sometimes keep working until it breaks at some arbitrary quantity.  At this point, it will also call the above function if itemCost is more than the currency (at least according to their corresponding labels), leaving the user with a negative currency.
I am wondering if this is happening because the number is too long to represent both the digits greater than 1 and the long string of decimal digits, like 2347.23482348982483 for example.  Is there a limit to how many digits I can accurately represent in Javascript? Would I be okay with rounding the number to say 6 decimal digits after passing 1, or do I need to look into modules that help me with the precision that I need?


text:
Q: Cocoa Swift: how to automate click on html using javascript using in WKWebView I'm loading html page inside of WKWebView and I need to click on a link. For example. loading apple.com
override func viewDidAppear() {
    super.viewDidAppear()
    webView.load(urlString: "https://www.apple.com")
}

and locating the links to click:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
    webView.evaluateJavaScript("document.getElementsByClassName('cta-links')[0].innerHTML") { (result, error) in
        if error != nil {
            print(error?.localizedDescription ?? "")
        }
        if result != nil{
            print("code with links \(result)")
        }
    }

}

The output I'll get is:
Buywith trade in

Learn more

But my question to you guys is how can I click on of those links for example on this link:
Learn more

There is a way to click on that link either with javascript or any other way in swift?
I'll really appreciate your help.

A: To click the following link, you need to identify it in some way, for sake of example I will use the label, as the class is not unique, ideally you would have an ID.
Learn more

In your script you will then need to find this element, you can use querySelectorAll() do to this.
let elementToClick = document.querySelectorAll('[aria-label="Learn more about trade in"]')[0];

And then in your script, call the DOM click() method
elementToClick.click();

This will emulate a click and redirect you to the path given in the href.


text:
Q: How to align applets on Gnome panel Does anyone know how to align applets on Gnome panel? For example I add notification area and there's five icons (you see it on the left of processor icon). Then, I plug my BlueTooth adapter out of my laptop and it's logo disappears, leaving blank space on the right side of applet.
Here's screenshot:

Same happens with any applet that's width can change (for example tray). Is there any way to tell applet "Move right as far as you can".

A: There is a feature request in Gnome's bugzilla asking for a way to do this, so it seems it is not possible at the moment. For now, what you can do is arrange all icons which are always visible at the very right of the panel and lock them (Rightclick->Lock to panel). Then the icons which may vanish at least don't interrupt their position.


text:
Q: The requested page cannot be accessed because the related configuration data for the page is invalid. (with a "catch"...) Another user in my organization put a folder with source code on a central server. I copied the source code to my local machine and when I try to run the application in VS on my local machine I get the following error:
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.

Detailed Error Information:
Module     IIS Web Core
Notification       Unknown
Handler    Not yet determined
Error Code     0x80070005
Config Error       Cannot read configuration file due to insufficient permissions
Config File    \\?\UNC\...\users\username\My Web Sites\Website1\web.config

The issue is with the file location of the problematic .config file:
\\?\UNC...\users\username\My Web Sites\Website1\web.config
This location does not exist on my local machine. I have confirmed with the other user that it does exist on his machine - so it appears that the application is referencing a file location that simply does not exist. My suspicion is that there is some kind of folder/cache that needs to be cleared out, but I don't know what to do in this situation. Any ideas?

A: Ended up actually finding a duplicate question with an answer regarding deleting an applicationhost.config file and then recreating it in VS:
HTTP error 500.19 - Cannot read configuration file


text:
Q: Assigning values to global environment variable using parallel sapply I have recently started working with the parallel package in R and it is working wonders for me. Still, I have encountered an issue for which I have not found answer.
I am trying to reformat some data and, to do so, I use sapply() or parSapply() in the parallel case. In the normal case, I go:
sapply(1:nrow(aux),function(x){
  r=which(M$Project==aux$Projecte[x] & M$Product==aux$Producte[x])
  c=which(names(M)==aux$Atribut[x])
  l=aux$meanss[x]
  M[r,c]<<-l
})

Using <<- to assign value to global environment. For the parallel case, I go:
no_cores <- detectCores()-2
cl <- makeCluster(no_cores)
clusterExport(cl,c("aux","M"))
parSapply(cl,1:20,function(x){
  r=which(M$Project==aux$Projecte[x] & M$Product==aux$Producte[x])
  c=which(names(M)==aux$Atribut[x])
  l=aux$meanss[x]
  M[r,c]<<-l
})

I know that the values are being computed (they are printed) but they are not assigned to the M dataframe the same way as with sapply(). I have looked around but haven't found any information regarding this. Is there any special consideration which I should consider to assign values inside parallel apply functions?
Thank you and please find a reproducible example below.
M:
structure(list(Project = c("11I040119", "11I040119", "11I040119",
"11I040119", "11I040119", "11I040119", "11I040119", "11I040119",
"11I040119", "11I040119", "11I040119", "11I040119", "11I040119"
), Product = c("Brulerie St. Denis (BOLD)", "Ethical Beans (BOLD)",
"Folgers (BOLD)", "Illy drip coffe (BOLD)", "Illy Espresso Coffee (BOLD)",
"Just Us (BOLD)", "Lavazza caffè espresso (BOLD)", "Lavazza Crema e gusto (BOLD)",
"Lavazza Tierra (BOLD)", "Medaglia d'Oro (BOLD)", "Seattle Best 4 (BOLD)",
"Starbucks café Verona (BOLD)", "Tully's (BOLD)"), Thing1 = c(0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Thing2 = c(0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0)), row.names = c(NA, 13L), class = "data.frame")

aux:
structure(list(Projecte = c("11I040119", "11I040119", "11I040119",
"11I040119", "11I040119", "11I040119", "11I040119", "11I040119",
"11I040119", "11I040119", "11I040119", "11I040119", "11I040119",
"11I040119", "11I040119"), Producte = c("Brulerie St. Denis (BOLD)",
"Ethical Beans (BOLD)", "Folgers (BOLD)", "Illy drip coffe (BOLD)",
"Illy Espresso Coffee (BOLD)", "Just Us (BOLD)", "Lavazza caffè espresso (BOLD)",
"Lavazza Crema e gusto (BOLD)", "Lavazza Tierra (BOLD)", "Medaglia d'Oro (BOLD)",
"Seattle Best 4 (BOLD)", "Starbucks café Verona (BOLD)", "Tully's (BOLD)",
"Brulerie St. Denis (BOLD)", "Ethical Beans (BOLD)"), Thing = c("Thing1",
"Thing1", "Thing1", "Thing1", "Thing1", "Thing1", "Thing1", "Thing1",
"Thing1", "Thing1", "Thing1", "Thing1", "Thing1", "Thing2", "Thing2"
), Value = c(0.142857142857143, 0.242857141154153, 0.614285715988704,
0, 0, 0.0714285714285714, 1.01428570917674, 0, 0.971428564616612,
0.5, 0.357142857142857, 0.642857142857143, 0.714285714285714,
3, 5)), row.names = c(NA, 15L), class = "data.frame")

Desired output (M):
     Project                       Product     Thing1 Thing2
1  11I040119     Brulerie St. Denis (BOLD) 0.14285714      3
2  11I040119          Ethical Beans (BOLD) 0.24285714      5
3  11I040119                Folgers (BOLD) 0.61428572      0
4  11I040119        Illy drip coffe (BOLD) 0.00000000      0
5  11I040119   Illy Espresso Coffee (BOLD) 0.00000000      0
6  11I040119                Just Us (BOLD) 0.07142857      0
7  11I040119 Lavazza caffè espresso (BOLD) 1.01428571      0
8  11I040119  Lavazza Crema e gusto (BOLD) 0.00000000      0
9  11I040119         Lavazza Tierra (BOLD) 0.97142856      0
10 11I040119         Medaglia d'Oro (BOLD) 0.50000000      0
11 11I040119         Seattle Best 4 (BOLD) 0.35714286      0
12 11I040119  Starbucks café Verona (BOLD) 0.64285714      0
13 11I040119                Tully's (BOLD) 0.71428571      0

A: Not a full solution, but for the sake of quickness - The parallelization works by launching multiple processes (imagine running multiple R sessions side-by-side). Each of these processes has its own global environment .GlobalEnv, so your M[r,c] <<- l is actually assigning somewhere else per process.
One possible implementation would be that you rewrite your function in a way that for example, you return list(r, c, l) and use parLapply and then you have a list of indices and values collected in parallel and do the assignment in the main process.


text:
Q: Why Does Transfer Of Music To A 32 Gigabyte Micro SDHC Card Keep Failing? I have a large number of music files on my hard drive, and am trying to transfer them onto a 32 gigabyte (31.2 usable) micro SDHC card so I can listen to them using my cellular phone; the transfer always fails.
I'm running Windows 8 - Core X86-64, and my laptop has an SDHC card reader so I'm using a SDHC to micro SDHC adapter. The data totals: 2,126 Files, 250 Folders, and 25.0 GB (26,871,421,564 bytes). The music is mostly m4a (aac), a large amount is m4a (alac), and there are a few mp3s.
If I just use copy/paste in Windows Explorer then it gets a decent amount done, then claims the rest are corrupt, and can't be read, they aren't. I have manually checked some of the files in question, and they are not corrupt. I can copy and paste the data successfully to my external hard drive. I'm using NTFS on my hard drive and FAT32 on the micro SDHC card so I thought perhaps it might be a filesystem problem like max file/dirs so I formatted the card as exFAT and tried again with the same result.
If I copy the data using my preferred method, Synkron Portable it claims to successfully complete, but in actuality it only copies about a 3rd which it claims uses 25 gigabytes of space anyway. If I attempt a secondary copy to add the missing files the the drive runs out of room part way through; GRRRRRRRR!
I've been using an allocation size of 64 kilobytes, but I've also tried 32, default, and some other small ones. I know the adapter isn't the problem because I've tried another one. I know the card isn't the problem because I've tried another one. I know the data isn't corrupt because Synkron and Windows Explorer can copy it to other locations, and it also plays fine in iTunes and VLC. I know the filesystem isn't the problem because using exFAT instead yielded the same results. I know that I'm getting sick and tired of transferring the same data over and over without success in a senario that should have worked 100% of the time.
If you have any ideas (no matter how far fetched) please share them; I'm at my wit's end. :(
EDIT:
It has been suggested that the problem might be a fake card that reports inaccurate storage capacity. To see if this was true I used DD on a Lubuntu live cd to try and fill the card to reveal an approximation of it's true capacity. As you can see from the DD output below the card doesn't appear to be a fake:
lubuntu@lubuntu:~$ sudo dd if=/dev/zero of=/dev/sdb bs=4MB
dd: writing '/dev/sdb': No space left on device
8389+0 records in
8388+0 records out
33554432000 bytes (34 GB) copied, 8257.43 s, 4.1 MB/s

A: The card(s) are defective. I used h2testw 1.4 and the card was not flagged as fake, but some data was flagged as corrupted so h2testw says the card may be defective and I agree.


text:
Q: AutoFill Data with Blank Rows - Google Sheets / Google Apps Script I have the below spreadsheet that I would like to AutoFill the persons name. the issue is that there are blank rows between the names. Each name is in line with a sku2 and needs to be inline with all locations. there can be up to 10 blank rows (due to how many locations).
if I could loop this maybe
function LoopTillLr() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('A2').activate();
  spreadsheet.getActiveRange().autoFillToNeighbor(SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
  spreadsheet.getCurrentCell().getNextDataCell(SpreadsheetApp.Direction.DOWN).activate();
};

Appreciate any help

A: If you only want to replicate the NAME values against variable LOCATION values then use this script:
function myFunction() {
  var ss = SpreadsheetApp.getActiveSheet();
  var lastRow = ss.getDataRange().getLastRow();

  for (var i = 1; i < lastRow+1; i++) {
    if (ss.getRange(i,1).getValue() == "") {
      var value = ss.getRange(i-1,1).getValue();
      ss.getRange(i,1).setValue(value);
    }
  }
}

Ensure that A2 is not empty else the script will fail.

A: If it is a lot of records, you can create a function and run it. The following does this until the end of the sheet, so make sure to delete all the rows towards the end which you do not need or adjust the range in the 2nd row.
function autoFillDown(){
  const range = SpreadsheetApp.getActiveSheet().getRange("A:A");
  const rows = range.getValues();
  let outputArray = [];

  rows.forEach( row => {
    // if it contains a name, leave it
    if( row[0].length > 1){
      outputArray.push( [row[0]] )
    // otherwise replace it with the value above it
    } else {
      outputArray.push( [outputArray[outputArray.length-1]] );
    }
  });
  range.setValues( outputArray );
}


text:
Q: Milnor's exercise: for any manifold $M$, $\mathrm{Hom}(C^\infty(M,\mathbb{R}),\mathbb{R})\cong M$ I am studying some chapters of Kolar-Michor-Slovak, Natural Operations in Differential Geometry, in particular the one on Weil bundles, where they present the famous "Milnor's exercise". They give two similar proofs, one much shorter than the other, supposedly because of omitted details. I would like to understand it better.
So we have to prove the:

Theorem For any manifold $M$, $\mathrm{Hom}(C^\infty(M,\mathbb{R}),\mathbb{R})\cong M$

Where $\mathrm{Hom}$ refers to morphisms of commutative unital algebras and $\cong$ to bijection of sets (I suppose).
Now the short proof goes like this:
Consider an homomorphism of algebras $C^\infty(M,\mathbb{R}\xrightarrow{\phi}\mathbb{R})$, by the usual short exact sequence argument, $\ker(\phi)\leq C^\infty(M,\mathbb{R})$ is an ideal of codimension $1$ (notice that such an homomorphism cannot be the zero map, since $\phi(1_\mathbb{R})=1\in\mathbb{R}$).
Now, consider the following system of subsets of $M$, where $V(f)=f^{-1}(0)$:
$$\{V(f)\mid (M\xrightarrow{f}\mathbb{R})\in \ker(\phi)\}$$
this is clearly a filter of closed sets of $M$, since $V(f^2+g^2)=V(f)\cap V(g)$.
Find a function $M\xrightarrow{f^*}\mathbb{R}\in \ker(\phi)$ which is unbounded on each non-compact closed subset of $M$ (for instance a positive proper function, such as the square of the geodesic distance w.r.t. any Riemannian metric).  Then $V(f^*)$ is a compact set contained in  $\bigcap_{f\in \ker(\phi)} V(f)$, which is then nonempty.
Let $x_0$ be one of its elements.
Then for any $f\in C^\infty(M,\mathbb{R})$ $f-\phi(f)1$ is in $\ker(\phi)$ so $(f-\phi(f)1)(x_0)=0$, and $\phi(f)=f(x_0)$.
So $x_0$ completely determines $\phi$ and the map $\phi\mapsto x_0$ is the desired bijection.
I have fetched the italicised details. What I am having trouble understanding is the bold passage. Moreover I don't see where we use the fact that the given system of sets is a filter and that $\ker(\phi)$ has codimension 1: I suspect these are relevant for the bold passage also.
Any help would be much appreciated.

A: First we observe that what we really need in the proof is that $\bigcap_{f \in \operatorname{ker}(\phi)} V(f)\ne  \emptyset$. The proof follows from that just as you written it. Now
$$V(f^*) \supset \bigcap_{f \in \operatorname{ker}(\phi)} V(f)=\bigcap_{f \in \operatorname{ker}(\phi)} V(f)\cap V(f^*),$$
so we can use the following characterization of compactness: Any collection of closed subsets of $V(f^*)$ with the finite intersection property has nonempty intersection.
Now we prove that each finite subset $\{V(f_i)\}_{i=1}^n\subset \ker \phi$ has non empty intersection. Otherwise $g:=\sum_i f_i^2>0$ and $g\in \ker \phi$. This can't be true because if $g$ is an invertible element then $1_\mathbb{R} \in \ker \phi$( Contradiction to $\ker \phi$ has codimension $1$).
We can conclude that $\bigcap_{f \in \operatorname{ker}(\phi)} V(f)=\bigcap_{f \in \operatorname{ker}(\phi)} V(f)\cap V(f^*)$ has a non empty intersection by the compactness of $V(f^*)$.
Some observations:
The hard part is to construct $f^*$ as this shows that ${f^*}^{-1}(0)$ is compact.
Another equivalent definition of compactness of a space $X$ is: Every filter on $X$ has a cluster point. You could probably use that for the proof. We have seen in the proof that I  imitate the same reasoning used ot show $\{V(f) \mid(M \stackrel{f}{\rightarrow} \mathbb{R}) \in \operatorname{ker}(\phi)\}$ is a filter. I was not confident enough with the definitions of filters to go in that direction.

A: This is a proof of the "hard part" mentioned in  @Elad's answer.
Lemma.  A smooth manifold $M$ admits a smooth real valued function $f$ such that
$$
  \lim_{x\to \infty }f(x) = \infty ,
  $$
(in the sense that for every $a>0$, there exists a compact subset $K\subseteq M$, such that $f(x)>a$, for every $x\in M\setminus
K$)
if and only if $M$ is $\sigma $-compact.
Proof. For the  "only if" part notice that,  given $f$ as above, one has that $f^{-1}((-\infty,a])$ is compact for every real
number $a$, and
$$
  M= \bigcup_{n\in \mathbb N}f^{-1}((-\infty,n]).
  $$
Conversely, let $\{K_n\}_{n\in \mathbb N}$ be a family of compact subsets of $M$  such that   $M= \bigcup_{n\in \mathbb N}K_n$.  By a
well known trick, based on the local compactness of $M$, we may assume WLOG that each $K_n$ is contained in the interior
of $K_{n+1}$.
By Lemma (1.3.2) in https://www.math.ucla.edu/~petersen/manifolds.pdf (Smooth Urysohn Lemma), for each $n$ in $\mathbb
N$ we may choose a nonegative smooth function $f_n$ vanishing on $K_n$ and taking on the value 1 on $M\setminus \text{int}(K_{n+1})$ (and
hence also on $M\setminus K_{n+1}$).
Defining
$$
  f(x) = \sum_{n=1}^\infty  f_n(x), \quad \forall x\in  M,
  $$
we claim that, for every $x$ in $M$,  there exists   a neighborhood $V$ of $x$,  and a natural number $m$, such that
$f_n=0$ on $V$, for every $n\geq m$.
To see this, find some $i$ such that $x\in  K_i$.   It then suffices to take
$V=\text{int}(K_{i+1})$ and $m=i+1$.
This said, it is clear that the  above function $f$ is well defined and smooth.
To see that  $\lim_{x\to \infty }f(x) = \infty $, observe that if $x\not\in  K_{m+1}$, then  surely $x\not\in K_{n+1}$, for  every $n\leq m$,  whence
$$
  f(x) \geq   \sum_{n=1}^m f_n(x) = m.
  $$
This completes the proof of the Lemma.  QED

Back to the question, let us assume that  $M$ is $\sigma $-compact, so we may pick  $f$  as in the
Lemma.
Setting
$$
  f^*=f-\phi(f)1,
  $$
one has  that $f^*\in \text{Ker}(\phi)$, and clearly also   $\lim_{x\to \infty }f^*(x) = \infty $, so we have that
$$
  V(f^*) =   {f^*}^{-1}(0)
  $$
is compact, as desired.


text:
Q: How to send two data to ajax I want to send two things to my ajax file. The first one is a formular (method POST) and the second is a simple string.
I can send the form like this :
$.post('ajaxDialog.php', $('#sol').serialize(),function(responseObject,ioArgs) ...

And it works but if I try to send two things like that :
$.post('ajaxDialog.php', {$('#sol').serialize(),simpleString},function(responseObject,ioArgs)

I have an error. So I tried to pass $('#sol').serialize() into an array :
var arrayForm = $('#sol').serialize();

I can't get the values of my form with $_POST['fieldName'] with this method. How should I do ?
Thanks !

A: serialize returns a url encoded query string, in the format: "key=val&anotherkey=anotherval" To append to it, just add your new key value pair, seperated by an ambersand &:
$.post('ajaxDialog.php',
       $('#sol').serialize()+"&somestring="+simpleString,
       function(responseObject,ioArgs){});


text:
Q: Beyond NARC: When to retain, when to assign, when to copy I finally understand whether I must release an object, and how to keep my retain counts as low as possible in a trivial application (by knowing whether the object comes back with an extra 'retain' already called or not). So the NARC rules are working pretty well in that regard.
On the other hand, I can't wrap my head around whether to retain (using retain properties, usually) or just assign instance variables. Are there any rules of thumb there? I know of only two:

*

*If I made the instance within my class (e.g., in an init), then I should retain it and release it in the dealloc.

*Delegates get assigned, not retained

But what I don't understand is whether I should retain stuff that I have passed from another instance. I know that the risk is that the retain count goes down to zero and I am left holding the bag (or left holding many extra bags and memory), but... how should I organize my application so that this doesn't happen?
I've seen some related questions, but nothing general.
While I'm Here: What about things that have been added to a UIWindow or UIView that I am not personally retaining? If their superview gets removed from all superviews, will the "naturally" retained instances get deallocated?

A:
how to keep my retain counts as low as possible

I don't understand this.  What makes you think you need to worry about retain counts at all?  The retain count is an implementation detail, forget about it.  All you need to worry about is whether you own an object.

I can't wrap my head around whether to retain (using retain properties, usually) or just assign instance variables.

In almost all cases you want to retain or copy when you assign instance variables.  The main exception is retain cycles.  Sometimes, you find yourself in a situation where object A has a reference to object B and object B has a reference to object A. If A retained B and B retained A, you cannot rely on the normal pattern of releasing references in dealloc to make them go away.  In this situation, it is usual to nominate one object as the owner and the other as the owned.  The owned object would then not retain its reference to the owner.
An example of this would be a tree structure where the parent node has references to its children and each child has a reference to its parent.  If each child retained its parent, when the application is done with the parent, it won't go away, because it has been retained by all its children.  So the parent reference is implemented as a weak reference which means that the child does not retain its parent.
It's a very common pattern with delegates for the owner of an object to set itself as the object's delegate.  For example, the controller of a table view is often also the table view's data source and/or delegate.  If the table view retained the delegate you would have a retain cycle (since the controller has already retained the view).  This is why the convention "delegates aren't retained" has arisen.
You should definitely copy if the object you want a reference to implements NSCopying and you need it not to change while you have ownership.  An example from Cocoa is the keys of elements in an NSDictionary.  If the keys were to change while in the dictionary, it would be a disaster.  So NSDictionary copies its keys.

I know that the risk is that the retain count goes down to zero and I am left holding the bag (or left holding many extra bags and memory), but... how should I organize my application so that this doesn't happen?

Simple: follow the Cocoa memory management rules.  If something goes away while you are holding a reference to it, you did not own that something.  If you need something to hang around for longer than the scope of the current method, you should retain it.

A: For class-type objects you want to:

*

*retain per default

*copy if the class is from a mutable/immutable class-cluster

*assign if you need weak references
As for cleanup, all retain and copy properties need to be released.

If I made the instance within my class (e.g., in an init), then I should retain it and release it in the dealloc.

The question isn't whether it was created in a method of your class, but whether you:

*

*want a strong reference to an instance

*already own it

If you don't own it yet and want a strong reference to it, retain - this is also true for instances passed into your methods. Whether you retain explicitly or implicitly through a setter doesn't matter.


text:
Q: Filter attributes of a class based on the type I would like to filter the attributes of an object of a class based on their types.
The answer will be something around inspect, "list comprehensions", type(), __dict__ and dict() but I don't get it working.
class A():
    def __init__(self, value):
        self.x = value

    def __str__(self):
        return "value = {}\n".format(self.x)

class T():
    def __init__(self):
        self.a1 = A(1)
        self.a2 = A(2)
        self.b = 4

t = T()

And I would like to print only the attributes of the type A in the class T
class T():
    def __init__(self):
        self.a1 = A(1)
        self.a2 = A(2)
        self.b = 4

    def __str__(self):
         ret = ""
         for i in [*magic*]:
             ret += str(i)
         return ret

Output should be something like:
value = 10
value = 15

A: You can use vars(self) to get a dictionary of the local attributes, then just test the values with isinstance():
def __str__(self):
    ret = ""
    for i in vars(self).values():
        if isinstance(i, A):
            ret += str(i)
    return ret

vars() essentially returns self.__dict__ here but is cleaner.
Turning this into a list comprehension for one-liner appeal:
def __str__(self):
    return ''.join([i for i in vars(self).values() if isinstance(i, A)])


text:
Q: "run the gamut"?
Russia's announcement that it had the bomb signaled the end of the era of the United States having what the secretary of war had called the royal straight flush. Predictably, the question of how to respond ran the gamut; even sober, humanitarian-minded scientists tried to figure out if the balance of rational thought had swung toward the idea of striking the Soviets preemptively. — Dan Carlin, The End Is Always Near

In this context, what does the phrase "ran the gamut" mean? I've found that to run the gamut from something to something can usually be paraphrased as to range from something to something. But I'm not sure if it's proper to apply that usage to this case.

A: The meaning of "ran the gamut" nearly equals your paraphrased meaning. It is usually considered a complete range. In this context, all the  possible responses were considered, with striking the Soviets preemptively as an extreme option that wouldn't have been considered in other contexts.
https://www.merriam-webster.com/dictionary/gamut


text:
Q: Laravel Event Fires but PHPUnit doesn't detect that it fired I am running a test to ensure my events are firing properly.
MyTest
/** @test */
public function foil_products_DO_trigger_oos_event ()
{
    $this->setUpTheWorld(true, 1);
    $response = $this->sendInStockData($this->pusher, Carbon::now()->subHour());

    $this->expectsEvents(\App\Events\InventoryOutOfStock::class);
    $this->sendCustomStockData($this->pusher, 0, 1, Carbon::now());

    // TEST THE RESULTS OF THE LISTENER FOR THAT EVENT
    $this->pusher = $this->pusher->fresh();
    $this->assertEquals(1, $this->pusher->oos);

    $this->assertCount(2, $this->pusher->inventories, "Pusher doesnt have 2 Inventories");
    $this->assertEquals(0, $this->pusher->latestInventory->tags_blocked);
}

If I comment out the line:
    $this->expectsEvents(\App\Events\InventoryOutOfStock::class);

Then my test will pass. The line:
    $this->assertEquals(1, $this->pusher->oos);

passes and this would only happen if the event fired. Additionally, I looked at my log file and I can guarantee that the event fired....
Is there anything I am doing wrong to tell PHPUnit that these events will be firing???
Thank you!
EventServiceProvider
class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        \App\Events\InventoryOutOfStock::class => [
            \App\Listeners\InventoryOutOfStockUpdater::class,
            \App\Listeners\EmailInventoryOutOfStockNotification::class,
            \App\Listeners\SMSInventoryOutOfStockNotification::class,
        ],
    ];

    /**
     * Register any other events for your application.
     *
     * @param  \Illuminate\Contracts\Events\Dispatcher  $events
     * @return void
     */
    public function boot(DispatcherContract $events)
    {
        parent::boot($events);
    }
}

A: Kind of an old question but I think previous answer doesn't really capture the issue.
The problem here is that you expect your event to fire and the listener to do something, while THIS WILL NOT HAPPEN here. Calling expectsEvent() asserts that the event fired but prevents listeners from firing, as official documentation states:

Laravel provides a convenient expectsEvents method that verifies the expected events are fired, but prevents any handlers for those events from running.

Read more: https://laravel.com/docs/5.2/testing#mocking-events
Try to simplify and separate your tests. Test either only that an event is fired, or that the listener does the what's expected, depending on complexity and separation of concerns.

A: I realize this is a pretty old question, but I just had this problem and I figured I would post the solution.
$this->expectsEvents($events)

doesn't work like an assertion. It doesn't assert anything until the very end. What is does is once it reaches that line, it expects that event to happen AFTER you've said you expected it.
TL;DR put the expectsEvents line at the top of your test method.
Here is a link to vague docs that don't really explain this, but they do say it. Kind of. https://laravel.com/docs/5.2/testing#mocking-events


text:
Q: How to add a column to a pyspark dataframe which contains the mean of one based on the grouping on another column It is similar to some other questions but it is different.
Let say we have a pyspark dataframe df as below:
+-----+------+-----+
|col1 | col2 | col3|
+-----+------+-----+
|A    |   5  |  6  |
+-----+------+-----+
|A    |   5  |  8  |
+-----+------+-----+
|A    |   6  |  3  |
+-----+------+-----+
|A    |   5  |  9  |
+-----+------+-----+
|B    |   9  |  6  |
+-----+------+-----+
|B    |   3  |  8  |
+-----+------+-----+
|B    |   9  |  8  |
+-----+------+-----+
|C    |  3   |  4  |
+-----+------+-----+
|C    |  5   |  1  |
+-----+------+-----+

I want to add another column as new_col which contains the mean of col2 based on grouping on col1. So, the answer must be as follows
   +-----+------+------+--------+
   |col1 | col2 | col3 | new_col|
   +-----+------+------+--------+
   |  A  |   5  |  6   | 5.25   |
   +-----+------+------+--------+
   |  A  |   5  |  8   | 5.25   |
   +-----+------+------+--------+
   |  A  |   6  |  3   | 5.25   |
   +-----+------+------+--------+
   |  A  |   5  |  9   | 5.25   |
   +-----+------+------+--------+
   |  B  |   9  |  6   | 7      |
   +-----+------+------+--------+
   |  B  |   3  |  8   | 7      |
   +-----+------+------+--------+
   |  B  |   9  |  8   | 7      |
   +-----+------+------+--------+
   |  C  |   3  |  4   | 4      |
   +-----+------+------+--------+
   |  C  |   5  |  1   | 4      |
   +-----+------+------+--------+

Any help will be appreciated.

A: Step 1: Creating the DataFrame.
from pyspark.sql.functions import avg, col
from pyspark.sql.window import Window
values = [('A',5,6),('A',5,8),('A',6,3),('A',5,9),('B',9,6),('B',3,8),('B',9,8),('C',3,4),('C',5,1)]
df = sqlContext.createDataFrame(values,['col1','col2','col3'])
df.show()
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   A|   5|   6|
|   A|   5|   8|
|   A|   6|   3|
|   A|   5|   9|
|   B|   9|   6|
|   B|   3|   8|
|   B|   9|   8|
|   C|   3|   4|
|   C|   5|   1|
+----+----+----+

Step 2: Creating another column having the mean, by grouping over column A.
w = Window().partitionBy('col1')
df = df.withColumn('new_col',avg(col('col2')).over(w))
df.show()
+----+----+----+-------+
|col1|col2|col3|new_col|
+----+----+----+-------+
|   B|   9|   6|    7.0|
|   B|   3|   8|    7.0|
|   B|   9|   8|    7.0|
|   C|   3|   4|    4.0|
|   C|   5|   1|    4.0|
|   A|   5|   6|   5.25|
|   A|   5|   8|   5.25|
|   A|   6|   3|   5.25|
|   A|   5|   9|   5.25|
+----+----+----+-------+

A: Ok, after a lot of trying, I could answer the question myself. I post the answer here for anyone else with the similar question. The original file is a csv file here.
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
#reading the file
df = spark.read.csv('file's name.csv', header=True)
df.show()

output
+-----+------+-----+
|col1 | col2 | col3|
+-----+------+-----+
|A    |   5  |  6  |
+-----+------+-----+
|A    |   5  |  8  |
+-----+------+-----+
|A    |   6  |  3  |
+-----+------+-----+
|A    |   5  |  9  |
+-----+------+-----+
|B    |   9  |  6  |
+-----+------+-----+
|B    |   3  |  8  |
+-----+------+-----+
|B    |   9  |  8  |
+-----+------+-----+
|C    |  3   |  4  |
+-----+------+-----+
|C    |  5   |  1  |
+-----+------+-----+

from pyspark.sql import functions as func
#Grouping the dataframe based on col1
col1group = df.groupBy('col1')
#Computing the average of col2 based on the grouping on col1
a= col1group.agg(func.avg("col2"))
a.show()

output
+-----+----------+
|col1 | avg(col2)|
+-----+----------+
| A   |   5.25   |
+-----+----------+
| B   |   7.0    |
+-----+----------+
| C   |   4.0    |
+-----+----------+

Now, we join the last table with the initial dataframe to generate our desired dataframe:
df=test1.join(a, on = 'lable', how = 'inner')
df.show()

output
   +-----+------+------+---------+
   |col1 | col2 | col3 |avg(col2)|
   +-----+------+------+---------+
   |  A  |   5  |  6   | 5.25    |
   +-----+------+------+---------+
   |  A  |   5  |  8   | 5.25    |
   +-----+------+------+---------+
   |  A  |   6  |  3   | 5.25    |
   +-----+------+------+---------+
   |  A  |   5  |  9   | 5.25    |
   +-----+------+------+---------+
   |  B  |   9  |  6   | 7       |
   +-----+------+------+---------+
   |  B  |   3  |  8   | 7       |
   +-----+------+------+---------+
   |  B  |   9  |  8   | 7       |
   +-----+------+------+---------+
   |  C  |   3  |  4   | 4       |
   +-----+------+------+---------+
   |  C  |   5  |  1   | 4       |
   +-----+------+------+---------+

Now change the name of the last column to whatever we want
df = df.withColumnRenamed('avg(val1)', 'new_col')
df.show()

output
   +-----+------+------+--------+
   |col1 | col2 | col3 | new_col|
   +-----+------+------+--------+
   |  A  |   5  |  6   | 5.25   |
   +-----+------+------+--------+
   |  A  |   5  |  8   | 5.25   |
   +-----+------+------+--------+
   |  A  |   6  |  3   | 5.25   |
   +-----+------+------+--------+
   |  A  |   5  |  9   | 5.25   |
   +-----+------+------+--------+
   |  B  |   9  |  6   | 7      |
   +-----+------+------+--------+
   |  B  |   3  |  8   | 7      |
   +-----+------+------+--------+
   |  B  |   9  |  8   | 7      |
   +-----+------+------+--------+
   |  C  |   3  |  4   | 4      |
   +-----+------+------+--------+
   |  C  |   5  |  1   | 4      |
   +-----+------+------+--------+


text:
Q: Homologous paths which are not homotopic I am new to homology and chains and such, so I am wondering whether my example is correct.
I have seen this question, but it seemed rather complicated, and I wanted to find a simple example without having to look at commutators and such.

Find an example of two closed curves $v$ and $w$, which are
    homologous (when regarded as 1-cycles), but are not homotopic.

The hint was to consider a surface, so I came up with the following.
Consider $X=\mathbb{C}\setminus\{\pm 1\}$ and consider the loops
  $$\gamma_\pm:[0,1]\rightarrow X,\quad
    \gamma_\pm(t)=\pm(e^{2\pi it}-1).$$
  Then $\gamma_\pm$ are closed paths starting and ending at $0$ and
  not homotopic.
Furthermore, regarding $\gamma_\pm$ and 1-chains, we have
  $$(\gamma_+-\gamma_-)(t)
    =(e^{2\pi it}-1)-(e^{2\pi it}-1)
    =0.$$
  Thus $\gamma_\pm$ are homologous.

A: You actually do not regard them as $1$-chains, but as functions $[0, 1] \rightarrow \mathbb C$ and use the additive structure on $\mathbb C$ to subtract them from each other. This is not what happens in homology: You add up their equivalence class in $H_1(X)$ by checking whether they bound a sum of $2$-chains.
The following example is pretty standard. Let $X = \Sigma_2$ (a two-holed torus). Then the curve around the "belly" of $X$ is null-homologous but not null-homotopic. You can probably convince yourself that it is not null-homotopic. It is null-homologous because it bounds a torus with a disk removed, which is a sum of $2$-chains (do you see why?).


text:
Q: Problema com o compartilhar Eu usei o seguinte código para capturar um texto e compartilhar.
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
String texto = "Olá sou um texto compartilhado"
sendIntent.putExtra(Intent.EXTRA_TEXT, texto);
sendIntent.setType("text/plain");
startActivity(sendIntent);

Quando executei a primeira vez ele abriu corretamente o compartilhar contendo todos os aplicativos. Quando eu executo novamente ele vai direto para o aplicativo que eu escolhi na primeira vez. É como se tivesse ficado salvo. Mas eu quero que ele abra sempre o compartilhar para escolher. Como resolver isso ?

A: Para resolver esse problema deve-se abrir  as opções de compartilhamento para se escolher com qual app quer compartilhar o texto. Dessa forma o código abaixo funciona para o que foi proposto.
Intent sendIntent = new Intent(Intent.ACTION_SEND);
String texto = "Olá sou um texto compartilhado";
sendIntent.putExtra(Intent.EXTRA_TEXT, texto);
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, "Share"));

A: Creio que está sendo armazenado em cache, pela minha pequena experiência, acredito que isso depende de Android pra Android, pois já vi alguns que somente marcam o ultimo utilizado. Meu app possui quase o mesmo código que você postou, no entanto com algumas pequenas modificações, mas que particularmente nunca vi ocorrer esse problema que mencionaste. Segue:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
String msg = "Sua mensagem aqui"
shareIntent.putExtra(Intent.EXTRA_TEXT, msg);
startActivity(shareIntent);

Se não resolver, então provavelmente deve ser o seu aparelho, ou melhor, o sistema do seu aparelho. Veja se quando foi selecionar o app pela primeira vez, se foi adicionado como sempre nas predefinições, logo, vá nas configurações do app que está iniciando e limpe as predefinições ou padrões (algo do tipo) e teste seu app em outros aparelhos e versões do Android.
Espero ter ajudado.


text:
Q: Check if a variable has been set with the name of the value of another variable I am setting up a template system, Long story short: I need/want to check if a variable with the name of a tag has been set. the tag name is in another variable.
Therefore, I need to check to see if the content of $tag (i.e. title) has a variable with the same name ($title).
Any help is appreciated. Thanks.

A: Use variable variables:
<?php

$tag = 'title';

// bool(false)
var_dump(isset($$tag));

$title = 'this is the title';

// bool(true)
var_dump(isset($$tag));


text:
Q: Django template filter keeps giving "unsupported operand type" I keep getting this error with my template filter:
"unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date'" I've looked at many other answers dealing with this error but I can't seem to find what's wrong. Any pointers much appreciated.
This is my template filter:
@register.filter(name='get_due_date_string')
def get_due_date_string(value):
    delta = value - date.today()

    if delta.days == 0:
        return "Today!"
    elif delta.days < 1:
        return "%s %s ago!" % (abs(delta.days),
            ("day" if abs(delta.days) == 1 else "days"))
    elif delta.days == 1:
        return "Tomorrow"
    elif delta.days > 1:
        return "In %s days" % delta.days

A: You can't get delta between datetime and date object.  You have to extract date from the datetime object:
delta = value.date() - date.today()


text:
Q: Connection between Boltzmann entropy and Kolmogorov entropy What is the connectivity between Boltzmann's entropy expression and Shannon's entropy expression? mentions a realtionship between Shannon entropy and Bolltzmann entropy. Is there a relationship between Kolmogorov Sinai entropy and Boltzmann entropy? And kolmogorov entropy and Shannon entropy?

A: This is a contentious question depending on the researcher answering and their background. Much of the available literature on the subject(s) will say that although the forms of these equations are similar, there is no relation between Shannon and Boltzman entropy.  The best treatment I've seen stems from E.T. Jaynes' classical paper on the subject and is presented by Arieh Ben-Naim in his book Farewell to Entropy.


text:
Q: How can I add a subtitle to a chapter and add it to the table of contents? I would like to add a subtitle to a chapter with the format \scshape and make it appear in the table of contents with the same format.
Something like this:


text:
Q: In-place quick-sort using random partition and only the array as argument I need to implement a quick-sort in java, when the following partition method is given:
private static int partition (int[] A, int low, int high)
{
int pivot, tmp, l, r;
pivot = low + qsr.nextInt(high - low + 1);
l = low;
r = high-1;
tmp = A[pivot];
A[pivot] = A[high];
A[high] = tmp;
pivot = high;
do
    {
    tmp = A[l];
    A[l] = A[r];
    A[r] = tmp;
    for(; l <= r && A[l] < A[pivot]; ++l)
        ;
    for(; l <= r && A[pivot] < A[r]; --r)
        ;
    }
while (l <= r);
tmp = A[l];
A[l] = A[pivot];
A[pivot] = tmp;
return l;
}

It chooses a random element from the array between the low and high index as pivot. Then the left side of the pivot is sorted so that it contains smaller values than the pivot, and the right side so that it contains only larger values. The sorting is done between the low and high values only. Finally, the index of the pivot is returned.
The quick-sort would be very easy to implement if the function took the low and high values as argument, but it doesn't:
 public static int[] quickSort (int[] table)
{return table;}

So it's a bit hairy problem. As I see it, I either have to create an array which stores the indexes or somehow split the array in place (not sure if possible), and then call the function recursively.
Any ideas how the algorithm can be created?


text:
Q: No puedo enviar variable POST con jquery AJAX necesito de vuestra ayuda. Mi problema es el siguiente:

*

*Necesito enviar un ID a través de una variable POST sin tener que hacerlo en un formulario.

He intentando con AJAX JQUERY pero no me funciona al momento de intentar rescatar la variable $_POST en mi archivo PHP no me la obtiene. Tengo el siguiente código pero no me esta funcionando, les dejo el código de mis archivos:
INDEX PHP
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Probando Jquery</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

ENVIAR VARIABLE POST JQUERY AJAX

      <input type="hidden" class="form-control d-none" id="inputName" value="1">
      <button class="btn btn-primary" id="btnEditar">editar</button>

  <?php require_once "controller.php"?>

JAVASCRIPT
    $(document).ready(function(){

    $("#btnEditar").click(function(){

        var dato = $("#inputName").val();
        alert(dato);

        $.ajax({
                url: 'controller.php',
                type: 'POST',
                data: {id_dato:dato},
                success: function(){
                   alert("Ha sido ejecutada la acción.");
                }
        });

    });
});

CONTROLLER.PHP
    <?php
    if(isset($_POST["id_dato"])){
        echo $_POST["id_dato"];
    }
?>

*

*En el archivo INDEX.PHP estoy ocupando un input oculto que tiene un value=1 ese value es el que necesito enviar como variable POST a mi archivo PHP.

espero haberme explicado bien, saludos.

A: 1.- revisa tu consola en el apartado de Red/xhr/encabezados y revisa si se esta enviando la variable id_dato=1.
2.- cambia
<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Probando Jquery</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

ENVIAR VARIABLE POST JQUERY AJAX

            <input type="hidden" class="form-control d-none" id="inputName" value="1">
            <button class="btn btn-primary" id="btnEditar">editar</button>

        <?php require_once "controller.php"?>

Por:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Probando Jquery</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

ENVIAR VARIABLE POST JQUERY AJAX

            <input type="hidden" class="form-control d-none" id="inputName" value="1">
            <button class="btn btn-primary" id="btnEditar">editar</button>

A: cambia
$(document).ready(function(){
    $("#btnEditar").click(function(){
        var dato = $("#inputName").val();
        alert(dato);
        $.ajax({
                url: 'controller.php',
                type: 'POST',
                data: {id_dato:dato},
                success: function(){
                   alert("Ha sido ejecutada la acción.");
                }
        });

    });
});

por
$(document).ready(function(){
    $("#btnEditar").click(function(){
        let url = "controller.php";
        var dato = $("#inputName").val();
        $.post(url, {'id_dato':dato}, function(data){
                alert( 'data')
            });
    });
});


text:
Q: ruby here documents I am trying to write a method in Ruby that uses a here-document of HTML code with input variables and fills them in accordingly.
My method is:
calcForm(left, op, right, result)

The html tags I am using are
<input type="text" name="left" value="?????">
<select name="op">
<option value="add" ?????>+</option>
<option value="mul" ?????>*</option>
</select>
<input type="text" name="right" value="?????">
=
?????

Everywhere there are question marks my method has to fill in with variables left, op, right, and result.
For example,
calcForm(6, "mul", 7, 42)

should return the string:
<input type="text" name="left" value="**6**">
<select name="op">
<option value="add">+</option>
<option value="mul" **selected**>*</option>
</select>
<input type="text" name="right" value="**7**">
=
**42**

So, the word "selected" should appear after "add" or "jul" depending on the value of op, the values of left and right should be filled in in value = "...", and the result should appear on the last line.
I am new to ruby but this is what I have done so far with my knowledge of here docs:
the_tags = <<HERE
<input type="text" name="left" value=#{left}>
<select name="op">
<option value="add" #{op}>+</option>
<option value="mul" #{op}>*</option>
</select>
<input type="text" name="right" value=#{right}>
=
#{result}
HERE

def calcForm(left,op,right,result)

I am stuck at this point. I am confused at how to connect my method calcForm to the here document above.
Any help with this would be greatly appreciated!
Thank you!

A: It looks like you're thinking of a heredoc as a sort of template, that you define once, with string interpolations built in, and then reuse.  It isn't.  As with any string definition, the string interpolation happens on the fly when the variable is defined.
So you would just do
def calcForm(left,op,right,result)
   <<HERE
     <input type="text" name="left" value=#{left}>
     <select name="op">
     <option value="add" #{op}>+</option>
     <option value="mul" #{op}>*</option>
     </select>
     <input type="text" name="right" value=#{right}>
     =
     #{result}
   HERE
end

However, a better approach for what you're trying to do might be ERB, which works more like what you had in mind above; i.e. it is a template.
require 'erb'
template = ERB.new <<HERE
         <input type="text" name="left" value=<%=left%>>
         <select name="op">
         <option value="add" <%=op%>>+</option>
         <option value="mul" <%=op%>>*</option>
         </select>
         <input type="text" name="right" value=<%=right%>>
         =
         <%=result%>
         HERE

def calcForm(left,op,right,result)
   template.result(binding)
end

Note that binding here is a magic word that means "evaluate the expression in the current context"; i.e. with the currently defined variables (the parameters that were passed in).

A: The easiest answer is to define and return the string inside your method, and use the parameter names as the interpolation variables.

A: This should work:
def calcForm(left,op,right,result)
  <<HERE
<input type="text" name="left" value="#{left}">
<select name="op">
<option value="add" #{'selected' if op == 'add'}>+</option>
<option value="mul" #{'selected' if op == 'mul'}>*</option>
</select>
<input type="text" name="right" value="#{right}">
=
#{result}
HERE
end

I added some quotes around your attributes to help with HTML validation.  You don't need to explicitly write return or declare a local variable because the return value of the method will always be the value of the last ruby expression.


text:
Q: Gnome 3 dependencies trouble I'm having trouble installing Gnome 3, from this web: http://oleeekchoff.blogspot.co.il/2011/10/gnome-3-on-gentoo.html
I already have Gnome 2, so i get this when i try to emerge -avuND world

Conflict: 7 blocks (4 unsatisfied)
!!! Multiple package instances within a single package slot have been pulled
!!! into the dependency graph, resulting in a slot conflict:
sys-fs/udev:0
(sys-fs/udev-171-r9::gentoo, installed) pulled in by

(sys-fs/udev-195::gentoo, ebuild scheduled for merge) pulled in by

=sys-fs/udev-187 required by (sys-fs/udev-init-scripts-17-r1::gentoo, ebuild scheduled for merge)
      (and 1 more with the same problem)

A: The conflict means that different packages are requiring different versions of sys-fs/udev. In your case for example, the version 171-r9 is the current version on your machine. Some other packages require version 195. The package udev-init-scripts requires version 187. Multiple versions of the same package are not allowed unless they are in the different slots.
When installing Gnome 3, there would be many packages that may require different versions of the same package. One walkaround is to use equery g <package> to check the packages it depends on, and equery d <package> to check which packages requires this package. Locate the package causing conflict and try removing some flags in /etc/portage/make.conf and /etc/portage/package.use, or masking some packages in /etc/portage/package.mask. Solving these conflicts when installing Gnome 3 is much fun compared to using it. Good luck.


text:
Q: Xcode 11 running on simulator failed with error Could not attach to pid I find a weird issue, every time when I close my WiFi, then Xcode command+R running my project on simulator will be failed with error like:
Details
Could not attach to pid : "1682"
Domain: IDEDebugSessionErrorDomain
Code: 3
Failure Reason: Error 1

Error 1
Domain: IDEDebugSessionErrorDomain
Code: 3

and when I open Wi-Fi, and connect to Internet, run on simulator will be fine.
My Xcode version:Version 11.3.1 (11C504)
OS: macOS Catalina 10.15.3 (19D76)
I have googled and found some similar issue like this one [https://forums.developer.apple.com/thread/120282
][1]
I tried all the solution I have googled, but none of them helped in any way.
Does anyone know how to solve this issue, or this is a bug of Xcode 11?
Thanks for any help!

A: clear data and restart Xcode it works for me.

A: Try running on a different simulator. That worked for me.
After that, I tried running on the previous simulator where I encountered the issue and it worked normally again.

A: Xcode 11.3.1: Restarting the Xcode resolved the issue.


text:
Q: Java web service client giving JaxWsClientProxy.invoke error I am working on a Java web service client development . I am using STS tool and Maven apache cxf plugin , Java 1.8. While executing it , I am getting following error for JaxWsClientProxy:
javax.xml.ws.soap.SOAPFaultException: Response message did not contain proper response data.
Expected: {<targetNameSpace>}ServerResponseMessage
    at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:161)
    at com.sun.proxy.$Proxy40.createdEndDeviceControls(Unknown Source)

In my pom.xml I have only added the cxf-spring-boot-starter-jaxws for version 3.2.4 dependency.
Can someone please let me know what is the reason for this error . The method createdEndDeviceControls exists in the corresponding Port
Please Help .
Best Regards,
Sudeshna Bhattacharya


text:
Q: Getting error while running Nutch on OSX mavrics I run the following command and I get an error of class not found. I tried run the following
$ bin/nutch crawl urls -dir crawl -depth 3 -topN 5
bin/nutch: line 106: [: too many arguments
Error: Could not find or load main class Course.Web
Apache Nutch Command Unable to Execute
I tried both the approaches from the above link but none of them worked.
I am using Nutch 1.7

A: If you are using Nutch 2.x .Command /bin/nutch crawl is deprecated. You should use /bin/crawl instead.

A: Solved the problem...
Folder name had a ' ' in it. that caused nutch crawl to not work.
After removing the space character from the folder name, it works fine now.


text:
Q: Storing multiple values in one column vs. Multiple columns for multiple values With regards to Performance & 'The proper way of doing things' and trying to figure out which way is better to store configuration data in a SQL database. Assume you have website configuration data for setting a minimum and maximum age that a person must be to access the site.
CREATE TABLE SiteConfig
(
  featureName varchar(100),
  value varchar(100),
)

Which is better:

*

*To store it all in a single row and process it in PHP with explode();.
featureName: "ageRequirement"
value: "13|60"

*To store it in separate rows for each feature and just SELECT the feature you need when needed.
featureName: "minAge"
value: "13"
featureName: "maxAge"
value: "60"
Due to the amount of features of the website, this is a difference of having 60 ROWS of data vs. about 25.

A: If those are values that you never will use by themselves in the database, either would work.
If you suspect that you would ever want to use the value in the database, you would not want them in the same value. That would make querying the data complicated and inefficient.

A: Store it has two separate features.
You may want to access the feature in the database, rather than in the application code.
There is no reason to parse a comma delimited string to get two features.
Admittedly, in the case of just two numbers separated by a comma, not much can go wrong.  This is, however, a slippery slope and you might soon find yourself trying to stuff multiple fields into a single string, and then devoting a lot of resources to parsing the string.


text:
Q: Uniform convergence of $f^2_n$ when $f_n$ converges uniformly Let $(f_n)$ be a sequence of functions that converge uniformly to $f$ on the interval $I$.
Prove or disprove: $f^2_n \to f^2$ uniformly on I.
I was almost certain this claim is false but was unable to construct any example. After several hours I started to try and prove it.
What i have so far is that if we can prove that $\sup_{x \in I}|f_n(f_n-f)| \ \to 0$ we're done. But after playing for another couple of hours with different functions i'm starting to believe it could be wrong.
I'm really at a loss here and any intuition i had about sequences seems to have been lost with this problem.

A: Let $f_n(x) = x+{1 \over n} $, $f(x) = x$. Then $f_n \to f$ uniformly, but
$f_n(n)^2-f(n)^2 = { 2 n^2 +1  \over n^2}$, hence the square does not converge uniformly.
By considering $f_n \circ \tan$, $f \circ \tan$ (and appropriate adjustments for the argument above), we can apply similar considerations to the open interval $(0,{\pi \over 2})$.

A: If $f_n+f $ is bounded, then $f_n^2-f^2=(f_n-f)(f_n+f) \rightarrow 0$ .


text:
Q: How to configure logging for rabbitmq queue interactions on Windows We need detailed traces for queue interactions in order to be able to resolve current development issues.
How that could be achieved?

A: I have figured it out. All that need to be done is bind another dummy queue to the same exchange poin and viola all messages get looged there and can be examined via management plug-in.


text:
Q: How to open multiple hrefs within a webtable to scrape through selenium I'm trying to scrape this website using python and selenium. However all the information I need is not on the main page, so how would I click the links in the 'Application number' column one by one go to that page scrape the information then return to original page?
Ive tried:
def getData():
  data = []
  select = Select(driver.find_elements_by_xpath('//*[@id="node-41"]/div/div/div/div/div/div[1]/table/tbody/tr/td/a/@href'))
  list_options = select.options
  for item in range(len(list_options)):
    item.click()
  driver.get(url)

URL: http://www.scilly.gov.uk/planning-development/planning-applications
Screenshot of the site:

A: To open multiple hrefs within a webtable to scrape through selenium you can use the following solution:

*

*Code Block:
  from selenium import webdriver
  from selenium.webdriver.chrome.options import Options
  from selenium.webdriver.support.ui import WebDriverWait
  from selenium.webdriver.common.by import By
  from selenium.webdriver.support import expected_conditions as EC

  hrefs = []
  options = Options()
  options.add_argument("start-maximized")
  options.add_argument("disable-infobars")
  options.add_argument("--disable-extensions")
  options.add_argument("--disable-gpu")
  options.add_argument("--no-sandbox")
  driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\ChromeDriver\chromedriver_win32\chromedriver.exe')
  driver.get('http://www.scilly.gov.uk/planning-development/planning-applications')
  windows_before  = driver.current_window_handle # Store the parent_window_handle for future use
  elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "td.views-field.views-field-title>a"))) # Induce WebDriverWait for the visibility of the desired elements
  for element in elements:
      hrefs.append(element.get_attribute("href")) # Collect the required href attributes and store in a list
  for href in hrefs:
      driver.execute_script("window.open('" + href +"');") # Open the hrefs one by one through execute_script method in a new tab
      WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2)) # Induce  WebDriverWait for the number_of_windows_to_be 2
      windows_after = driver.window_handles
      new_window = [x for x in windows_after if x != windows_before][0] # Identify the newly opened window
      # driver.switch_to_window(new_window) <!---deprecated>
      driver.switch_to.window(new_window) # switch_to the new window
      # perform your webscraping here
      print(driver.title) # print the page title or your perform your webscraping
      driver.close() # close the window
      # driver.switch_to_window(windows_before) <!---deprecated>
      driver.switch_to.window(windows_before) # switch_to the parent_window_handle
  driver.quit() #Quit your program

*Console Output:
  Planning application: P/18/064 | Council of the ISLES OF SCILLY
  Planning application: P/18/063 | Council of the ISLES OF SCILLY
  Planning application: P/18/062 | Council of the ISLES OF SCILLY
  Planning application: P/18/061 | Council of the ISLES OF SCILLY
  Planning application: p/18/059 | Council of the ISLES OF SCILLY
  Planning application: P/18/058 | Council of the ISLES OF SCILLY
  Planning application: P/18/057 | Council of the ISLES OF SCILLY
  Planning application: P/18/056 | Council of the ISLES OF SCILLY
  Planning application: P/18/055 | Council of the ISLES OF SCILLY
  Planning application: P/18/054 | Council of the ISLES OF SCILLY

References
You can find a couple of relevant detailed discussions in:

*

*WebScraping JavaScript-Rendered Content using Selenium in Python

*StaleElementReferenceException even after adding the wait while collecting the data from the wikipedia using web-scraping

*Unable to access the remaining elements by xpaths in a loop after accessing the first element- Webscraping Selenium Python

*How to open each product within a website in a new tab for scraping using Selenium through Python

*How to open multiple hrefs within a webtable to scrape through selenium

A: What you can do is the following:
import selenium
from selenium.webdriver.common.keys import Keys
from selenium import Webdriver
import time

url = "url"
browser = Webdriver.Chrome() #or whatever driver you use
browser.find_element_by_class_name("views-field views-field-title").click()
# or use this browser.find_element_by_xpath("xpath")
#Note you will need to change the class name to click a different item in the table
    time.sleep(5) # not the best way to do this but its simple. Just to make sure things load
#it is here that you will be able to scrape the new url I will not post that as you can scrape what you want.
# When you are done scraping you can return to the previous page with this
driver.execute_script("window.history.go(-1)")

hope this is what you are looking for.

A: When you navigate to new page DOM is refreshed and you cannot use list method here. Here is my approach for this action (I don't code much in python so syntax and indendation may be broken)
count = driver.find_elements_by_xpath("//table[@class='views-table cols-6']/tbody/tr") # to count total number of links
len(count)
j = 1
if j<=len:
    driver.find_element_by_xpath("//table[@class='views-table cols-6']/tbody/tr["+str(j)+"]/td/a").click()

    #add wait here
    #do your scrape action here

    driver.find_element_by_xpath("//a[text()='Back to planning applications']").click()#to go back to main page

    #add wait here for main page to load.
    j+=1


text:
Q: Angular app not working on iphone and some devices and has no error I deployed my angular app last week and it was working fine in all devices, i added pwa and google tag and noticed some users cannot load app and saw google tag error on console, i removed it and now all my pc browsers can load it correctly but cannot load it on my iphone (i cleared cache and also tried to use different isp) also users cannot load app without VPN
the weird thing is there is no error on console, i tried to push without --prod flag and even though loads as development mode dosent show any errors!
dependencies and asset groups in ngsw.config.json
{
  "$schema": "./node_modules/@angular/service-worker/config/schema.json",
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "resources": {
        "files": [
          "/favicon.ico",
          "/index.html",
          "/manifest.webmanifest",
          "/*.css",
          "/*.js"
        ],
        "urls": [
          "https://fonts.googleapis.com/**",
          "https://fonts.gstatic.com/**",
          "https://kit.fontawesome.com/*",
          "https://www.googletagmanager.com/**"
        ]
      }
    },
    {
      "name": "assets",
      "installMode": "lazy",
      "updateMode": "prefetch",
      "resources": {
        "files": [
          "/assets/**",
          "/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
        ]
      }
    }
  ],

package.json
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^11.2.14",
    "@angular/cdk": "^10.2.7",
    "@angular/common": "~11.2.8",
    "@angular/compiler": "~11.2.8",
    "@angular/core": "~11.2.8",
    "@angular/forms": "~11.2.8",
    "@angular/material": "^10.2.7",
    "@angular/platform-browser": "~11.2.8",
    "@angular/platform-browser-dynamic": "~11.2.8",
    "@angular/router": "~11.2.8",
    "@angular/service-worker": "~11.2.8",
    "@ngrx/effects": "^11.1.1",
    "@ngrx/entity": "^11.1.0",
    "@ngrx/router-store": "^11.1.0",
    "@ngrx/store": "^11.1.1",
    "angular-datatables": "^12.0.0",
    "bootstrap": "^4.6.0",
    "chart.js": "^2.9.3",
    "datatables.net": "^1.10.24",
    "datatables.net-bs4": "^1.10.20",
    "datatables.net-buttons": "^1.7.0",
    "datatables.net-buttons-dt": "^1.7.0",
    "datatables.net-dt": "^1.10.24",
    "datatables.net-searchbuilder-dt": "^1.0.1",
    "html2canvas": "^1.1.1",
    "jquery": "^3.6.0",
    "jszip": "^3.6.0",
    "ng2-charts": "^2.3.0",
    "popper.js": "^1.16.1",
    "rxjs": "~6.5.5",
    "swiper": "^6.6.2",
    "tslib": "^2.0.0",
    "zone.js": "~0.10.3"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.1102.7",
    "@angular/cli": "~11.2.7",
    "@angular/compiler-cli": "~11.2.8",
    "@ngrx/store-devtools": "^11.1.1",
    "@types/datatables.net": "^1.10.19",
    "@types/datatables.net-buttons": "^1.4.5",
    "@types/jasmine": "~3.6.0",
    "@types/jasminewd2": "~2.0.3",
    "@types/jquery": "^3.5.5",
    "@types/node": "^12.11.1",
    "codelyzer": "^6.0.0",
    "jasmine-core": "~3.6.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~6.3.2",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~3.0.2",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "protractor": "~7.0.0",
    "ts-node": "~8.3.0",
    "tslint": "~6.1.0",
    "typescript": "~4.1.5"
  }

A: Don't know if this will help, but I had the same problem where my login feature wouldn't work on some devices.
What had happened was, I was using string.prototype.replaceAll() but it seems that string.prototype.replaceAll() is not available on the browser version on my iPhone. So I changed .replaceAll() with .replace() and it worked. So for you, I'm guessing you're using a method that's not supported by the browser version on your iPhone.


text:
Q: Installing Rails 4.2.0.beta1 – Bundler could not find compatible versions for gem "sprockets-rails" I've attempted to install Rails 4.2.0.beta1 (released Aug 20, 2014). I get an error Bundler could not find compatible versions for gem "sprockets-rails". Here are the details:
$ bundle update rails
Fetching gem metadata from https://rubygems.org/.........
Fetching additional metadata from https://rubygems.org/..
Resolving dependencies...
Bundler could not find compatible versions for gem "sprockets-rails":
  In Gemfile:
    sass-rails (~> 4.0.3) ruby depends on
      sprockets-rails (~> 2.0) ruby

    rails (= 4.2.0.beta1) ruby depends on
      sprockets-rails (3.0.0.beta1)

How can I install Rails 4.2.0.beta1?

A: You have a sass-rails gem in your Gemfile. You need to change the version of sass-rails to '5.0.0.beta1'. And then run bundle update sass-rails rails.
You could find some useful info at this sprockets-rails issue.
P.S.: Moreover I have the same problem with rails_admin which I reported here.


text:
Q: What is the equivalent NSBox from AppKit to be used in Cocoa Touch environment? Is there a similar to NSBox class from AppKit for MAC in UIKit for iPad?

A: Not really. You will have to customize a UIView, but its not that hard. You can easily make a UIView that looks completely identical, and the best part is that when you remove the uiview, all the containing items inside it are removed.
in effect, all items (like uibutton and uiscrollview) are actually children of UIview.